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