Bin will be removed on June 1, 2014 in favor of http://gist.github.com. Please save all your pastes before then. So long, and thanks for all the fish!×
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
<?php
if (!defined('FILES')) {
    define('FILES', WWW_ROOT . 'files' . DS);
}
class UploadBehavior extends ModelBehavior {
   
    var $options    = array(      
        'dir'       => null,
        'filename'  => null,
        'overwrite' => null,
        'cascade'   => null,
        'messages'  => array(
            'no_dir'        => 'The servers upload directory is missing.',
            'no_write'      => 'Failed to write to the upload directory.',
            'file_exists'   => 'The file %s already exists.',
            'no_move'       => 'Failed to move file the upload directory.'
        )
    );
 
    var $fields     = array();
 
    function setup(&$model, $config = array()) {
        if(!is_array($config)) {
            $config = array($config);
        }
        foreach($config as $field => $options) {
            if(is_numeric($field) && is_string($options) && $model->hasField($options)) {
                unset($config[$field]);
                $field = $options;
                $options = array();
            } elseif(!$model->hasField($field)) {
                unset($config[$field]);
                continue;
            }
            $options = array_merge_recursive($this->options, $options);
            if(empty($options['dir'])) {
                $options['dir'] = FILES . low(Inflector::pluralize($model->name) . DS . $field) . DS;
            } elseif(substr($options['dir'], -1) != DS) {
                $options['dir'] .= DS;
            }
            $config[$field] = $options;
        }
        $this->fields = $config;
    }
 
    function beforeSave(&$model) {
        if(count($this->fields)) {
            foreach($this->fields as $field => $options) {
                if (!empty($model->data[$model->name][$field]['tmp_name']) && file_exists($model->data[$model->name][$field]['tmp_name'])) {
                    if(!is_dir($options['dir']) && !Folder::mkdirr($options['dir'])) {
                        return $model->invalidate($field, $options['messages']['no_dir']) && false;
                    }
                    if(!is_writable($options['dir'])) {
                        return $model->invalidate($field, $options['messages']['no_write']) && false;
                    }
                    if($options['filename'] === true) {
                        $filename  = $model->data[$model->name][$field]['name'];
                    } elseif(method_exists($model, $options['filename'])) {
                        $filename  = call_user_func(array($model, $options['filename']), $model->data[$model->name][$field]['name']);
                    } else {
                        $filename  = md5(uniqid(time())) . '.' . pathinfo($model->data[$model->name][$field]['name'], PATHINFO_EXTENSION);
                    }
                    $file = $options['dir'] . $filename;
                    if(empty($options['overwrite']) && file_exists($file)) {
                        return $model->invalidate($field, sprintf($options['messages']['no_write'], $filename)) && false;
                    }
                    if(!move_uploaded_file(@$model->data[$model->name][$field]['tmp_name'], $file)) {
                        return $model->invalidate($field, $options['messages']['no_move']) && false;
                    }
                    $model->data[$model->name][$field] = $filename;
                    $model->data[$model->name]['mimetype'] = mime_content_type($file);
                    $model->data[$model->name]['filesize'] = filesize($file);
                } else {
                    //Not an uploaded file
                }
            }
        }
    }
 
    function beforeDelete(&$model, $cascade) {
        if(count($this->fields)) {
            $model->read(null, $model->id);
            if(isset($model->data)) {
                foreach($this->fields as $field => $options) {
                    $file   = $options['dir'] . $model->data[$model->name][$field];
                    if(is_file($file) && !unlink($file)) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
 
    function afterDelete(&$model) {
        if(count($this->fields)) {
            foreach($this->fields as $field => $options) {
                $used  = $model->findAll("{$model->name}.$field = '{$model->data[$model->name][$field]}'");
                if(!empty($options['cascade']) && !empty($used)){
                    foreach($used as $line) {
                        $model->del($line[$model->name]['id']);
                    }
                }
            }
        }
    }
 
    /* check uploaded file error */
    function uploaded($model, $check, $messages = array(), $param) {
        if(!$this->upload_check($model, $check, $param)) {
            return false;
        }
        $messages =  (array)$messages + array(
            'Error while uploading file.',
            UPLOAD_ERR_INI_SIZE     => 'The file is too large, max filesize on server: %s.',
            UPLOAD_ERR_FORM_SIZE    => 'The file is too large, max filesize on form: %s.',
            UPLOAD_ERR_PARTIAL      => 'The file was only partially uploaded.',
            UPLOAD_ERR_NO_TMP_DIR   => 'The servers temporary folder is missing.',
            UPLOAD_ERR_CANT_WRITE   => 'Failed to write file to disk.',
            UPLOAD_ERR_EXTENSION    => 'File upload stopped by extension.'
        );
        $data = array_shift(array_values($check));
        $message = !empty($messages[$data['error']]) ?
            $messages[$data['error']] :
            (!empty($param['message']) ? $param['message'] : $messages[0]);
        switch($data['error']) {
            case UPLOAD_ERR_OK:
                return true;
            case UPLOAD_ERR_NO_FILE:
                return isset($param['no_upload']) && $param['no_upload'];
            case UPLOAD_ERR_INI_SIZE:
                $message = sprintf($message, $this->_size_format($this->_size_int(ini_get('upload_max_filesize'))));
            break;
            case UPLOAD_ERR_FORM_SIZE:
                $message = sprintf($message, $this->_size_format($_POST['MAX_FILE_SIZE']));
            break;
        }
        return $model->invalidate(array_shift(array_keys($check)), $message) && true;
        // return true to show the custom message
    }
 
    /* check if file is uploaded via HTTP POST */
    function upload_check($model, $check, $param) {
        $data = array_shift(array_values($check));
        return !empty($data['tmp_name']) ?
            is_uploaded_file($data['tmp_name']) :
            (isset($param['no_upload']) && $param['no_upload']);
    }
 
    /* check uploaded file name */
    function upload_name($model, $check, $regex = VALID_NOT_EMPTY, $param) {
        $data = array_shift(array_values($check));
        return !empty($data['tmp_name']) ?
            preg_match($regex, $data['name']) :
            (isset($param['no_upload']) && $param['no_upload']);
    }
 
    /* check uploaded file type */
    function upload_type($model, $check, $allowed = array('image/jpeg', 'image/png', 'image/gif'), $param) {
        $data = array_shift(array_values($check));
        return !empty($data['tmp_name']) ?
            in_array(mime_content_type($data['tmp_name']), $allowed) :
            (isset($param['no_upload']) && $param['no_upload']);
    }
 
    /* check uploaded file size */
    function upload_size($model, $check, $min = 0, $max = null, $param) {
        $max = !$max ? ini_get('upload_max_filesize') : $max;
        $data = array_shift(array_values($check));
        return !empty($data['tmp_name']) ?
            Validation::range(filesize($data['tmp_name']), $this->_size_int($min), $this->_size_int($max)) :
            (isset($param['no_upload']) && $param['no_upload']);
    }
 
    function _size_format($size) {
        return array_reduce (
            array ('octets', 'Ko', 'Mo'),
            create_function('$a,$b', 'return is_numeric($a)?($a>=1024?$a/1024:intval($a)." ".$b):$a;'),
            $size
        );
    }
 
    function _size_int($size) {
        switch(substr(low(preg_replace('/[^tgmk]/i' , '', $size)), 0, 1)) {
            case 'm':
                $size *= 1024;
            case 'k':
                $size *= 1024;
        }
        return intval($size);
    }
 
}
?>