WordPress.org

Forums

UploadPlus : File Name Cleaner
Consider som logic and fixes (4 posts)

  1. Jonas Lundman
    Member
    Posted 1 year ago #

    Hi, This is a great base plugin!

    My projects love it, and I need it to work while waiting for update. Thanks for your nice work with this plug!

    To get this plugin to work for a lot of customers I did the following tweaks and suggest some logic for updates to the authors. I run it on diffrent 50 blogs, langs, and with those changes, my clients don complain any more about their filenames... This is only suggestions, cant use github, so posting here for any one to use.

    First, the order of cleanup self::functions

    If I choose to replace all lowercase with "-" as separator I don wanna end up with :

    My-blognamephoto_1234-.jpg

    instead

    my-blogname-photo-1234.jpg

    The separator would be consistant and also replace old separator like "_" in this case.

    By changing the order of the cleanup functions

    $file_name = self::_clean_global( $file_name );
                $file_name = self::_add_prefix( $file_name ); // QQ
                $file_name = self::_clean_filename( $ext, $file_name );
                $file_name = self::_clean_case( $file_name );
                //$file_name = self::_add_prefix( $file_name ); // QQ Moved up

    And reverse the separators cases :

    switch( $cleanlevel[0] ):
    			case "dash":
    			default:
    				$file_name = preg_replace ('/[-\s]+/', '-', $file_name);
    				$file_name = str_replace('_', '-', $file_name); // QQ
    				$sep = "-";
    				break;
    			case "space":
    				$file_name = preg_replace ('/[-\s]+/', ' ', $file_name);
    				$file_name = trim($file_name); // QQ
    				$sep = "-";
    				break;
    			case "underscore":
    				$file_name = preg_replace ('/[-\s]+/', '_', $file_name);
    				$file_name = str_replace('-', '_', $file_name); // QQ
    				$sep = "_";
    				break;
    			endswitch;

    ...adds a more logic for most users.

    Second, The functions are renundant

    For all the filename cleaning handling, I suggest running by wp core sanitize_file_name() means, other plugin like Enable Replace Media, buddypress etc etc get cleaned by Upload plus.

    wp_handle_upload() is using wp_handle_upload_prefilter() AND wp_unique_filename() and the latter is using sanitize_file_name()

    So instead of using add_action for wp_handle_upload(), and rewrite the file all over again, just focus on sanitize_file_name(), and then skip option "B" wp_unique_filename(). Its already parsed. Safe and WP style.

    Finally,

    I added an option to add date taken by camera as prefix if custom prefix is set to exif. Many clients need to know when they actually took the picture... This is the only reason to still use wp_handle_upload_prefilter().

    Dots, are preserved, for ex upload-plus-v-1.2.3.zip but not for images, so they dont endup with upload-plus-image.bmp.jpeg or files with dubble dots like upload-plus-revision-1..2.3.doc

    Summary : in uploadplus.php

    function __construct() {
                #$core = new SWER_uploadplus_core();
                add_action( 'admin_init', array( &$this, '_admin_init' ) );
                add_action( 'wp_handle_upload_prefilter', array( 'SWER_uploadplus_core', 'wp_handle_upload_prefilter' ), 1, 1);
                add_action( 'add_attachment', array( 'SWER_uploadplus_core', 'add_attachment') );
                add_filter( 'sanitize_file_name', array( 'SWER_uploadplus_core', 'sanitize_file_name') );
            }

    The rest of tweaks in core.class.php

    // bottom of _add_prefix function
    $custom = get_option('uploadplus_customprefix');
                if( $custom !== '' ):
    				if(strtolower($custom) == 'exif'){
    					$return_file_name = $file_name;
    				} else {
    					if(isset($GLOBALS['UPLOAD-PLUS-EXIF'])) unset($GLOBALS['UPLOAD-PLUS-EXIF']);
    					$return_file_name = $custom.$sep.$file_name; // QQ Separator added
    				}
                else:
                    $return_file_name = $file_name;
                endif;

    AND

    function wp_handle_upload_prefilter( $arr ){
                //$name = self::upp_mangle_filename( $arr['name'] );
    			if(isset($GLOBALS['UPLOAD-PLUS-EXIF'])) unset($GLOBALS['UPLOAD-PLUS-EXIF']);
    			//QQ
    			if ( is_callable('exif_read_data') && $arr['type'] == 'image/jpeg' ) {
    				$exif = exif_read_data($arr['tmp_name'], 0, true);
    				foreach (array('DateTimeDigitized', 'DateTimeOriginal', 'FileDateTime') as $key) {
    					if (isset($exif['EXIF'][$key]) && trim($exif['EXIF'][$key])) {
    						$prefix = trim($exif['EXIF'][$key]);
    					}
    				}
    				if(isset($prefix)) {
    					list($date, $time) = explode(' ', $prefix);
    					list($y, $m, $d) = explode(':', $date);
    					$prefix = "{$y}-{$m}-{$d}";
    					$GLOBALS['UPLOAD-PLUS-EXIF'] = $prefix;
    					unset($prefix);
    				}
    			}
    			return $arr;
            }

    AND

    function sanitize_file_name( $filename, $filename_raw ){
    			global $sep;
    			$new_name = self::upp_mangle_filename($filename);
    			if(isset($GLOBALS['UPLOAD-PLUS-EXIF'])) {
    				$new_name = $GLOBALS['UPLOAD-PLUS-EXIF'].$sep.$new_name;
    				unset($GLOBALS['UPLOAD-PLUS-EXIF']);
    			}
    			return $new_name;
            }

    AND THE ugly but working dots fix

    function _clean_filename( $ext, $file_name ){
            	$file_name = str_replace('.'.$ext, '', $file_name);
            	if(in_array(strtolower($ext), array('jpg', 'tiff', 'jpeg', 'tif', 'png', 'bmp', 'gif') ) ) $file_name = str_replace('.', '-', $file_name);
    				else $file_name = str_replace('.', 'qQQppQQq', $file_name);
    			$file_name = str_replace('qqQQppQQ', '', $file_name);
                $file_name = preg_replace('~[^\\pL0-9_]+~u', '-', $file_name);
        		$file_name = preg_replace ('/^\s+|\s+$/', '', $file_name);
    			$file_name = str_replace('qQQppQQq', '.', $file_name);
            	$file_name = $file_name.'.'.$ext;
    
            	return $file_name;
            }

    AND AT LAST

    The add_attachment() action has never worked ok, so I replaced it by adding a filter call. The same filter can be use consistant by other plugin, like rename files, buddypress m.m. So I just wanna decide overall what also upload plus should do with the attachment title name.

    function add_attachment( $id ){
    
    			$obj = get_post( $id );
    			$title = $obj->post_title;
    
    			$title = apply_filters( 'upload_plus_add_attachment_title', $title );
    
    			// Update the post into the database
    			$uploaded_post = array();
    			$uploaded_post['ID'] = $id;
    			$uploaded_post['post_title'] = $title;
    			wp_update_post( $uploaded_post );
    
    			return $id;
    
            }

    in my theme functions.php

    function ua_sanitize_file_title($title){
    	$char_array = array();
    	$char_array[] = '-';
    	$char_array[] = '_';
    	//$char_array[] = '.';
    	$char_array[] = '~';
    	$char_array[] = '+';
    
    	$title = str_replace($char_array, ' ', $title );
    	$title = preg_replace("/\s+/", " ", $title);
    	$title = str_replace(array('.jpg', '.tiff', '.jpeg', '.tif', '.png', '.bmp', '.gif'), '', $title);
    	$title = ucfirst( strtolower( $title ) );
    	return $title;
    }
    add_filter( 'upload_plus_add_attachment_title', 'ua_sanitize_file_title');

    Be my guest!

    http://wordpress.org/extend/plugins/uploadplus/

  2. Paolo T. (pixline)
    Member
    Plugin Author

    Posted 1 year ago #

    Wow. I've dreamed for a bug report like that for YEARS, literally. Thank you Jonas (and please excuse our lag as well)!

    I'm going to review code and reply as soon as I can, I'd love to fix those things in the next release (~ 1 week later WP 3.6).

    Please feel free to follow uploadplus public Github repository: I'm going to add this report as a trackable issue, if you have a github account please chime in, you're welcome!

  3. Paolo T. (pixline)
    Member
    Plugin Author

    Posted 1 year ago #

    This and other fixes have been pushed to Github. We'll review and test them in the next days (I'm actually mobile-coding, sorry :).

    Feel free to download the repository version and test in your localhost(not on production, please!), fork it and send pull requests if you are used to it (or learn how to do it as we're doing :)

  4. Paolo T. (pixline)
    Member
    Plugin Author

    Posted 1 year ago #

    Have been diggin the code, looks like your modification were made on a previous uploadplus version than 3.2.1. Apart from that I'm including each modification and testing it with a new comprehensive setup on Travis CI. Here's some details:

    # cleanup ordering
    Looks it's working, I need to write better unit test.

    # function redundancy
    This is the very legacy of uploadplus: sanitize_file_name was out with WP 2.1, plugin born well before that. I didn't noticed it 'till now, though. I'd better audit the code often.

    # EXIF data
    Really nice idea, but I need to tweak it a bit and make it an option.

    Really thank your for sharing!

Topic Closed

This topic has been closed to new replies.

About this Plugin

  • UploadPlus : File Name Cleaner
  • Frequently Asked Questions
  • Support Threads
  • Reviews

About this Topic