source: trunk/lib/Upload.inc.php @ 502

Last change on this file since 502 was 502, checked in by anonymous, 9 years ago

Many minor fixes during pulso development

File size: 31.1 KB
Line 
1<?php
2/**
3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
5 * Copyright 2001-2012 Strangecode, LLC
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/**
24 * Upload.inc.php
25 *
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
30 * @version 1.4
31 */
32
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);
39
40class Upload
41{
42
43    // General object parameters.
44    protected $_params = array(
45
46        // Which messages do we pass to raiseMsg?
47        'display_messages' => MSG_ALL,
48
49        // Existing files will be overwritten when there is a name conflict?
50        'allow_overwriting' => false,
51
52        // The filesystem path to the final upload directory.
53        'upload_path' => null,
54
55        // The file permissions of the uploaded files. Remember, files will be owned by the web server user.
56        'dest_file_perms' => 0600,
57
58        // The file permissions of the uploaded files. Remember, files will be owned by the web server user.
59        'dest_dir_perms' => 0700,
60
61        // Require file to have one of the following file name extensions.
62        'valid_file_extensions' => array('jpg', 'jpeg', 'gif', 'png', 'pdf', 'txt', 'text', 'html', 'htm'),
63    );
64
65    // Array of files with errors.
66    public $errors = array();
67
68    // Array of file name extensions and corresponding mime-types.
69    public $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', );
70
71    /**
72     * Set (or overwrite existing) parameters by passing an array of new parameters.
73     *
74     * @access public
75     * @param  array    $params     Array of parameters (key => val pairs).
76     */
77    public function setParam($params)
78    {
79        $app =& App::getInstance();
80
81        if (isset($params) && is_array($params)) {
82
83            // Enforce valid upload_path parameter.
84            if (isset($params['upload_path'])) {
85                $upload_path = realpath($params['upload_path']);
86                // Source must be directory.
87                if (!is_dir($upload_path)) {
88                    $app->logMsg(sprintf('Attempting to auto-create upload directory: %s', $upload_path), LOG_NOTICE, __FILE__, __LINE__);
89                    if (version_compare(PHP_VERSION, '5.0.0', '>=')) {
90                        // Recursive.
91                        mkdir($upload_path, isset($params['dest_dir_perms']) ? $params['dest_dir_perms'] : $this->getParam('dest_dir_perms'), true);
92                    } else {
93                        mkdir($upload_path, isset($params['dest_dir_perms']) ? $params['dest_dir_perms'] : $this->getParam('dest_dir_perms'));
94                    }
95                    if (!is_dir($upload_path)) {
96                        $app->logMsg(sprintf('Upload directory invalid: %s', $params['upload_path']), LOG_ERR, __FILE__, __LINE__);
97                        trigger_error(sprintf('Upload directory invalid: %s', $params['upload_path']), E_USER_ERROR);
98                    }
99                }
100                // Source must be writable.
101                if (!is_writable($upload_path)) {
102                    $app->logMsg(sprintf('Upload directory not writable: %s', $params['upload_path']), LOG_ERR, __FILE__, __LINE__);
103                    trigger_error(sprintf('Upload directory not writable: %s', $params['upload_path']), E_USER_ERROR);
104                }
105            }
106
107            // Merge new parameters with old overriding only those passed.
108            $this->_params = array_merge($this->_params, $params);
109        } else {
110            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
111        }
112    }
113
114    /**
115     * Return the value of a parameter, if it exists.
116     *
117     * @access public
118     * @param string $param        Which parameter to return.
119     * @return mixed               Configured parameter value.
120     */
121    public function getParam($param)
122    {
123        $app =& App::getInstance();
124
125        if (array_key_exists($param, $this->_params)) {
126            return $this->_params[$param];
127        } else {
128            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
129            return null;
130        }
131    }
132
133    /**
134     * Process uploaded files. Processes files existing within the specified $_FILES['form_name'] array.
135     * It tests for errors, cleans the filename, optionally sets custom file names. It will process
136     * multiple files automatically if the file form element is an array (<input type="file" name="myfiles[]" />).
137     *
138     * @access  public
139     * @param   string  $form_name          The name of the form to process.
140     * @param   string  $custom_file_name   The new name of the file. An array of filenames in the case of multiple files.
141     * @return  mixed   Returns FALSE if a major error occurred preventing any file uploads.
142     *                  Returns an empty array if any minor errors occurred or no files were found.
143     *                  Returns a multidimensional array of filenames, sizes and extensions, if one-or-more files succeeded uploading.
144     *                  Note: this last option presents a problem in the case of when some files uploaded successfully, and some failed.
145     *                        In this case it is necessary to check the Upload::anyErrors method to discover if any did fail.
146     */
147    public function process($form_name, $custom_file_name=null)
148    {
149        $app =& App::getInstance();
150
151        // Ensure we have a upload directory.
152        if (!$this->getParam('upload_path')) {
153            $app->logMsg(sprintf('Upload directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
154            $this->_raiseMsg(_("There was a problem with the file upload. Please try again later."), MSG_ERR, __FILE__, __LINE__);
155            return false;
156        }
157
158        // Ensure the file form element specified actually exists.
159        if (!isset($_FILES[$form_name])) {
160            $app->logMsg(sprintf('Form element %s does not exist.', $form_name), LOG_ERR, __FILE__, __LINE__);
161            $this->_raiseMsg(_("There was a problem with the file upload. Please try again later."), MSG_ERR, __FILE__, __LINE__);
162            return false;
163        }
164
165        if (is_array($_FILES[$form_name]['name'])) {
166            $files = $_FILES[$form_name];
167        } else {
168            // Convert variables to single-cell array so it will loop.
169            $files = array(
170                'name'      => array($_FILES[$form_name]['name']),
171                'type'      => array($_FILES[$form_name]['type']),
172                'tmp_name'  => array($_FILES[$form_name]['tmp_name']),
173                'error'     => array($_FILES[$form_name]['error']),
174                'size'      => array($_FILES[$form_name]['size']),
175            );
176        }
177
178        // To keep this script running even if user tries to stop browser.
179        ignore_user_abort(true);
180        ini_set('max_execution_time', 300);
181        ini_set('max_input_time', 300);
182
183        $new_file_names = array();
184
185        $num = sizeof($files['name']);
186        for ($i=0; $i<$num; $i++) {
187            $file_path_name = '';
188
189            if ('' == trim($files['name'][$i])) {
190                // User may not have attached a file.
191                continue;
192            }
193
194            // Determine final file name.
195            if ($num == 1) {
196                // Single upload.
197                if (isset($custom_file_name)) {
198                    if (is_array($custom_file_name) && sizeof($custom_file_name) == 1) {
199                        // Is an array, but just one value. Pull it out.
200                        $file_name = current($custom_file_name);
201                        $this->_raiseMsg(sprintf(_("The file %s has been renamed to %s."), $files['name'][$i], $file_name), MSG_NOTICE, __FILE__, __LINE__);
202                        $app->logMsg(sprintf('Using custom file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
203                    } else if (!is_array($custom_file_name) && '' != $custom_file_name) {
204                        // Valid custom file name.
205                        $file_name = $custom_file_name;
206                        $this->_raiseMsg(sprintf(_("The file %s has been renamed to %s."), $files['name'][$i], $file_name), MSG_NOTICE, __FILE__, __LINE__);
207                        $app->logMsg(sprintf('Using custom file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
208                    } else {
209                        // Invalid custom file name provided. Use uploaded file name.
210                        $file_name = $files['name'][$i];
211                        $app->logMsg(sprintf('Custom filename invalid! Using uploaded file name: %s', $file_name), LOG_WARNING, __FILE__, __LINE__);
212                    }
213                } else {
214                    // Normal case. Use uploaded file name.
215                    $file_name = $files['name'][$i];
216                    $app->logMsg(sprintf('Using uploaded file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
217                }
218            } else {
219                // Multiple upload. Final file names must be array.
220                if (isset($custom_file_name) && is_array($custom_file_name) && '' != $custom_file_name[$i]) {
221                    // Valid custom file name.
222                    $file_name = $custom_file_name[$i];
223                    $this->_raiseMsg(sprintf(_("The file %s has been renamed to %s."), $files['name'][$i], $file_name), MSG_NOTICE, __FILE__, __LINE__);
224                    $app->logMsg(sprintf('Using custom file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
225                } else {
226                    // Invalid custom file name provided. Use uploaded file name.
227                    $file_name = $files['name'][$i];
228                    $app->logMsg(sprintf('Using uploaded file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
229                }
230            }
231
232            // Check The php upload error messages.
233            if (UPLOAD_ERR_INI_SIZE === $files['error'][$i]) { // Error code 1
234                $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__);
235                $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__);
236                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_ERR_INI_SIZE);
237                continue;
238            }
239            if (UPLOAD_ERR_FORM_SIZE === $files['error'][$i]) { // Error code 2
240                $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__);
241                $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__);
242                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_ERR_FORM_SIZE);
243                continue;
244            }
245            if (UPLOAD_ERR_PARTIAL === $files['error'][$i]) { // Error code 3
246                $this->_raiseMsg(sprintf(_("The file %s failed uploading: it was only partially uploaded."), $file_name), MSG_ERR, __FILE__, __LINE__);
247                $app->logMsg(sprintf('The file %s failed uploading with PHP error UPLOAD_ERR_PARTIAL.', $file_name), LOG_ERR, __FILE__, __LINE__);
248                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_ERR_PARTIAL);
249                continue;
250            }
251            if (UPLOAD_ERR_NO_FILE === $files['error'][$i]) { // Error code 4
252                $this->_raiseMsg(sprintf(_("The file %s failed uploading: no file was uploaded."), $file_name), MSG_ERR, __FILE__, __LINE__);
253                $app->logMsg(sprintf('The file %s failed uploading with PHP error UPLOAD_ERR_NO_FILE.', $file_name), LOG_ERR, __FILE__, __LINE__);
254                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_ERR_NO_FILE);
255                continue;
256            }
257            if (UPLOAD_ERR_NO_TMP_DIR === $files['error'][$i]) { // Error code 6
258                $this->_raiseMsg(sprintf(_("The file %s failed uploading: temporary upload directory missing."), $file_name), MSG_ERR, __FILE__, __LINE__);
259                $app->logMsg(sprintf('The file %s failed uploading with PHP error UPLOAD_ERR_NO_TMP_DIR.', $file_name), LOG_ERR, __FILE__, __LINE__);
260                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_ERR_NO_TMP_DIR);
261                continue;
262            }
263
264            // Check to be sure it's an uploaded file.
265            if (!is_uploaded_file($files['tmp_name'][$i])) {
266                $this->_raiseMsg(sprintf(_("The file %s failed uploading."), $file_name), MSG_ERR, __FILE__, __LINE__);
267                $app->logMsg(sprintf('The file %s failed is_uploaded_file.', $file_name), LOG_ERR, __FILE__, __LINE__);
268                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_USER_ERR_NOT_UPLOADED_FILE);
269                continue;
270            }
271
272            // Check to be sure the file is not empty.
273            if ($files['size'][$i] <= 0) {
274                $this->_raiseMsg(sprintf(_("The file %s failed uploading: it contains zero bytes."), $file_name), MSG_ERR, __FILE__, __LINE__);
275                $app->logMsg(sprintf('The uploaded file %s contains zero bytes.', $file_name), LOG_ERR, __FILE__, __LINE__);
276                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_USER_ERR_EMPTY_FILE);
277                continue;
278            }
279
280            // Check to be sure the file has a valid file name extension.
281            if (!in_array(mb_strtolower(self::getFilenameExtension($file_name)), $this->getParam('valid_file_extensions'))) {
282                // TODO: Add option to allow any extention to be uploaded.
283                $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__);
284                $app->logMsg(sprintf('The uploaded file %s has an unrecognized file name extension.', $file_name), LOG_WARNING, __FILE__, __LINE__);
285                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_USER_ERR_INVALID_EXTENSION);
286                continue;
287            }
288
289            // Check to be sure the file has a unique file name.
290            if (!$this->getParam('allow_overwriting') && $this->exists($file_name)) {
291                $this->_raiseMsg(sprintf(_("The file %s failed uploading: a file with that name already exists."), $file_name), MSG_ERR, __FILE__, __LINE__);
292                $app->logMsg(sprintf('The uploaded file %s does not have a unique filename.', $file_name), LOG_WARNING, __FILE__, __LINE__);
293                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_USER_ERR_NOT_UNIQUE);
294                continue;
295            }
296
297            // If the file name has no extension, use the mime-type to choose one.
298            if (!preg_match('/\.[^.]{1,5}$/', $file_name) && function_exists('mime_content_type')) {
299                // TODO: will this run if an extention is filtered by 'valid_file_extensions'?
300                if ($ext = array_search(mime_content_type($files['tmp_name'][$i]), $this->mime_extension_map)) {
301                    $file_name .= ".$ext";
302                }
303            }
304
305            // Clean the file name of bad characters.
306            $file_name = $this->cleanFileName($file_name);
307
308            // FINAL path and file name, lowercase extension.
309            $file_extension = mb_strtolower(self::getFilenameExtension($file_name));
310            $file_name = sprintf('%s.%s', mb_substr($file_name, 0, mb_strrpos($file_name, '.')), $file_extension);
311            $file_path_name = sprintf('%s/%s', $this->getParam('upload_path'), $file_name);
312
313            // Move the file to the final place.
314            if (move_uploaded_file($files['tmp_name'][$i], $file_path_name)) {
315                chmod($file_path_name, $this->getParam('dest_file_perms'));
316                $app->logMsg(sprintf('File uploaded: %s', $file_path_name), LOG_INFO, __FILE__, __LINE__);
317                $this->_raiseMsg(sprintf(_("The file %s uploaded successfully."), $file_name), MSG_SUCCESS, __FILE__, __LINE__);
318                if (!isset($custom_file_name) && $files['name'][$i] != $file_name) {
319                    // Notify user if uploaded file name was modified (unless a custom file name will be used anyways).
320                    $this->_raiseMsg(sprintf(_("The file %s was renamed to %s."), $files['name'][$i], $file_name), MSG_NOTICE, __FILE__, __LINE__);
321                }
322                $new_file_names[] = array(
323                    'name' => $file_name,
324                    'mime' => $files['type'][$i],
325                    'size' => filesize($file_path_name),
326                    'extension' => $file_extension,
327                    'original_index' => $i,
328                    'original_name' => $files['name'][$i],
329                );
330            } else {
331                $this->_raiseMsg(sprintf(_("The file %s failed uploading."), $file_name), MSG_ERR, __FILE__, __LINE__);
332                $app->logMsg(sprintf('Moving file failed: %s -> %s', $files['tmp_name'][$i], $file_path_name), LOG_ALERT, __FILE__, __LINE__);
333                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_USER_ERR_MOVE_FAILED);
334            }
335
336            // Check file extension with browsers interpretation of file type.
337            if (isset($this->mime_extension_map[$file_extension]) && $files['type'][$i] != $this->mime_extension_map[$file_extension]) {
338                $app->logMsg(sprintf('File extension (%s) does not match mime type (%s).', $file_extension, $files['type'][$i]), LOG_NOTICE, __FILE__, __LINE__);
339            }
340        }
341
342        // Return names of files uploaded (or empty array when none processed).
343        return $new_file_names;
344    }
345
346    /**
347     * Remove file within upload path.
348     *
349     * @access  public
350     * @param   string  $file_name  A name of a file.
351     * @param   bool    $use_glob   Set true to use glob to find the filename (using $file_name as a pattern)
352     * @return  bool                Success of operation.
353     */
354    public function deleteFile($file_name, $use_glob=false)
355    {
356        $app =& App::getInstance();
357
358        // Ensure we have a upload directory.
359        if (!$this->getParam('upload_path')) {
360            $app->logMsg(sprintf('Upload directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
361            return false;
362        }
363
364        $file_path_name = $this->getParam('upload_path') . '/' . ($use_glob ? $this->getFilenameGlob($file_name) : $file_name);
365
366        if (!is_file($file_path_name)) {
367            $app->logMsg(sprintf('Error deleting nonexistent file: %s', $file_path_name), LOG_ERR, __FILE__, __LINE__);
368            return false;
369        } else if (unlink($file_path_name)) {
370            $app->logMsg(sprintf('Deleted file: %s', $file_path_name), LOG_INFO, __FILE__, __LINE__);
371            return true;
372        } else {
373            $this->_raiseMsg(sprintf(_("The file %s could not be deleted."), $file_name), MSG_ERR, __FILE__, __LINE__);
374            $app->logMsg(sprintf('Failed deleting file: %s', $file_path_name), LOG_ERR, __FILE__, __LINE__);
375            return false;
376        }
377    }
378
379    /**
380     * Renames a file within the upload path.
381     *
382     * @access  public
383     * @param   string  $old_name   The currently existing file name.
384     * @param   string  $new_name   The new name for this file.
385     * @return  bool                Success of operation.
386     */
387    public function moveFile($old_name, $new_name)
388    {
389        $app =& App::getInstance();
390
391        // Ensure we have an upload directory.
392        if (!$this->getParam('upload_path')) {
393            $app->logMsg(sprintf('Upload directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
394            return false;
395        }
396
397        $old_file_path_name = $this->getParam('upload_path') . '/' . $old_name;
398        $new_file_path_name = $this->getParam('upload_path') . '/' . $new_name;
399        if (file_exists($old_file_path_name)) {
400            if (rename($old_file_path_name, $new_file_path_name)) {
401                $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__);
402                $app->logMsg(sprintf('File renamed from %s to %s', $old_file_path_name, $new_file_path_name), LOG_DEBUG, __FILE__, __LINE__);
403            } else {
404                $this->_raiseMsg(sprintf(_("Error renaming file to %s"), $new_file_path_name), MSG_WARNING, __FILE__, __LINE__);
405                $app->logMsg(sprintf('Error renaming file to %s', $new_file_path_name), LOG_WARNING, __FILE__, __LINE__);
406                return false;
407            }
408        } else {
409            $this->_raiseMsg(sprintf(_("Couldn't rename nonexistent file %s."), $old_name), MSG_WARNING, __FILE__, __LINE__);
410            $app->logMsg(sprintf('Error renaming nonexistent file: %s', $old_file_path_name), LOG_WARNING, __FILE__, __LINE__);
411            return false;
412        }
413    }
414
415    /**
416     * Tests if a file exists within the current upload_path.
417     *
418     * @access  public
419     * @param   string  $file_name  A name of a file.
420     * @return  bool                Existence of file.
421     */
422    public function exists($file_name)
423    {
424        $app =& App::getInstance();
425
426        // Ensure we have a upload directory.
427        if (!$this->getParam('upload_path')) {
428            $app->logMsg(sprintf('Upload directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
429            return false;
430        }
431
432        return file_exists($this->getParam('upload_path') . '/' . $file_name);
433    }
434
435    /**
436     * Get filename by glob pattern. Searches a directory for an image that matches the
437     * specified glob pattern and returns the filename of the first file found.
438     *
439     * @access  public
440     * @param   string  $pattern   Pattern to match filename.
441     * @return  string filename on success, empty string on failure.
442     * @author  Quinn Comendant <quinn@strangecode.com>
443     * @since   15 Nov 2005 20:55:22
444     */
445    public function getFilenameGlob($pattern)
446    {
447        $file_list = glob(sprintf('%s/%s', $this->getParam('upload_path'), $pattern));
448        if (isset($file_list[0])) {
449            return basename($file_list[0]);
450        } else {
451            return '';
452        }
453    }
454
455    /**
456     * Returns an array of file names that failed uploading.
457     *
458     * @access  public
459     * @return  array   List of file names.
460     */
461    public function getErrors()
462    {
463        return $this->errors;
464    }
465
466    /**
467     * Determines if any errors occurred while calling the Upload::process method.
468     *
469     * @access  public
470     */
471    public function anyErrors()
472    {
473        return sizeof($this->errors) > 0;
474    }
475
476    /**
477     * Removes non-latin characters from file name, using htmlentities to convert known weirdos into regular squares.
478     *
479     * @access  public
480     * @param   string  $file_name  A name of a file.
481     * @return  string              The same name, but cleaned.
482     */
483    public function cleanFileName($file_name)
484    {
485        $file_name = preg_replace(array(
486            '/&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml|caron);/ui',
487            '/&(?:amp);/ui',
488            '/[&;]+/u',
489            '/[^a-zA-Z0-9()@._=+-]+/u',
490            '/^_+|_+$/u'
491        ), array(
492            '$1',
493            'and',
494            '',
495            '_',
496            ''
497        ), htmlentities($file_name, ENT_NOQUOTES | ENT_IGNORE, 'UTF-8'));
498        return mb_substr($file_name, 0, 250);
499    }
500
501
502    /**
503     * Returns the extension of a file name, or an empty string if non exists.
504     *
505     * @access  public
506     * @param   string  $file_name  A name of a file, with extension after a dot.
507     * @return  string              The value found after the dot
508     */
509    static public function getFilenameExtension($file_name)
510    {
511        preg_match('/.*?\.(\w+)$/i', trim($file_name), $ext);
512        return isset($ext[1]) ? $ext[1] : '';
513    }
514
515    /**
516     * An alias for $app->raiseMsg that only sends messages configured by display_messages.
517     *
518     * @access public
519     *
520     * @param string $message The text description of the message.
521     * @param int    $type    The type of message: MSG_NOTICE,
522     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
523     * @param string $file    __FILE__.
524     * @param string $line    __LINE__.
525     */
526    public function _raiseMsg($message, $type, $file, $line)
527    {
528        $app =& App::getInstance();
529
530        if ($this->getParam('display_messages') === true || (is_int($this->getParam('display_messages')) && ($this->getParam('display_messages') & $type) > 0)) {
531            $app->raiseMsg($message, $type, $file, $line);
532        }
533    }
534}
535
Note: See TracBrowser for help on using the repository browser.