pepebe
7/11/2015 - 2:18 PM

Transliteration plugin for the file manager upload process.

Transliteration plugin for the file manager upload process.

<?php
/**
 * ppb_translitFilennames 
 * 
 * Translit filename plugin for the file manager upload process.
 * 
 * Example: Rename "Straßenbeleuchtung über Hamburg".jpg to "strassenbeleuchtung_ueber_hamburg.jpg"
 * 
 * Usage: 
 * 1. Install translit package by Jason Coward: http://modx.com/extras/package/translit
 * 2. Set friendly_alias_translit to german (or russian). Hint use small caps...
 * 3. Trigger plugin OnFileManagerUpload
 *
 */

$debug = true;
$copy = '_kopie'; // suffix the filename, if a file alreadyy exists.

/* No need to change anything below this line */

$pluginName = '[ppb_translitFilennames]';

if(!function_exists('debug')){
    function debug($msg){
        global $modx;
        $modx->log(modX::LOG_LEVEL_ERROR, $msg);
    }
}

$classPath = MODX_CORE_PATH . 'components/translit/model/modx/translit/';
$className = 'modtransliterate';

$modx->getService( 'translit' , $className , $classPath);

if(!class_exists('modTransliterate')){
    debug($pluginName . ' ' . $className .' could not be found in ' . $classPath);
    return;
}

$modTransliterate = new modTransliterate($modx,array());

$lang = $modx->getOption('friendly_alias_translit',null,'german');

if($debug){
    debug($pluginName . ' use transliteration for ' . $lang);
}

// Rename each uploaded file and check for duplicates
foreach( $files as $file ) 
{
    if ( $file['error'] == 0 ) 
    {
        $pathInfo = pathinfo($file['name']);
        
        $filename  = $pathInfo['filename'];
        $extension = $pathInfo['extension'];
        
        $basePath = $source->getBasePath();
 
        $oldPath = $directory . $file['name'];
        $newPath = $modTransliterate->translate( $filename, $lang ) . '.' .$extension;
         
        if ( file_exists($basePath . $directory . $newPath) ) {
            $newPath = $modTransliterate->translate( $filename , $lang ) . $copy . '.' . $extension;
        }
 
        $newPath = trim(str_replace(' ', '_' , $newPath));
 
        $source->renameObject($oldPath, $newPath);
        
        if($debug){
            debug($pluginName . ' Renamed file from ' . $oldPath . ' to ' . $newPath);
        }
    } 
    else 
    {
        debug($pluginName . ' There was an error during the upload process...');
    }
}