]> git.mxchange.org Git - friendica-addons.git/blob - js_upload/js_upload.php
Upgrade phpunit version in PHP-CI
[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(array &$b)
29 {
30         $b['default_upload'] = false;
31
32         DI::page()->registerStylesheet(__DIR__ . '/file-uploader/client/fileuploader.css');
33         DI::page()->registerFooterScript(__DIR__ . '/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' => Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize')),
43         ]);
44 }
45
46 function js_upload_post_init(array &$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 = Strings::getBytesFromShorthand(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::info('mod/photos.php: photos_post(): error uploading photo: ' . $result['error']);
65                 echo json_encode($result);
66                 exit();
67         }
68
69         $js_upload_result = $result;
70 }
71
72 function js_upload_post_file(array &$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(int &$b)
85 {
86         global $js_upload_jsonresponse;
87
88         Logger::notice('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         /**
204          * Returns array('success'=>true) or array('error'=>'error message')
205          */
206         function handleUpload()
207         {
208                 if (!$this->file) {
209                         return ['error' => DI::l10n()->t('No files were uploaded.')];
210                 }
211
212                 $size = $this->file->getSize();
213
214                 if ($size == 0) {
215                         return ['error' => DI::l10n()->t('Uploaded file is empty')];
216                 }
217
218 //              if ($size > $this->sizeLimit) {
219
220 //                      return array('error' => DI::l10n()->t('Uploaded file is too large'));
221 //              }
222
223
224                 $maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
225
226                 if (($maximagesize) && ($size > $maximagesize)) {
227                         return ['error' => DI::l10n()->t('Image exceeds size limit of %s', Strings::formatBytes($maximagesize))];
228                 }
229
230                 $pathinfo = pathinfo($this->file->getName());
231                 $filename = $pathinfo['filename'];
232
233                 if (!isset($pathinfo['extension'])) {
234                         Logger::warning('extension isn\'t set.', ['filename' => $filename]);
235                 }
236                 $ext = $pathinfo['extension'] ?? '';
237
238                 if ($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)) {
239                         return ['error' => DI::l10n()->t('File has an invalid extension, it should be one of %s.', implode(', ', $this->allowedExtensions))];
240                 }
241
242                 if ($this->file->save()) {
243                         return [
244                                 'success' => true,
245                                 'path' => $this->file->getPath(),
246                                 'filename' => $filename . '.' . $ext
247                         ];
248                 } else {
249                         return [
250                                 'error' => DI::l10n()->t('Upload was cancelled, or server error encountered'),
251                                 'path' => $this->file->getPath(),
252                                 'filename' => $filename . '.' . $ext
253                         ];
254                 }
255         }
256 }