-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Expand file tree
/
Copy pathApiController.php
More file actions
437 lines (383 loc) · 14.5 KB
/
Copy pathApiController.php
File metadata and controls
437 lines (383 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
<?php
/**
* @package Joomla.Administrator
* @subpackage com_media
*
* @copyright (C) 2017 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\Component\Media\Administrator\Controller;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\CMS\MVC\Model\BaseModel;
use Joomla\CMS\Response\JsonResponse;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Session\Session;
use Joomla\Component\Media\Administrator\Exception\FileExistsException;
use Joomla\Component\Media\Administrator\Exception\FileNotFoundException;
use Joomla\Component\Media\Administrator\Exception\InvalidPathException;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/**
* Api Media Controller
*
* This is NO public api controller, it is internal for the com_media component only!
*
* @since 4.0.0
*/
class ApiController extends BaseController
{
/**
* Execute a task by triggering a method in the derived class.
*
* @param string $task The task to perform. If no matching task is found, the '__default' task is executed, if defined.
*
* @return void
*
* @since 4.0.0
* @throws \Exception
*/
public function execute($task)
{
$method = $this->input->getMethod();
$this->task = $task;
try {
// Check token for requests which do modify files (all except get requests)
if ($method !== 'GET' && !Session::checkToken('json')) {
throw new \InvalidArgumentException(Text::_('JINVALID_TOKEN_NOTICE'), 403);
}
$doTask = strtolower($method) . ucfirst($task);
// Record the actual task being fired
$this->doTask = $doTask;
if (!\in_array($this->doTask, $this->taskMap)) {
throw new \Exception(Text::sprintf('JLIB_APPLICATION_ERROR_TASK_NOT_FOUND', $task), 405);
}
$data = $this->$doTask();
// Return the data
$this->sendResponse($data);
} catch (FileNotFoundException $e) {
$this->sendResponse($e, 404);
} catch (FileExistsException $e) {
$this->sendResponse($e, 409);
} catch (InvalidPathException $e) {
$this->sendResponse($e, 400);
} catch (\Exception $e) {
$errorCode = 500;
if ($e->getCode() > 0) {
$errorCode = $e->getCode();
}
$this->sendResponse($e, $errorCode);
}
}
/**
* Files Get Method
*
* Examples:
*
* - GET a list of folders below the root:
* index.php?option=com_media&task=api.files
* /api/files
* - GET a list of files and subfolders of a given folder:
* index.php?option=com_media&task=api.files&format=json&path=/sampledata/cassiopeia
* /api/files/sampledata/cassiopeia
* - GET a list of files and subfolders of a given folder for a given search term:
* use recursive=1 to search recursively in the working directory
* index.php?option=com_media&task=api.files&format=json&path=/sampledata/cassiopeia&search=nasa5
* /api/files/sampledata/cassiopeia?search=nasa5
* To look up in same working directory set flag recursive=0
* index.php?option=com_media&task=api.files&format=json&path=/sampledata/cassiopeia&search=nasa5&recursive=0
* /api/files/sampledata/cassiopeia?search=nasa5&recursive=0
* - GET file information for a specific file:
* index.php?option=com_media&task=api.files&format=json&path=/sampledata/cassiopeia/test.jpg
* /api/files/sampledata/cassiopeia/test.jpg
* - GET a temporary URL to a given file
* index.php?option=com_media&task=api.files&format=json&path=/sampledata/cassiopeia/test.jpg&url=1&temp=1
* /api/files/sampledata/cassiopeia/test.jpg&url=1&temp=1
* - GET a temporary URL to a given file
* index.php?option=com_media&task=api.files&format=json&path=/sampledata/cassiopeia/test.jpg&url=1
* /api/files/sampledata/cassiopeia/test.jpg&url=1
*
* @return array The data to send with the response
*
* @since 4.0.0
* @throws \Exception
*/
public function getFiles()
{
// Grab options
$options = [];
$options['url'] = $this->input->getBool('url', false);
$options['search'] = $this->input->getString('search', '');
$options['recursive'] = $this->input->getBool('recursive', true);
$options['content'] = $this->input->getBool('content', false);
return $this->getModel()->getFiles($this->getAdapter(), $this->getPath(), $options);
}
/**
* Files delete Method
*
* Examples:
*
* - DELETE an existing folder in a specific folder:
* index.php?option=com_media&task=api.files&format=json&path=/sampledata/cassiopeia/test
* /api/files/sampledata/cassiopeia/test
* - DELETE an existing file in a specific folder:
* index.php?option=com_media&task=api.files&path=/sampledata/cassiopeia/test.jpg
* /api/files/sampledata/cassiopeia/test.jpg
*
* @return null
*
* @since 4.0.0
* @throws \Exception
*/
public function deleteFiles()
{
if (!$this->app->getIdentity()->authorise('core.delete', 'com_media')) {
throw new \Exception(Text::_('JLIB_APPLICATION_ERROR_DELETE_NOT_PERMITTED'), 403);
}
$this->getModel()->delete($this->getAdapter(), $this->getPath());
return null;
}
/**
* Files Post Method
*
* Examples:
*
* - POST a new file or folder into a specific folder, the file or folder information is returned:
* index.php?option=com_media&task=api.files&format=json&path=/sampledata/cassiopeia
* /api/files/sampledata/cassiopeia
*
* New file body:
* {
* "name": "test.jpg",
* "content":"base64 encoded image"
* }
* New folder body:
* {
* "name": "test",
* }
*
* @return array The data to send with the response
*
* @since 4.0.0
* @throws \Exception
*/
public function postFiles()
{
if (!$this->app->getIdentity()->authorise('core.create', 'com_media')) {
throw new \Exception(Text::_('JLIB_APPLICATION_ERROR_CREATE_RECORD_NOT_PERMITTED'), 403);
}
$adapter = $this->getAdapter();
$path = $this->getPath();
// Get the data depending on the request type
if ($this->input->json->count()) {
$content = $this->input->json;
$mediaContent = base64_decode($content->get('content', '', 'raw'));
$mediaLength = $mediaContent ? \strlen($mediaContent) : 0;
} else {
$content = $this->input->post;
$mediaContent = null;
$mediaLength = 0;
$file = $this->input->files->get('content', []);
if ($file && empty($file['error'])) {
// Open the uploaded file as a stream, because whole media API are expecting already loaded data, but we do not want to.
$mediaContent = fopen($file['tmp_name'], 'r');
$mediaLength = $file['size'];
} elseif (!empty($file['error'])) {
throw new \Exception(Text::_('JLIB_MEDIA_ERROR_UPLOAD_INPUT'));
}
}
$name = $content->getString('name');
$override = $content->getBool('override', false);
if ($mediaContent) {
$this->checkFileSize($mediaLength);
// A file needs to be created
$name = $this->getModel()->createFile($adapter, $name, $path, $mediaContent, $override);
} else {
// A folder needs to be created
$name = $this->getModel()->createFolder($adapter, $name, $path, $override);
}
$options = [];
$options['url'] = $this->input->getBool('url', false);
if (\is_resource($mediaContent)) {
fclose($mediaContent);
}
return $this->getModel()->getFile($adapter, $path . '/' . $name, $options);
}
/**
* Files Put method
*
* Examples:
*
* - PUT a media file, the file or folder information is returned:
* index.php?option=com_media&task=api.files&format=json&path=/sampledata/cassiopeia/test.jpg
* /api/files/sampledata/cassiopeia/test.jpg
*
* Update file body:
* {
* "content":"base64 encoded image"
* }
*
* - PUT move a file, folder to another one
* path : will be taken as the source
* index.php?option=com_media&task=api.files&format=json&path=/sampledata/cassiopeia/test.jpg
* /api/files/sampledata/cassiopeia/test.jpg
*
* JSON body:
* {
* "newPath" : "/path/to/destination",
* "move" : "1"
* }
*
* - PUT copy a file, folder to another one
* path : will be taken as the source
* index.php?option=com_media&task=api.files&format=json&path=/sampledata/cassiopeia/test.jpg
* /api/files/sampledata/cassiopeia/test.jpg
*
* JSON body:
* {
* "newPath" : "/path/to/destination",
* "move" : "0"
* }
*
* @return array The data to send with the response
*
* @since 4.0.0
* @throws \Exception
*/
public function putFiles()
{
if (!$this->app->getIdentity()->authorise('core.edit', 'com_media')) {
throw new \Exception(Text::_('JLIB_APPLICATION_ERROR_EDIT_NOT_PERMITTED'), 403);
}
$adapter = $this->getAdapter();
$path = $this->getPath();
// Get the data depending on the request type
if ($this->input->json->count()) {
$content = $this->input->json;
$mediaContent = base64_decode($content->get('content', '', 'raw'));
$mediaLength = $mediaContent ? \strlen($mediaContent) : 0;
} else {
$content = $this->input->post;
$mediaContent = null;
$mediaLength = 0;
$file = $this->input->files->get('content', []);
if ($file && empty($file['error'])) {
// Open the uploaded file as a stream, because whole media API are expecting already loaded data, but we do not want to.
$mediaContent = fopen($file['tmp_name'], 'r');
$mediaLength = $file['size'];
} elseif (!empty($file['error'])) {
throw new \Exception(Text::_('JLIB_MEDIA_ERROR_UPLOAD_INPUT'));
}
}
$name = basename($path);
$newPath = $content->getString('newPath', null);
$move = $content->get('move', true);
if ($mediaContent) {
$this->checkFileSize($mediaLength);
$this->getModel()->updateFile($adapter, $name, str_replace($name, '', $path), $mediaContent);
}
if ($newPath != null && $newPath !== $adapter . ':' . $path) {
list($destinationAdapter, $destinationPath) = explode(':', $newPath, 2);
if ($move) {
$destinationPath = $this->getModel()->move($adapter, $path, $destinationPath, false);
} else {
$destinationPath = $this->getModel()->copy($adapter, $path, $destinationPath, false);
}
$path = $destinationPath;
}
if (\is_resource($mediaContent)) {
fclose($mediaContent);
}
return $this->getModel()->getFile($adapter, $path);
}
/**
* Send the given data as JSON response in the following format:
*
* {"success":true,"message":"ok","messages":null,"data":[{"type":"dir","name":"banners","path":"//"}]}
*
* @param mixed $data The data to send
* @param integer $responseCode The response code
*
* @return void
*
* @since 4.0.0
*/
private function sendResponse($data = null, int $responseCode = 200)
{
// Set the correct content type
$this->app->setHeader('Content-Type', 'application/json');
// Set the status code for the response
http_response_code($responseCode);
// Send the data
echo new JsonResponse($data);
$this->app->close();
}
/**
* Method to get a model object, loading it if required.
*
* @param string $name The model name. Optional.
* @param string $prefix The class prefix. Optional.
* @param array $config Configuration array for model. Optional.
*
* @return BaseModel|boolean Model object on success; otherwise false on failure.
*
* @since 4.0.0
*/
public function getModel($name = 'Api', $prefix = 'Administrator', $config = [])
{
return parent::getModel($name, $prefix, $config);
}
/**
* Performs file size checks if it is allowed to be saved.
*
* @param integer $fileSize The size of submitted file
*
* @return void
*
* @since 4.4.9
* @throws \Exception
*/
private function checkFileSize(int $fileSize)
{
$params = ComponentHelper::getParams('com_media');
$paramsUploadMaxsize = $params->get('upload_maxsize', 0) * 1024 * 1024;
if ($paramsUploadMaxsize > 0 && $fileSize > $paramsUploadMaxsize) {
$link = 'index.php?option=com_config&view=component&component=com_media';
$output = HTMLHelper::_('link', Route::_($link), Text::_('JOPTIONS'));
throw new \Exception(Text::sprintf('COM_MEDIA_ERROR_WARNFILETOOLARGE', $output), 403);
}
}
/**
* Get the Adapter.
*
* @return string
*
* @since 4.0.0
*/
private function getAdapter()
{
$parts = explode(':', $this->input->getString('path', ''), 2);
if (\count($parts) < 1) {
return null;
}
return $parts[0];
}
/**
* Get the Path.
*
* @return string
*
* @since 4.0.0
*/
private function getPath()
{
$parts = explode(':', $this->input->getString('path', ''), 2);
if (\count($parts) < 2) {
return null;
}
return $parts[1];
}
}