TriAnMan / filetranslit

Filename transliteration module for MODX
2 stars 2 forks source link

How I can get file extension? #2

Closed skazhikadyadya closed 10 years ago

skazhikadyadya commented 10 years ago

Hello. I try to modify your nice plugin: target file must be seen as "ve197-j7bmi-hmkr0-yxwdm-4r332.jpg" (or .png, .gif). How I can do it? I try to add this function to your plugin:

function rand_string($len, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
{
    $string = '';
    for ($i = 0; $i < $len; $i++)
    {
        $pos = rand(0, strlen($chars)-1);
        $string .= $chars{$pos};
    }
    return $string;
}

...and modify

$newName = $currentdoc->cleanAlias(rand_string(5)."-".rand_string(5)."-".rand_string(5)."-".rand_string(5)."-".rand_string(5));

Then I get uploaded file without extension. :( How I can correct this problem? Thank you!

TriAnMan commented 10 years ago

You could refer to MODx documentation. As you can see cleanAlias is a method of the modResource class.

skazhikadyadya commented 10 years ago

With the power of Ktulhu I do that:

<?php
$currentdoc = $modx->newObject('modResource');
foreach ($files as &$file) {

function rand_string($len, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
{
    $string = '';
    for ($i = 0; $i < $len; $i++)
    {
        $pos = rand(0, strlen($chars)-1);
        $string .= $chars{$pos};
    }
    return $string;
}

    if ($file['error'] == 0) 
    {
        $newName = rand_string(5) . "-" . rand_string(5) . "-" . rand_string(5) . "-" . rand_string(5) . "-" . rand_string(5);
        //file rename logic
        if ($file['name'] !== $newName) 
        {
            $arDirFiles = $source->getObjectsInContainer($directory);
            foreach ($arDirFiles as &$dirFile){
                if($dirFile['name']===$newName){
                    //delete file if there is one with new name
                    $source->removeObject($directory . $newName);
                }
            }

            $ext = strtolower(strrchr($file['name'], '.'));
            $source->renameObject($directory . $file['name'], $newName . $ext);

        }
    }
}

Works nice. Thank you.

TriAnMan commented 10 years ago

Your code has a minor bug. But it's ok, if it suits you.