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