source: tags/2.1.5/lib/Upload.inc.php

Last change on this file was 377, checked in by quinn, 14 years ago

Releasing trunk as stable version 2.1.5

File size: 30.7 KB
RevLine 
[1]1<?php
2/**
[362]3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
[376]5 * Copyright 2001-2010 Strangecode, LLC
[362]6 *
7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/**
[42]24 * Upload.inc.php
[20]25 *
[1]26 * The Upload class provides an interface to deal with http uploaded files.
27 *
28 * @author  Quinn Comendant <quinn@strangecode.com>
29 * @requires App.inc.php
[119]30 * @version 1.4
[1]31 */
32
[119]33// Upload error types.
34define('UPLOAD_USER_ERR_EMPTY_FILE', 100);
35define('UPLOAD_USER_ERR_NOT_UPLOADED_FILE', 101);
36define('UPLOAD_USER_ERR_INVALID_EXTENSION', 102);
37define('UPLOAD_USER_ERR_NOT_UNIQUE', 103);
38define('UPLOAD_USER_ERR_MOVE_FAILED', 104);
[37]39
[1]40class Upload {
[42]41
[1]42    // General object parameters.
43    var $_params = array(
[42]44
[37]45        // Which messages do we pass to raiseMsg?
[119]46        'display_messages' => MSG_ALL,
[42]47
[20]48        // Existing files will be overwritten when there is a name conflict?
[1]49        'allow_overwriting' => false,
[20]50
51        // The filesystem path to the final upload directory.
52        'upload_path' => null,
53
54        // The file permissions of the uploaded files. Remember, files will be owned by the web server user.
55        'dest_file_perms' => 0600,
56
[121]57        // The file permissions of the uploaded files. Remember, files will be owned by the web server user.
58        'dest_dir_perms' => 0700,
59
[334]60        // Require file to have one of the following file name extensions.
[20]61        'valid_file_extensions' => array('jpg', 'jpeg', 'gif', 'png', 'pdf', 'txt', 'text', 'html', 'htm'),
[1]62    );
63
64    // Array of files with errors.
65    var $errors = array();
[20]66
[22]67    // Array of file name extensions and corresponding mime-types.
[203]68    var $mime_extension_map = array( 'ez' => 'application/andrew-inset', 'hqx' => 'application/mac-binhex40', 'cpt' => 'application/mac-compactpro', 'doc' => 'application/msword', 'bin' => 'application/octet-stream', 'class' => 'application/octet-stream', 'dll' => 'application/octet-stream', 'dms' => 'application/octet-stream', 'exe' => 'application/octet-stream', 'lha' => 'application/octet-stream', 'lzh' => 'application/octet-stream', 'so' => 'application/octet-stream', 'oda' => 'application/oda', 'pdf' => 'application/pdf', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'smi' => 'application/smil', 'smil' => 'application/smil', 'mif' => 'application/vnd.mif', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', 'sxc' => 'application/vnd.sun.xml.calc', 'stc' => 'application/vnd.sun.xml.calc.template', 'sxd' => 'application/vnd.sun.xml.draw', 'std' => 'application/vnd.sun.xml.draw.template', 'sxi' => 'application/vnd.sun.xml.impress', 'sti' => 'application/vnd.sun.xml.impress.template', 'sxm' => 'application/vnd.sun.xml.math', 'sxw' => 'application/vnd.sun.xml.writer', 'sxg' => 'application/vnd.sun.xml.writer.global', 'stw' => 'application/vnd.sun.xml.writer.template', 'vsd' => 'application/vnd.visio', 'wbxml' => 'application/vnd.wap.wbxml', 'wmlc' => 'application/vnd.wap.wmlc', 'wmlsc' => 'application/vnd.wap.wmlscriptc', 'bcpio' => 'application/x-bcpio', 'vcd' => 'application/x-cdlink', 'pgn' => 'application/x-chess-pgn', 'Z' => 'application/x-compress', 'cpio' => 'application/x-cpio', 'csh' => 'application/x-csh', 'dcr' => 'application/x-director', 'dir' => 'application/x-director', 'dxr' => 'application/x-director', 'dvi' => 'application/x-dvi', 'spl' => 'application/x-futuresplash', 'gtar' => 'application/x-gtar', 'tgz' => 'application/x-gtar', 'gz' => 'application/x-gzip', 'hdf' => 'application/x-hdf', 'php' => 'application/x-httpd-php', 'php3' => 'application/x-httpd-php3', 'js' => 'application/x-javascript', 'skd' => 'application/x-koan', 'skm' => 'application/x-koan', 'skp' => 'application/x-koan', 'skt' => 'application/x-koan', 'latex' => 'application/x-latex', 'wmd' => 'application/x-ms-wmd', 'wmz' => 'application/x-ms-wmz', 'cdf' => 'application/x-netcdf', 'nc' => 'application/x-netcdf', 'pl' => 'application/x-perl', 'pm' => 'application/x-perl', 'psd' => 'application/x-photoshop', 'sh' => 'application/x-sh', 'shar' => 'application/x-shar', 'swf' => 'application/x-shockwave-flash', 'sit' => 'application/x-stuffit', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc', 'tar' => 'application/x-tar', 'tcl' => 'application/x-tcl', 'tex' => 'application/x-tex', 'texi' => 'application/x-texinfo', 'texinfo' => 'application/x-texinfo', 'roff' => 'application/x-troff', 't' => 'application/x-troff', 'tr' => 'application/x-troff', 'man' => 'application/x-troff-man', 'me' => 'application/x-troff-me', 'ms' => 'application/x-troff-ms', 'ustar' => 'application/x-ustar', 'src' => 'application/x-wais-source', 'xht' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', 'xml' => 'application/xml', 'zip' => 'application/zip', 'au' => 'audio/basic', 'snd' => 'audio/basic', 'kar' => 'audio/midi', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'mpga' => 'audio/mpeg', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'm3u' => 'audio/x-mpegurl', 'wax' => 'audio/x-ms-wax', 'wma' => 'audio/x-ms-wma', 'ram' => 'audio/x-pn-realaudio', 'rm' => 'audio/x-pn-realaudio', 'rpm' => 'audio/x-pn-realaudio-plugin', 'ra' => 'audio/x-realaudio', 'wav' => 'audio/x-wav', 'pdb' => 'chemical/x-pdb', 'xyz' => 'chemical/x-xyz', 'bmp' => 'image/bmp', 'gif' => 'image/gif', 'ief' => 'image/ief', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'png' => 'image/png', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'wbmp' => 'image/vnd.wap.wbmp', 'ras' => 'image/x-cmu-raster', 'pnm' => 'image/x-portable-anymap', 'pbm' => 'image/x-portable-bitmap', 'pgm' => 'image/x-portable-graymap', 'ppm' => 'image/x-portable-pixmap', 'rgb' => 'image/x-rgb', 'xbm' => 'image/x-xbitmap', 'xpm' => 'image/x-xpixmap', 'xwd' => 'image/x-xwindowdump', 'iges' => 'model/iges', 'igs' => 'model/iges', 'mesh' => 'model/mesh', 'msh' => 'model/mesh', 'silo' => 'model/mesh', 'vrml' => 'model/vrml', 'wrl' => 'model/vrml', 'ics' => 'text/calendar', 'ifb' => 'text/calendar', 'vcs' => 'text/calendar', 'vfb' => 'text/calendar', 'css' => 'text/css', 'csv' => 'text/csv', 'diff' => 'text/diff', 'patch' => 'text/diff', 'htm' => 'text/html', 'html' => 'text/html', 'shtml' => 'text/html', 'asc' => 'text/plain', 'log' => 'text/plain', 'po' => 'text/plain', 'txt' => 'text/plain', 'rtx' => 'text/richtext', 'rtf' => 'text/rtf', 'sgm' => 'text/sgml', 'sgml' => 'text/sgml', 'tsv' => 'text/tab-separated-values', 'wml' => 'text/vnd.wap.wml', 'wmls' => 'text/vnd.wap.wmlscript', 'etx' => 'text/x-setext', 'vcf' => 'text/x-vcard', 'xsl' => 'text/xml', 'mp4' => 'video/mp4', 'mpe' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mov' => 'video/quicktime', 'qt' => 'video/quicktime', 'mxu' => 'video/vnd.mpegurl', 'asf' => 'video/x-ms-asf', 'asx' => 'video/x-ms-asf', 'wm' => 'video/x-ms-wm', 'wmv' => 'video/x-ms-wmv', 'wmx' => 'video/x-ms-wmx', 'wvx' => 'video/x-ms-wvx', 'avi' => 'video/x-msvideo', 'movie' => 'video/x-sgi-movie', 'ice' => 'x-conference/x-cooltalk', );
[42]69
[1]70    /**
71     * Set (or overwrite existing) parameters by passing an array of new parameters.
72     *
73     * @access public
74     * @param  array    $params     Array of parameters (key => val pairs).
75     */
76    function setParam($params)
77    {
[136]78        $app =& App::getInstance();
79
[1]80        if (isset($params) && is_array($params)) {
[42]81
[20]82            // Enforce valid upload_path parameter.
83            if (isset($params['upload_path'])) {
84                $params['upload_path'] = realpath($params['upload_path']);
[152]85                // Source must be directory.
[20]86                if (!is_dir($params['upload_path'])) {
[136]87                    $app->logMsg(sprintf('Attempting to auto-create upload directory: %s', $params['upload_path']), LOG_NOTICE, __FILE__, __LINE__);
[152]88                    if (phpversion() > '5') {
89                        // Recursive.
90                        mkdir($params['upload_path'], isset($params['dest_dir_perms']) ? $params['dest_dir_perms'] : $this->getParam('dest_dir_perms'), true);
91                    } else {
92                        mkdir($params['upload_path'], isset($params['dest_dir_perms']) ? $params['dest_dir_perms'] : $this->getParam('dest_dir_perms'));
93                    }
[121]94                    if (!is_dir($params['upload_path'])) {
[136]95                        $app->logMsg(sprintf('Upload directory invalid: %s', $params['upload_path']), LOG_ERR, __FILE__, __LINE__);
[121]96                        trigger_error(sprintf('Upload directory invalid: %s', $params['upload_path']), E_USER_ERROR);
97                    }
[20]98                }
[152]99                // Source must be writable.
[20]100                if (!is_writable($params['upload_path'])) {
[136]101                    $app->logMsg(sprintf('Upload directory not writable: %s', $params['upload_path']), LOG_ERR, __FILE__, __LINE__);
[20]102                    trigger_error(sprintf('Upload directory not writable: %s', $params['upload_path']), E_USER_ERROR);
103                }
104            }
[42]105
[1]106            // Merge new parameters with old overriding only those passed.
107            $this->_params = array_merge($this->_params, $params);
108        } else {
[136]109            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
[1]110        }
111    }
112
113    /**
114     * Return the value of a parameter, if it exists.
115     *
116     * @access public
117     * @param string $param        Which parameter to return.
118     * @return mixed               Configured parameter value.
119     */
120    function getParam($param)
121    {
[136]122        $app =& App::getInstance();
123   
[1]124        if (isset($this->_params[$param])) {
125            return $this->_params[$param];
126        } else {
[146]127            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
[1]128            return null;
129        }
130    }
131
132    /**
[37]133     * Process uploaded files. Processes files existing within the specified $_FILES['form_name'] array.
[42]134     * It tests for errors, cleans the filename, optionally sets custom file names. It will process
[37]135     * multiple files automatically if the file form element is an array (<input type="file" name="myfiles[]" />).
[1]136     *
[37]137     * @access  public
138     * @param   string  $form_name          The name of the form to process.
[256]139     * @param   string  $custom_file_name   The new name of the file. An array of filenames in the case of multiple files.
[334]140     * @return  mixed   Returns FALSE if a major error occurred preventing any file uploads.
141     *                  Returns an empty array if any minor errors occurred or no files were found.
142     *                  Returns a multidimensional array of filenames, sizes and extensions, if one-or-more files succeeded uploading.
[37]143     *                  Note: this last option presents a problem in the case of when some files uploaded successfully, and some failed.
144     *                        In this case it is necessary to check the Upload::anyErrors method to discover if any did fail.
[1]145     */
146    function process($form_name, $custom_file_name=null)
147    {
[136]148        $app =& App::getInstance();
149
[1]150        // Ensure we have a upload directory.
[20]151        if (!$this->getParam('upload_path')) {
[136]152            $app->logMsg(sprintf('Upload directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
[119]153            $this->_raiseMsg(_("There was a problem with the file upload. Please try again later."), MSG_ERR, __FILE__, __LINE__);
[1]154            return false;
155        }
[42]156
[22]157        // Ensure the file form element specified actually exists.
[1]158        if (!isset($_FILES[$form_name])) {
[141]159            $app->logMsg(sprintf('Form element %s does not exist.', $form_name), LOG_ERR, __FILE__, __LINE__);
[119]160            $this->_raiseMsg(_("There was a problem with the file upload. Please try again later."), MSG_ERR, __FILE__, __LINE__);
[1]161            return false;
162        }
[42]163
[1]164        if (is_array($_FILES[$form_name]['name'])) {
165            $files = $_FILES[$form_name];
166        } else {
167            // Convert variables to single-cell array so it will loop.
168            $files = array(
169                'name'      => array($_FILES[$form_name]['name']),
170                'type'      => array($_FILES[$form_name]['type']),
171                'tmp_name'  => array($_FILES[$form_name]['tmp_name']),
172                'error'     => array($_FILES[$form_name]['error']),
173                'size'      => array($_FILES[$form_name]['size']),
174            );
175        }
176
177        // To keep this script running even if user tries to stop browser.
[42]178        ignore_user_abort(true);
[35]179        ini_set('max_execution_time', 300);
180        ini_set('max_input_time', 300);
[1]181
182        $new_file_names = array();
183
184        $num = sizeof($files['name']);
185        for ($i=0; $i<$num; $i++) {
186            $file_path_name = '';
187
[49]188            if ('' == trim($files['name'][$i])) {
[1]189                // User may not have attached a file.
190                continue;
191            }
[42]192
[22]193            // Determine final file name.
[1]194            if ($num == 1) {
195                // Single upload.
[286]196                if (isset($custom_file_name)) {
197                    if (is_array($custom_file_name) && sizeof($custom_file_name) == 1) {
198                        // Is an array, but just one value. Pull it out.
199                        $custom_file_name = current($custom_file_name);
200                        $this->_raiseMsg(sprintf(_("The file %s has been renamed to %s."), $files['name'][$i], $file_name), MSG_NOTICE, __FILE__, __LINE__);
201                        $app->logMsg(sprintf('Using custom file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
202                    } else if (!is_array($custom_file_name) && '' != $custom_file_name) {
203                        // Valid custom file name.
204                        $file_name = $custom_file_name;
205                        $this->_raiseMsg(sprintf(_("The file %s has been renamed to %s."), $files['name'][$i], $file_name), MSG_NOTICE, __FILE__, __LINE__);
206                        $app->logMsg(sprintf('Using custom file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
207                    } else {
208                        // Invalid custom file name provided. Use uploaded file name.
209                        $file_name = $files['name'][$i];
210                        $app->logMsg(sprintf('Custom filename invalid! Using uploaded file name: %s', $file_name), LOG_WARNING, __FILE__, __LINE__);
211                    }
[1]212                } else {
[286]213                    // Normal case. Use uploaded file name.
[1]214                    $file_name = $files['name'][$i];
[136]215                    $app->logMsg(sprintf('Using uploaded file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
[1]216                }
217            } else {
218                // Multiple upload. Final file names must be array.
[256]219                if (isset($custom_file_name) && is_array($custom_file_name) && '' != $custom_file_name[$i]) {
[1]220                    // Valid custom file name.
221                    $file_name = $custom_file_name[$i];
[121]222                    $this->_raiseMsg(sprintf(_("The file %s has been renamed to %s."), $files['name'][$i], $file_name), MSG_NOTICE, __FILE__, __LINE__);
[136]223                    $app->logMsg(sprintf('Using custom file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
[1]224                } else {
225                    // Invalid custom file name provided. Use uploaded file name.
226                    $file_name = $files['name'][$i];
[136]227                    $app->logMsg(sprintf('Using uploaded file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
[1]228                }
229            }
230
[22]231            // Check The php upload error messages.
[259]232            if (UPLOAD_ERR_INI_SIZE === $files['error'][$i]) { // Error code 1
[121]233                $this->_raiseMsg(sprintf(_("The file %s failed uploading: it exceeds the maximum allowed upload file size of %s."), $file_name, ini_get('upload_max_filesize')), MSG_ERR, __FILE__, __LINE__);
[203]234                $app->logMsg(sprintf('The file %s failed uploading with PHP error UPLOAD_ERR_INI_SIZE (currently %s).', $file_name, ini_get('upload_max_filesize')), LOG_ERR, __FILE__, __LINE__);
[119]235                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_ERR_INI_SIZE);
[22]236                continue;
237            }
[259]238            if (UPLOAD_ERR_FORM_SIZE === $files['error'][$i]) { // Error code 2
[121]239                $this->_raiseMsg(sprintf(_("The file %s failed uploading: it exceeds the maximum allowed upload file size of %s."), $file_name, $_POST['MAX_FILE_SIZE']), MSG_ERR, __FILE__, __LINE__);
[203]240                $app->logMsg(sprintf('The file %s failed uploading with PHP error UPLOAD_ERR_FORM_SIZE (currently %s).', $file_name, $_POST['MAX_FILE_SIZE']), LOG_ERR, __FILE__, __LINE__);
[119]241                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_ERR_FORM_SIZE);
[22]242                continue;
243            }
[259]244            if (UPLOAD_ERR_PARTIAL === $files['error'][$i]) { // Error code 3
[121]245                $this->_raiseMsg(sprintf(_("The file %s failed uploading: it was only partially uploaded."), $file_name), MSG_ERR, __FILE__, __LINE__);
[203]246                $app->logMsg(sprintf('The file %s failed uploading with PHP error UPLOAD_ERR_PARTIAL.', $file_name), LOG_ERR, __FILE__, __LINE__);
[119]247                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_ERR_PARTIAL);
[22]248                continue;
249            }
[259]250            if (UPLOAD_ERR_NO_FILE === $files['error'][$i]) { // Error code 4
[121]251                $this->_raiseMsg(sprintf(_("The file %s failed uploading: no file was uploaded."), $file_name), MSG_ERR, __FILE__, __LINE__);
[203]252                $app->logMsg(sprintf('The file %s failed uploading with PHP error UPLOAD_ERR_NO_FILE.', $file_name), LOG_ERR, __FILE__, __LINE__);
[119]253                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_ERR_NO_FILE);
[22]254                continue;
255            }
[259]256            if (UPLOAD_ERR_NO_TMP_DIR === $files['error'][$i]) { // Error code 6
[121]257                $this->_raiseMsg(sprintf(_("The file %s failed uploading: temporary upload directory missing."), $file_name), MSG_ERR, __FILE__, __LINE__);
[203]258                $app->logMsg(sprintf('The file %s failed uploading with PHP error UPLOAD_ERR_NO_TMP_DIR.', $file_name), LOG_ERR, __FILE__, __LINE__);
[119]259                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_ERR_NO_TMP_DIR);
[22]260                continue;
261            }
[42]262
[22]263            // Check to be sure it's an uploaded file.
264            if (!is_uploaded_file($files['tmp_name'][$i])) {
[121]265                $this->_raiseMsg(sprintf(_("The file %s failed uploading."), $file_name), MSG_ERR, __FILE__, __LINE__);
[141]266                $app->logMsg(sprintf('The file %s failed is_uploaded_file.', $file_name), LOG_ERR, __FILE__, __LINE__);
[119]267                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_USER_ERR_NOT_UPLOADED_FILE);
[22]268                continue;
269            }
[42]270
[22]271            // Check to be sure the file is not empty.
[119]272            if ($files['size'][$i] <= 0) {
[121]273                $this->_raiseMsg(sprintf(_("The file %s failed uploading: it contains zero bytes."), $file_name), MSG_ERR, __FILE__, __LINE__);
[141]274                $app->logMsg(sprintf('The uploaded file %s contains zero bytes.', $file_name), LOG_ERR, __FILE__, __LINE__);
[119]275                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_USER_ERR_EMPTY_FILE);
[22]276                continue;
277            }
[42]278
[22]279            // Check to be sure the file has a valid file name extension.
[247]280            if (!in_array(mb_strtolower($this->getFilenameExtension($file_name)), $this->getParam('valid_file_extensions'))) {
[121]281                $this->_raiseMsg(sprintf(_("The file %s failed uploading: it is an unrecognized type. Files must have one of the following file name extensions: %s."), $file_name, join(', ', $this->getParam('valid_file_extensions'))), MSG_ERR, __FILE__, __LINE__);
[141]282                $app->logMsg(sprintf('The uploaded file %s has an unrecognized file name extension.', $file_name), LOG_WARNING, __FILE__, __LINE__);
[119]283                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_USER_ERR_INVALID_EXTENSION);
[22]284                continue;
285            }
[42]286
[22]287            // Check to be sure the file has a unique file name.
288            if (!$this->getParam('allow_overwriting') && $this->exists($file_name)) {
[121]289                $this->_raiseMsg(sprintf(_("The file %s failed uploading: a file with that name already exists."), $file_name), MSG_ERR, __FILE__, __LINE__);
[142]290                $app->logMsg(sprintf('The uploaded file %s does not have a unique filename.', $file_name), LOG_WARNING, __FILE__, __LINE__);
[119]291                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_USER_ERR_NOT_UNIQUE);
[22]292                continue;
293            }
[42]294
[121]295            // If the file name has no extension, use the mime-type to choose one.
296            if (!preg_match('/\.[^.]{1,5}$/', $file_name) && function_exists('mime_content_type')) {
297                if ($ext = array_search(mime_content_type($files['tmp_name'][$i]), $this->mime_extension_map)) {
298                    $file_name .= ".$ext";
299                }
300            }
301
302            // Clean the file name of bad characters.
303            $file_name = $this->cleanFileName($file_name);
304
305            // FINAL path and file name, lowercase extension.
[247]306            $file_extension = mb_strtolower($this->getFilenameExtension($file_name));
307            $file_name = sprintf('%s.%s', mb_substr($file_name, 0, mb_strrpos($file_name, '.')), $file_extension);
[121]308            $file_path_name = sprintf('%s/%s', $this->getParam('upload_path'), $file_name);
309
[1]310            // Move the file to the final place.
311            if (move_uploaded_file($files['tmp_name'][$i], $file_path_name)) {
[20]312                chmod($file_path_name, $this->getParam('dest_file_perms'));
[136]313                $app->logMsg(sprintf('File uploaded: %s', $file_path_name), LOG_INFO, __FILE__, __LINE__);
[121]314                $this->_raiseMsg(sprintf(_("The file %s uploaded successfully."), $file_name), MSG_SUCCESS, __FILE__, __LINE__);
[1]315                if (!isset($custom_file_name) && $files['name'][$i] != $file_name) {
316                    // Notify user if uploaded file name was modified (unless a custom file name will be used anyways).
[121]317                    $this->_raiseMsg(sprintf(_("The file %s was renamed to %s."), $files['name'][$i], $file_name), MSG_NOTICE, __FILE__, __LINE__);
[1]318                }
319                $new_file_names[] = array(
320                    'name' => $file_name,
[121]321                    'mime' => $files['type'][$i],
[1]322                    'size' => filesize($file_path_name),
[121]323                    'extension' => $file_extension,
324                    'original_index' => $i,
[301]325                    'original_name' => $files['name'][$i],
[1]326                );
327            } else {
[121]328                $this->_raiseMsg(sprintf(_("The file %s failed uploading."), $file_name), MSG_ERR, __FILE__, __LINE__);
[141]329                $app->logMsg(sprintf('Moving file failed: %s -> %s', $files['tmp_name'][$i], $file_path_name), LOG_ALERT, __FILE__, __LINE__);
[119]330                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_USER_ERR_MOVE_FAILED);
[1]331            }
[121]332
333            // Check file extension with browsers interpretation of file type.
334            if (isset($this->mime_extension_map[$file_extension]) && $files['type'][$i] != $this->mime_extension_map[$file_extension]) {
[136]335                $app->logMsg(sprintf('File extension (%s) does not match mime type (%s).', $file_extension, $files['type'][$i]), LOG_NOTICE, __FILE__, __LINE__);
[121]336            }
[1]337        }
[42]338
[22]339        // Return names of files uploaded (or empty array when none processed).
340        return $new_file_names;
[1]341    }
[42]342
[1]343    /**
[37]344     * Remove file within upload path.
[1]345     *
[37]346     * @access  public
347     * @param   string  $file_name  A name of a file.
[301]348     * @param   bool    $use_glob   Set true to use glob to find the filename (using $file_name as a pattern)
[37]349     * @return  bool                Success of operation.
[1]350     */
[301]351    function deleteFile($file_name, $use_glob=false)
[1]352    {
[136]353        $app =& App::getInstance();
354
[1]355        // Ensure we have a upload directory.
[20]356        if (!$this->getParam('upload_path')) {
[136]357            $app->logMsg(sprintf('Upload directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
[1]358            return false;
359        }
[42]360
[301]361        $file_path_name = $this->getParam('upload_path') . '/' . ($use_glob ? $this->getFilenameGlob($file_name) : $file_name);
[1]362
363        if (!is_file($file_path_name)) {
[141]364            $app->logMsg(sprintf('Error deleting nonexistent file: %s', $file_path_name), LOG_ERR, __FILE__, __LINE__);
[1]365            return false;
366        } else if (unlink($file_path_name)) {
[136]367            $app->logMsg(sprintf('Deleted file: %s', $file_path_name), LOG_INFO, __FILE__, __LINE__);
[301]368            return true;
[1]369        } else {
[121]370            $this->_raiseMsg(sprintf(_("The file %s could not be deleted."), $file_name), MSG_ERR, __FILE__, __LINE__);
[141]371            $app->logMsg(sprintf('Failed deleting file: %s', $file_path_name), LOG_ERR, __FILE__, __LINE__);
[1]372            return false;
373        }
374    }
[42]375
[1]376    /**
[37]377     * Renames a file within the upload path.
[1]378     *
[37]379     * @access  public
380     * @param   string  $old_name   The currently existing file name.
381     * @param   string  $new_name   The new name for this file.
382     * @return  bool                Success of operation.
[1]383     */
384    function moveFile($old_name, $new_name)
385    {
[136]386        $app =& App::getInstance();
387
[1]388        // Ensure we have an upload directory.
[20]389        if (!$this->getParam('upload_path')) {
[136]390            $app->logMsg(sprintf('Upload directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
[1]391            return false;
392        }
[42]393
[20]394        $old_file_path_name = $this->getParam('upload_path') . '/' . $old_name;
395        $new_file_path_name = $this->getParam('upload_path') . '/' . $new_name;
[1]396        if (file_exists($old_file_path_name)) {
[20]397            if (rename($old_file_path_name, $new_file_path_name)) {
[121]398                $this->_raiseMsg(sprintf(_("The file %s has been renamed to %s."), basename($old_file_path_name), basename($new_file_path_name)), MSG_NOTICE, __FILE__, __LINE__);
[136]399                $app->logMsg(sprintf('File renamed from %s to %s', $old_file_path_name, $new_file_path_name), LOG_DEBUG, __FILE__, __LINE__);
[20]400            } else {
[119]401                $this->_raiseMsg(sprintf(_("Error renaming file to %s"), $new_file_path_name), MSG_WARNING, __FILE__, __LINE__);
[141]402                $app->logMsg(sprintf('Error renaming file to %s', $new_file_path_name), LOG_WARNING, __FILE__, __LINE__);
[1]403                return false;
404            }
405        } else {
[121]406            $this->_raiseMsg(sprintf(_("Couldn't rename nonexistent file %s."), $old_name), MSG_WARNING, __FILE__, __LINE__);
[141]407            $app->logMsg(sprintf('Error renaming nonexistent file: %s', $old_file_path_name), LOG_WARNING, __FILE__, __LINE__);
[1]408            return false;
409        }
410    }
[42]411
[1]412    /**
[37]413     * Tests if a file exists within the current upload_path.
[1]414     *
[37]415     * @access  public
416     * @param   string  $file_name  A name of a file.
417     * @return  bool                Existence of file.
[1]418     */
419    function exists($file_name)
420    {
[136]421        $app =& App::getInstance();
422
[1]423        // Ensure we have a upload directory.
[20]424        if (!$this->getParam('upload_path')) {
[136]425            $app->logMsg(sprintf('Upload directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
[1]426            return false;
427        }
[42]428
[20]429        return file_exists($this->getParam('upload_path') . '/' . $file_name);
[1]430    }
431
432    /**
[42]433     * Get filename by glob pattern. Searches a directory for an image that matches the
[20]434     * specified glob pattern and returns the filename of the first file found.
[1]435     *
[20]436     * @access  public
437     * @param   string  $pattern   Pattern to match filename.
438     * @return  string filename on success, empty string on failure.
439     * @author  Quinn Comendant <quinn@strangecode.com>
440     * @since   15 Nov 2005 20:55:22
[1]441     */
[20]442    function getFilenameGlob($pattern)
443    {
444        $file_list = glob(sprintf('%s/%s', $this->getParam('upload_path'), $pattern));
445        if (isset($file_list[0])) {
446            return basename($file_list[0]);
447        } else {
448            return '';
449        }
450    }
451
452    /**
[37]453     * Returns an array of file names that failed uploading.
[20]454     *
[37]455     * @access  public
456     * @return  array   List of file names.
[20]457     */
[1]458    function getErrors()
459    {
460        return $this->errors;
461    }
462
463    /**
[334]464     * Determines if any errors occurred while calling the Upload::process method.
[1]465     *
[37]466     * @access  public
[1]467     */
[22]468    function anyErrors()
469    {
470        return sizeof($this->errors) > 0;
471    }
472
473    /**
[37]474     * Removes unsafe characters from file name.
[22]475     *
[37]476     * @access  public
477     * @param   string  $file_name  A name of a file.
478     * @return  string              The same name, but cleaned.
[22]479     */
[1]480    function cleanFileName($file_name)
481    {
[106]482        $bad  = 'áéíóúàÚìòùÀëïöÌÁÉÍÓÚÀÈÌÒÙÄËÏÖÜâêîÎûÂÊÎÔÛñçÇ@';
[1]483        $good = 'aeiouaeiouaeiouAEIOUAEIOUAEIOUaeiouAEIOUncCa';
484        $file_name = trim($file_name);
485        $file_name = strtr($file_name, $bad, $good);
[303]486        $file_name = preg_replace('/[^-\w.,~_=+()]+/i', '_', $file_name);
[247]487        $file_name = mb_substr($file_name, 0, 250);
[1]488        return $file_name;
489    }
490
[37]491
[1]492    /**
[334]493     * Returns the extension of a file name, or an empty string if non exists.
[1]494     *
[37]495     * @access  public
[334]496     * @param   string  $file_name  A name of a file, with extension after a dot.
[37]497     * @return  string              The value found after the dot
[1]498     */
499    function getFilenameExtension($file_name)
500    {
[37]501        preg_match('/.*?\.(\w+)$/i', trim($file_name), $ext);
[22]502        return isset($ext[1]) ? $ext[1] : '';
[1]503    }
[42]504
[1]505    /**
[136]506     * An alias for $app->raiseMsg that only sends messages configured by display_messages.
[1]507     *
508     * @access public
509     *
510     * @param string $message The text description of the message.
511     * @param int    $type    The type of message: MSG_NOTICE,
512     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
513     * @param string $file    __FILE__.
514     * @param string $line    __LINE__.
515     */
[119]516    function _raiseMsg($message, $type, $file, $line)
[1]517    {
[136]518        $app =& App::getInstance();
519
[119]520        if ($this->getParam('display_messages') === true || (is_int($this->getParam('display_messages')) && $this->getParam('display_messages') & $type > 0)) {
[136]521            $app->raiseMsg($message, $type, $file, $line);
[1]522        }
523    }
524}
525
526?>
Note: See TracBrowser for help on using the repository browser.