]> git.mxchange.org Git - friendica-addons.git/blob - js_upload/js_upload.php
Merge pull request #140 from repat/master
[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
200                 $upload_dir = get_config('system','tempdir');
201                 if(! $upload_dir)
202                         $upload_dir = sys_get_temp_dir();
203
204         $this->pathnm = tempnam($upload_dir,'frn');
205
206                 $temp = fopen($this->pathnm,"w");
207         $realSize = stream_copy_to_stream($input, $temp);
208
209         fclose($input);
210                 fclose($temp);
211         
212         if ($realSize != $this->getSize()){            
213             return false;
214         }
215         return true;
216     }
217
218         function getPath() {
219                 return $this->pathnm;
220         }
221
222     function getName() {
223         return $_GET['qqfile'];
224     }
225
226     function getSize() {
227         if (isset($_SERVER["CONTENT_LENGTH"])){
228             return (int)$_SERVER["CONTENT_LENGTH"];            
229         } else {
230             throw new Exception('Getting content length is not supported.');
231         }      
232     }   
233 }
234
235 /**
236  * Handle file uploads via regular form post (uses the $_FILES array)
237  */
238
239 class qqUploadedFileForm {  
240
241
242     /**
243      * Save the file to the specified path
244      * @return boolean TRUE on success
245      */
246
247
248     function save() {
249         return true;
250     }
251
252         function getPath() {
253                 return $_FILES['qqfile']['tmp_name'];
254         }
255
256     function getName() {
257         return $_FILES['qqfile']['name'];
258     }
259     function getSize() {
260         return $_FILES['qqfile']['size'];
261     }
262 }
263
264 class qqFileUploader {
265     private $allowedExtensions = array();
266     private $sizeLimit = 10485760;
267     private $file;
268
269     function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760){        
270         $allowedExtensions = array_map("strtolower", $allowedExtensions);
271             
272         $this->allowedExtensions = $allowedExtensions;        
273         $this->sizeLimit = $sizeLimit;
274         
275         if (isset($_GET['qqfile'])) {
276             $this->file = new qqUploadedFileXhr();
277         } elseif (isset($_FILES['qqfile'])) {
278             $this->file = new qqUploadedFileForm();
279         } else {
280             $this->file = false; 
281         }
282
283     }
284     
285     
286     private function toBytes($str){
287         $val = trim($str);
288         $last = strtolower($str[strlen($str)-1]);
289         switch($last) {
290             case 'g': $val *= 1024;
291             case 'm': $val *= 1024;
292             case 'k': $val *= 1024;        
293         }
294         return $val;
295     }
296     
297     /**
298      * Returns array('success'=>true) or array('error'=>'error message')
299      */
300     function handleUpload(){
301         
302         if (!$this->file){
303             return array('error' => t('No files were uploaded.'));
304         }
305         
306         $size = $this->file->getSize();
307         
308         if ($size == 0) {
309             return array('error' => t('Uploaded file is empty'));
310         }
311         
312 //        if ($size > $this->sizeLimit) {
313
314 //            return array('error' => t('Uploaded file is too large'));
315 //        }
316         
317
318                 $maximagesize = get_config('system','maximagesize');
319
320                 if(($maximagesize) && ($size > $maximagesize)) {
321                         return array('error' => t('Image exceeds size limit of ') . $maximagesize );
322
323                 }
324
325         $pathinfo = pathinfo($this->file->getName());
326         $filename = $pathinfo['filename'];
327
328         $ext = $pathinfo['extension'];
329
330         if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
331             $these = implode(', ', $this->allowedExtensions);
332             return array('error' => t('File has an invalid extension, it should be one of ') . $these . '.');
333         }
334         
335         if ($this->file->save()){
336             return array(
337                                 'success'=>true,
338                                 'path' => $this->file->getPath(), 
339                                 'filename' => $filename . '.' . $ext
340                         );
341         } else {
342             return array(
343                                 'error'=> t('Upload was cancelled, or server error encountered'),
344                                 'path' => $this->file->getPath(), 
345                                 'filename' => $filename . '.' . $ext
346                         );
347         }
348         
349     }    
350 }