On March 26, 2019 we launched new MODX Forums. Please join us at the new MODX Community Forums.
Subscribe: RSS
  • With plugin what I have mentioned is safe to use future releases of MODX Revo (upgrades) and I think it's better solution than "hacking" core. ;-)
      Freelance Web Developer who likes MODX, PHP, jQuery, ExtJS, SASS and other cool web things. Currenty doing great stuff at COEX CZ.

      GitHub: https://github.com/hansek
      Follow me: https://twitter.com/jantezner
      Or follow us: https://twitter.com/coexcz

      http://www.modx.cz || http://www.coex.cz
    • Thanks!
      I'm testing it,
      actually my customer is scared by the unique_id() suffix,
      but I think there is no other way to avoid overwriting files... smiley

        TilliLab | MODX Ambassador
        website
      • not sure, but is this now included in the new update 2.2.3 ??

        MODX Revolution 2.2.3-pl (June 13, 2012)
        ====================================
        - [#8051] Added extra sanitization for modFileHandler.sanitizePath
          Revolution 2.2.6
        • Coming from this thread here: http://forums.modx.com/thread/80676/german-umlauts-and-blanks-in-image-names-and-paths#dis-post-444589

          I was very happy to find all that different approaches to this problem. So thank you guys!

          @manfred: no, I don't think that this fix has something to do with the issue discussed here, but correct me if I'm wrong!

          I searched for the plugin mentioned earlier in this thread, but couldn't find it anymore under the link that susan posted and found it here again: https://github.com/benjamin-vauchel/SanitizeFilename

          I just copy & pasted the plugin itself to a modx installation of mine, but the transliteration did not work and I also like it more to replace spaces/unwanted chars with an underline and I also didn't need the added uniqeid, so I began to dig into the code a bit and came up with the following, rewritten plugin, which works quite well until now (not really tested intensively, but it shouldn't make problems...hopefully...if it does, please report it to me...)...ah, and I renamed it to SanitiX =))

          <?php
          /**
           * MODx SanitiX sanitize filename plugin for the file manager upload process
           *
           * @author exside
           * @credits:
           * 		- Based on the code of the sanitizefilename plugin of Benjamin Vauchel https://github.com/benjamin-vauchel/SanitizeFilename
           * 		- The Slug() phunction of AlixAxel https://github.com/alixaxel/phunction/blob/master/phunction/Text.php
           * @version Version 1.1
           * @modified 26.11.2012
           *
           * @description 
           * Remove unwanted characters from uploaded filenames and replace accented-characters with "normal" ones based on transliteration & language
           * Example : a file with the following name "gäñz leidä file#nàmä mît jéglèçhem shì@t w0mä n!d sött.png" 
           * will be "gaenz_leidae_file_namae_mit_jeglechem_shi_t_w0mae_n_d_soett.png" (in a german environment with culturKey 'de')
           *
           * If a file already exists (with the sanitized filename), _duplicate is attached to the filename
           *
           * You can change the character that is used to replace spaces and special chars by specifing it in the $slug variable below, defaults to _
           *
           * Events: OnFileManagerUpload
           *
           * @package SanitiX
           */
          
          // Cleaning function
          if ( !function_exists('cleanFilename')) {
          	function cleanFilename($modx, $filename, $slug) {
          
          		// trim, lowercase, replace special chars, transliterate
          		if (function_exists('iconv')) {
          			// iconv somehow doesn't work without this and it doesn't sem to be set by modx
          			setlocale(LC_ALL, strtolower($modx->getOption('cultureKey')) . '_' . strtoupper($modx->getOption('cultureKey')));
          			
          			$filename = strtolower(trim(preg_replace('~[^0-9a-z' . preg_quote(null, '~') . ']+~i', $slug, iconv('UTF-8', 'ASCII//TRANSLIT', $filename)), $slug));
          			
          			//$modx->log(modX::LOG_LEVEL_ERROR, '[SanitiX] transliteraded filename: ' . $filename);
          		} else {
          			$modx->log(modX::LOG_LEVEL_ERROR, '[SanitiX] No iconv functions available, cannot transliterate the filename, that\'s why it looks ugly');
          
          			$filename = strtolower(trim(preg_replace('~[^0-9a-z' . preg_quote(null, '~') . ']+~i', $slug, $filename), $slug));
          		}
          
          		if ( empty($filename) ) {
          			return 'noname';
          		}
          
          		return $filename;
          	}
          }
          
          // We rename each of the uploaded files
          foreach( $files as $file ) {
          	if ( $file['error'] == 0 ) {
          		$slug = '_';
          		$pathInfo = pathinfo($file['name']);
          		$basePath = $source->getBasePath();
          
          		$oldPath = $directory . $file['name'];
          		
          		$newPath = cleanFilename($modx, $pathInfo['filename'], $slug) . '.' . $pathInfo['extension'];
          		
          		if ( file_exists($basePath . $directory . $newPath) ) {
          			$newPath = cleanFilename($modx, $pathInfo['filename'], $slug) . '_duplicate.' . $pathInfo['extension'];
          		}
          
          		$source->renameObject($oldPath, $newPath);
          	} else {
          		$modx->log(modX::LOG_LEVEL_ERROR, '[SanitiX] There was an error during the upload process...');
          	}
          }
          



          hope it will be helpful to somebody! Improvements and suggestions are always welcome =) [ed. note: exside last edited this post 7 years, 11 months ago.]
          • Hi, I'm using your plugin, thanks smiley
            the only problem is that the filename is always changed with "duplicate", even if it doesn't exist...

            May be it depends on the media source?

              TilliLab | MODX Ambassador
              website
            • Yes, I have actually also noticed this, but not on a regular basis, it's strange^^...seems to be dependent from where the file gets uploaded (through file-tab or through or via image tv or so...), but I actually didn't have time to dig into this, so if you see where the problem lies, tell me =)!
              • Well, I did some test.. I think the problem is that plugin is executed "after" that the file has been uploaded.

                So, if the original filename doesn't need to be renamed, you will always satisfy the condition:

                 if ( file_exists($basePath . $newPath) ) { ...


                it would be best to store file in a temporary folder or to execute the plugin before uploading the file.

                Otherwise the only solution is to use unique_id() as the original plugin of Hansek does...

                  TilliLab | MODX Ambassador
                  website
                • I've put in a feature request for an "OnBeforeFilemanagerUpload" event that fires just before the move_uploaded_file() PHP function is run. I have also had problems with non-ascii characters in filenames uploaded by the public; in Windows the files are saved according to whatever the default Windows charset is, and that is rarely utf-8, so a link to the file based on the filename in a utf-8 MODx will fail to find the file, since its filename is based on whatever charset Windows used when moving the file. Plus there is the occasional need to report that a file of that name already exists, and offer options as to what to do about it.
                    Studying MODX in the desert - http://sottwell.com
                    Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
                    Join the Slack Community - http://modx.org