]> git.mxchange.org Git - friendica.git/blob - addon/js_upload/js_upload.php
Merge branch 'fabrixxm-master'
[friendica.git] / addon / js_upload / js_upload.php
1 <?php
2
3 /**
4  *
5  * JavaScript Photo/Image Uploader
6  *
7  * Uses Valum 'qq' Uploader. 
8  * Module Author: Chris Case
9  *
10  * Prior to enabling, ensure that you have a directory 'uploads'
11  * which is writable by the web server.
12  *
13  */
14
15
16 function js_upload_install() {
17         register_hook('photo_upload_form', 'addon/js_upload/js_upload.php', 'js_upload_form');
18         register_hook('photo_post_init',   'addon/js_upload/js_upload.php', 'js_upload_post_init');
19         register_hook('photo_post_file',   'addon/js_upload/js_upload.php', 'js_upload_post_file');
20         register_hook('photo_post_end',    'addon/js_upload/js_upload.php', 'js_upload_post_end');
21 }
22
23
24 function js_upload_uninstall() {
25         unregister_hook('photo_upload_form', 'addon/js_upload/js_upload.php', 'js_upload_form');
26         unregister_hook('photo_post_init',   'addon/js_upload/js_upload.php', 'js_upload_post_init');
27         unregister_hook('photo_post_file',   'addon/js_upload/js_upload.php', 'js_upload_post_file');
28         unregister_hook('photo_post_end',    'addon/js_upload/js_upload.php', 'js_upload_post_end');
29 }
30
31
32 function js_upload_form(&$a,&$b) {
33
34         $b['default_upload'] = false;
35
36         $b['addon_text'] .= '<link href="' . $a->get_baseurl() . '/addon/js_upload/file-uploader/client/fileuploader.css" rel="stylesheet" type="text/css">';
37         $b['addon_text'] .= '<script src="' . $a->get_baseurl() . '/addon/js_upload/file-uploader/client/fileuploader.js" type="text/javascript"></script>';
38    
39         $b['addon_text'] .= <<< EOT
40         
41  <div id="file-uploader-demo1">         
42   <noscript>                    
43    <p>Please enable JavaScript to use file uploader.</p>
44    <!-- or put a simple form for upload here -->
45   </noscript> 
46  </div>
47
48 <script type="text/javascript">
49 var uploader = null;       
50 function getSelected(opt) {
51             var selected = new Array();
52             var index = 0;
53             for (var intLoop = 0; intLoop < opt.length; intLoop++) {
54                if ((opt[intLoop].selected) ||
55                    (opt[intLoop].checked)) {
56                   index = selected.length;
57                   //selected[index] = new Object;
58                   selected[index] = opt[intLoop].value;
59                   //selected[index] = intLoop;
60                }
61             }
62             return selected;
63          } 
64 function createUploader() {
65         uploader = new qq.FileUploader({
66                 element: document.getElementById('file-uploader-demo1'),
67                 action: '{$b['post_url']}',
68                 debug: true,
69                 onSubmit: function(id,filename) {
70
71                         uploader.setParams( {
72                                 newalbum                :       document.getElementById('photos-upload-newalbum').value,
73                                 album                   :       document.getElementById('photos-upload-album-select').value,
74                                 group_allow             :       getSelected(document.getElementById('group_allow')).join(','),
75                                 contact_allow   :       getSelected(document.getElementById('contact_allow')).join(','),
76                                 group_deny              :       getSelected(document.getElementById('group_deny')).join(','),
77                                 contact_deny    :       getSelected(document.getElementById('contact_deny')).join(',')
78                         });
79                 }
80         });           
81 }
82
83
84 // in your app create uploader as soon as the DOM is ready
85 // don't wait for the window to load  
86 window.onload = createUploader;     
87
88
89 </script>
90  
91 EOT;
92
93
94 }
95
96 function js_upload_post_init(&$a,&$b) {
97
98         // list of valid extensions, ex. array("jpeg", "xml", "bmp")
99
100         $allowedExtensions = array("jpeg","gif","png","jpg");
101
102         // max file size in bytes
103
104         $sizeLimit = 6 * 1024 * 1024;
105
106         $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
107
108         $result = $uploader->handleUpload();
109
110
111         // to pass data through iframe you will need to encode all html tags
112         $a->data['upload_jsonresponse'] =  htmlspecialchars(json_encode($result), ENT_NOQUOTES);
113
114         if(isset($result['error'])) {
115                 logger('mod/photos.php: photos_post(): error uploading photo: ' . $result['error'] , 'LOGGER_DEBUG');
116                 killme();
117         }
118
119         $a->data['upload_result'] = $result;
120
121 }
122
123 function js_upload_post_file(&$a,&$b) {
124
125         $result = $a->data['upload_result'];
126
127         $b['src']               = $result['path'];
128         $b['filename']  = $result['filename'];
129         $b['filesize']  = filesize($b['src']);
130
131 }
132
133
134 function js_upload_post_end(&$a,&$b) {
135
136 logger('upload_post_end');
137         if(x($a->data,'upload_jsonresponse')) {
138                 echo $a->data['upload_jsonresponse'];
139                 killme();
140         }
141
142 }
143
144
145 /**
146  * Handle file uploads via XMLHttpRequest
147  */
148 class qqUploadedFileXhr {
149
150         private $pathnm = '';
151
152     /**
153      * Save the file in the temp dir.
154      * @return boolean TRUE on success
155      */
156     function save() {    
157         $input = fopen("php://input", "r");
158         $this->pathnm = tempnam(sys_get_temp_dir(),'frn');
159                 $temp = fopen($this->pathnm,"w");
160         $realSize = stream_copy_to_stream($input, $temp);
161
162         fclose($input);
163                 fclose($temp);
164         
165         if ($realSize != $this->getSize()){            
166             return false;
167         }
168         return true;
169     }
170
171         function getPath() {
172                 return $this->pathnm;
173         }
174
175     function getName() {
176         return $_GET['qqfile'];
177     }
178
179     function getSize() {
180         if (isset($_SERVER["CONTENT_LENGTH"])){
181             return (int)$_SERVER["CONTENT_LENGTH"];            
182         } else {
183             throw new Exception('Getting content length is not supported.');
184         }      
185     }   
186 }
187
188 /**
189  * Handle file uploads via regular form post (uses the $_FILES array)
190  */
191
192 class qqUploadedFileForm {  
193
194
195     /**
196      * Save the file to the specified path
197      * @return boolean TRUE on success
198      */
199
200
201     function save() {
202         return true;
203     }
204
205         function getPath() {
206                 return $_FILES['qqfile']['tmp_name'];
207         }
208
209     function getName() {
210         return $_FILES['qqfile']['name'];
211     }
212     function getSize() {
213         return $_FILES['qqfile']['size'];
214     }
215 }
216
217 class qqFileUploader {
218     private $allowedExtensions = array();
219     private $sizeLimit = 10485760;
220     private $file;
221
222     function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760){        
223         $allowedExtensions = array_map("strtolower", $allowedExtensions);
224             
225         $this->allowedExtensions = $allowedExtensions;        
226         $this->sizeLimit = $sizeLimit;
227         
228         $this->checkServerSettings();       
229
230         if (isset($_GET['qqfile'])) {
231             $this->file = new qqUploadedFileXhr();
232         } elseif (isset($_FILES['qqfile'])) {
233             $this->file = new qqUploadedFileForm();
234         } else {
235             $this->file = false; 
236         }
237
238     }
239     
240     private function checkServerSettings(){        
241         $postSize = $this->toBytes(ini_get('post_max_size'));
242         $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));        
243                 logger('mod/photos.php: qqFileUploader(): upload_max_filesize=' . $uploadSize , 'LOGGER_DEBUG');
244         if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit){
245             $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';             
246             die("{'error':'increase post_max_size and upload_max_filesize to $size'}");    
247         }        
248     }
249     
250     private function toBytes($str){
251         $val = trim($str);
252         $last = strtolower($str[strlen($str)-1]);
253         switch($last) {
254             case 'g': $val *= 1024;
255             case 'm': $val *= 1024;
256             case 'k': $val *= 1024;        
257         }
258         return $val;
259     }
260     
261     /**
262      * Returns array('success'=>true) or array('error'=>'error message')
263      */
264     function handleUpload(){
265         
266         if (!$this->file){
267             return array('error' => t('No files were uploaded.'));
268         }
269         
270         $size = $this->file->getSize();
271         
272         if ($size == 0) {
273             return array('error' => t('Uploaded file is empty'));
274         }
275         
276         if ($size > $this->sizeLimit) {
277
278             return array('error' => t('Uploaded file is too large'));
279         }
280         
281
282                 $maximagesize = get_config('system','maximagesize');
283
284                 if(($maximagesize) && ($size > $maximagesize)) {
285                         return array('error' => t('Image exceeds size limit of ') . $maximagesize );
286
287                 }
288
289         $pathinfo = pathinfo($this->file->getName());
290         $filename = $pathinfo['filename'];
291
292         $ext = $pathinfo['extension'];
293
294         if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
295             $these = implode(', ', $this->allowedExtensions);
296             return array('error' => t('File has an invalid extension, it should be one of ') . $these . '.');
297         }
298         
299         if ($this->file->save()){
300             return array(
301                                 'success'=>true,
302                                 'path' => $this->file->getPath(), 
303                                 'filename' => $filename . '.' . $ext
304                         );
305         } else {
306             return array(
307                                 'error'=> t('Upload was cancelled, or server error encountered'),
308                                 'path' => $this->file->getPath(), 
309                                 'filename' => $filename . '.' . $ext
310                         );
311         }
312         
313     }    
314 }