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