]> git.mxchange.org Git - friendica-addons.git/blob - js_upload/js_upload.php
Merge pull request #1157 from MrPetovan/task/advancecontentfilter-attachments
[friendica-addons.git] / js_upload / js_upload.php
1 <?php
2 /**
3  * Name: JS Uploader
4  * Description: JavaScript photo/image uploader. Helpful for uploading multiple files at once. Uses Valum 'qq' Uploader.
5  * Version: 1.1
6  * Author: Chris Case <http://friendika.openmindspace.org/profile/chris_case>
7  * Maintainer: Hypolite Petovan <https://friendica.mrpetovan.com/profile/hypolite>
8  */
9
10 use Friendica\App;
11 use Friendica\Core\Hook;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Renderer;
14 use Friendica\DI;
15 use Friendica\Util\Strings;
16
17 global $js_upload_jsonresponse;
18 global $js_upload_result;
19
20 function js_upload_install()
21 {
22         Hook::register('photo_upload_form', __FILE__, 'js_upload_form');
23         Hook::register('photo_post_init', __FILE__, 'js_upload_post_init');
24         Hook::register('photo_post_file', __FILE__, 'js_upload_post_file');
25         Hook::register('photo_post_end', __FILE__, 'js_upload_post_end');
26 }
27
28 function js_upload_form(App $a, array &$b)
29 {
30         $b['default_upload'] = false;
31
32         DI::page()->registerStylesheet('addon/js_upload/file-uploader/client/fileuploader.css');
33         DI::page()->registerFooterScript('addon/js_upload/file-uploader/client/fileuploader.js');
34
35         $tpl = Renderer::getMarkupTemplate('js_upload.tpl', 'addon/js_upload');
36         $b['addon_text'] .= Renderer::replaceMacros($tpl, [
37                 '$upload_msg' => DI::l10n()->t('Select files for upload'),
38                 '$drop_msg' => DI::l10n()->t('Drop files here to upload'),
39                 '$cancel' => DI::l10n()->t('Cancel'),
40                 '$failed' => DI::l10n()->t('Failed'),
41                 '$post_url' => $b['post_url'],
42                 '$maximagesize' => intval(DI::config()->get('system', 'maximagesize')),
43         ]);
44 }
45
46 function js_upload_post_init(App $a, &$b)
47 {
48         global $js_upload_result, $js_upload_jsonresponse;
49
50         // list of valid extensions
51         $allowedExtensions = ['jpeg', 'gif', 'png', 'jpg'];
52
53         // max file size in bytes
54         $sizeLimit = DI::config()->get('system', 'maximagesize');
55
56         $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
57
58         $result = $uploader->handleUpload();
59
60         // to pass data through iframe you will need to encode all html tags
61         $js_upload_jsonresponse = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
62
63         if (isset($result['error'])) {
64                 Logger::log('mod/photos.php: photos_post(): error uploading photo: ' . $result['error'], Logger::DEBUG);
65                 echo json_encode($result);
66                 exit();
67         }
68
69         $js_upload_result = $result;
70 }
71
72 function js_upload_post_file(App $a, &$b)
73 {
74         global $js_upload_result;
75
76         $result = $js_upload_result;
77
78         $b['src'] = $result['path'];
79         $b['filename'] = $result['filename'];
80         $b['filesize'] = filesize($b['src']);
81
82 }
83
84 function js_upload_post_end(App $a, &$b)
85 {
86         global $js_upload_jsonresponse;
87
88         Logger::log('upload_post_end');
89         if (!empty($js_upload_jsonresponse)) {
90                 echo $js_upload_jsonresponse;
91                 exit();
92         }
93 }
94
95 /**
96  * Handle file uploads via XMLHttpRequest
97  */
98 class qqUploadedFileXhr
99 {
100         private $pathnm = '';
101
102         /**
103          * Save the file in the temp dir.
104          *
105          * @return boolean TRUE on success
106          */
107         function save()
108         {
109                 $input = fopen('php://input', 'r');
110
111                 $upload_dir = DI::config()->get('system', 'tempdir');
112                 if (!$upload_dir)
113                         $upload_dir = sys_get_temp_dir();
114
115                 $this->pathnm = tempnam($upload_dir, 'frn');
116
117                 $temp = fopen($this->pathnm, 'w');
118                 $realSize = stream_copy_to_stream($input, $temp);
119
120                 fclose($input);
121                 fclose($temp);
122
123                 if ($realSize != $this->getSize()) {
124                         return false;
125                 }
126                 return true;
127         }
128
129         function getPath()
130         {
131                 return $this->pathnm;
132         }
133
134         function getName()
135         {
136                 return $_GET['qqfile'];
137         }
138
139         function getSize()
140         {
141                 if (isset($_SERVER['CONTENT_LENGTH'])) {
142                         return (int)$_SERVER['CONTENT_LENGTH'];
143                 } else {
144                         throw new Exception('Getting content length is not supported.');
145                 }
146         }
147 }
148
149 /**
150  * Handle file uploads via regular form post (uses the $_FILES array)
151  */
152 class qqUploadedFileForm
153 {
154         /**
155          * Save the file to the specified path
156          *
157          * @return boolean TRUE on success
158          */
159         function save()
160         {
161                 return true;
162         }
163
164         function getPath()
165         {
166                 return $_FILES['qqfile']['tmp_name'];
167         }
168
169         function getName()
170         {
171                 return $_FILES['qqfile']['name'];
172         }
173
174         function getSize()
175         {
176                 return $_FILES['qqfile']['size'];
177         }
178 }
179
180 class qqFileUploader
181 {
182         private $allowedExtensions = [];
183         private $sizeLimit = 10485760;
184         private $file;
185
186         function __construct(array $allowedExtensions = [], $sizeLimit = 10485760)
187         {
188                 $allowedExtensions = array_map('strtolower', $allowedExtensions);
189
190                 $this->allowedExtensions = $allowedExtensions;
191                 $this->sizeLimit = $sizeLimit;
192
193                 if (isset($_GET['qqfile'])) {
194                         $this->file = new qqUploadedFileXhr();
195                 } elseif (isset($_FILES['qqfile'])) {
196                         $this->file = new qqUploadedFileForm();
197                 } else {
198                         $this->file = false;
199                 }
200
201         }
202
203         private function toBytes($str)
204         {
205                 $val = trim($str);
206                 $last = strtolower($str[strlen($str) - 1]);
207                 switch ($last) {
208                         case 'g':
209                                 $val *= 1024;
210                         case 'm':
211                                 $val *= 1024;
212                         case 'k':
213                                 $val *= 1024;
214                 }
215                 return $val;
216         }
217
218         /**
219          * Returns array('success'=>true) or array('error'=>'error message')
220          */
221         function handleUpload()
222         {
223                 if (!$this->file) {
224                         return ['error' => DI::l10n()->t('No files were uploaded.')];
225                 }
226
227                 $size = $this->file->getSize();
228
229                 if ($size == 0) {
230                         return ['error' => DI::l10n()->t('Uploaded file is empty')];
231                 }
232
233 //              if ($size > $this->sizeLimit) {
234
235 //                      return array('error' => DI::l10n()->t('Uploaded file is too large'));
236 //              }
237
238
239                 $maximagesize = DI::config()->get('system', 'maximagesize');
240
241                 if (($maximagesize) && ($size > $maximagesize)) {
242                         return ['error' => DI::l10n()->t('Image exceeds size limit of %s', Strings::formatBytes($maximagesize))];
243                 }
244
245                 $pathinfo = pathinfo($this->file->getName());
246                 $filename = $pathinfo['filename'];
247
248                 if (!isset($pathinfo['extension'])) {
249                         Logger::warning('extension isn\'t set.', ['filename' => $filename]);
250                 }
251                 $ext = $pathinfo['extension'] ?? '';
252
253                 if ($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)) {
254                         return ['error' => DI::l10n()->t('File has an invalid extension, it should be one of %s.', implode(', ', $this->allowedExtensions))];
255                 }
256
257                 if ($this->file->save()) {
258                         return [
259                                 'success' => true,
260                                 'path' => $this->file->getPath(),
261                                 'filename' => $filename . '.' . $ext
262                         ];
263                 } else {
264                         return [
265                                 'error' => DI::l10n()->t('Upload was cancelled, or server error encountered'),
266                                 'path' => $this->file->getPath(),
267                                 'filename' => $filename . '.' . $ext
268                         ];
269                 }
270         }
271 }