-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathplugin.php
More file actions
executable file
·601 lines (506 loc) · 13.9 KB
/
plugin.php
File metadata and controls
executable file
·601 lines (506 loc) · 13.9 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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
<?php
/**
* @package Joomla.Site
* @subpackage Com_api
*
* @copyright Copyright (C) 2009-2014 Techjoomla, Tekdi Technologies Pvt. Ltd. All rights reserved.
* @license GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
* @link http://techjoomla.com
* Work derived from the original RESTful API by Techjoomla (https://github.com/techjoomla/Joomla-REST-API)
* and the com_api extension by Brian Edgerton (http://www.edgewebworks.com)
*/
defined('_JEXEC') or die('Restricted access');
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Factory;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Filesystem\File;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Table\Table;
use Joomla\CMS\User\User;
use Joomla\Registry\Registry;
use Joomla\CMS\Uri\Uri;
/**
* API_plugin base class
* API resource class
*
* @since 1.0
*/
class ApiPlugin extends CMSPlugin
{
protected $user = null;
protected $format = null;
private $response = null;
protected $request = null;
protected $request_method = null;
protected $request_headers = null;
protected $resource_acl = array();
protected $cache_folder = 'com_api';
protected $content_types = array('application/json' => 'json', 'application/xml' => 'xml');
public static $instances = array();
public static $plg_prefix = 'plgAPI';
public static $plg_path = '/plugins/api/';
public $err_code = 403;
public $err_message = 'JGLOBAL_AUTH_EMPTY_PASS_NOT_ALLOWED';
public $response_id = '';
public $customAttributes = null;
/**
* create instance
*
* @param STRING $name name
*
* @return Obj
*
* @since 1.0
*/
public static function getInstance($name)
{
$app = Factory::getApplication();
$param_path = JPATH_BASE . self::$plg_path . $name . '.xml';
$plugin = PluginHelper::getPlugin('api', $name);
PluginHelper::importPlugin("api", $name);
if (isset(self::$instances[$name]))
{
return self::$instances[$name];
}
if (version_compare(JVERSION, '4.0', 'ge'))
{
$dispatcher = $app->getDispatcher();
}
else if (version_compare(JVERSION, '3.0', 'ge'))
{
$dispatcher = JEventDispatcher::getInstance();
}
else
{
self::$plg_path = self::$plg_path . $plugin->name . '/';
}
if (empty($plugin))
{
ApiError::raiseError(400, Text::sprintf('COM_API_PLUGIN_CLASS_NOT_FOUND', ucfirst($name)), 'APINotFoundException');
}
$plgfile = JPATH_BASE . self::$plg_path . $name . '/' . $name . '.php';
if (!File::exists($plgfile))
{
ApiError::raiseError(400, Text::sprintf('COM_API_FILE_NOT_FOUND', ucfirst($name)), 'APINotFoundException');
}
include_once $plgfile;
$class = self::$plg_prefix . ucwords($name);
if (!class_exists($class))
{
ApiError::raiseError(400, Text::sprintf('COM_API_PLUGIN_CLASS_NOT_FOUND', ucfirst($name)), 'APINotFoundException');
}
$cparams = ComponentHelper::getParams('com_api');
$enabled = PluginHelper::isEnabled("api", $name);
$handler = new $class($dispatcher, array('params' => $cparams));
$handler->set('params', $cparams);
$call_methd = $app->input->server->get('REQUEST_METHOD', '', 'STRING');
// Switch case for differ calling method
switch ($call_methd)
{
case 'GET':
$handler->set('component', $app->input->get('app', '', 'CMD'));
$handler->set('resource', $app->input->get('resource', '', 'CMD'));
$handler->set('format', $handler->negotiateContent($app->input->get('output', null, 'CMD')));
break;
case 'POST':
$handler->set('component', $app->input->get('app', '', 'CMD'));
$handler->set('resource', $app->input->get('resource', '', 'CMD'));
$handler->set('format', $handler->negotiateContent($app->input->get('output', null, 'CMD')));
break;
case 'PUT':
$handler->set('component', $app->input->get('app', '', 'CMD'));
$handler->set('resource', $app->input->get('resource', '', 'CMD'));
$handler->set('format', $handler->negotiateContent($app->input->get('output', null, 'CMD')));
break;
case 'DELETE':
$handler->set('component', $app->input->get('app', '', 'CMD'));
$handler->set('resource', $app->input->get('resource', '', 'CMD'));
$handler->set('format', $handler->negotiateContent($app->input->get('output', null, 'CMD')));
break;
case 'PATCH':
$handler->set('component', $app->input->get('app', '', 'CMD'));
$handler->set('resource', $app->input->get('resource', '', 'CMD'));
$handler->set('format', $handler->negotiateContent($app->input->post->get('output', null, 'CMD')));
break;
}
$handler->set('request_method', $app->input->server->get('REQUEST_METHOD', '', 'STRING'));
$handler->set('customAttributes', new Registry);
self::$instances[$name] = $handler;
return self::$instances[$name];
}
/**
* Constructor
*
* @param STRING &$subject subject
* @param array $config config
*
* @since 1.0
*/
public function __construct(&$subject, $config = array())
{
// Parent::__construct($subject, $config);
}
/**
* Intelligently negotiates the content type based on explicit declaration or header (HTTP_ACCEPT) declaration.
* If neither is present, it will default to the component parameter default.
*
* @param string $output String content declaration (usually 'json' or 'xml')
*
* @return NULL|mixed
*
* @since 1.0
*/
protected function negotiateContent($output = null)
{
$format = null;
if (is_null($output) && isset($_SERVER['HTTP_ACCEPT']))
{
if (in_array($_SERVER['HTTP_ACCEPT'], array_keys($this->content_types)))
{
$format = $_SERVER['HTTP_ACCEPT'];
}
}
elseif (in_array($output, $this->content_types))
{
$flipped = array_flip($this->content_types);
$format = $flipped[$output];
}
if (is_null($format))
{
$output = $this->params->get('default_content_type', 'json');
$flipped = array_flip($this->content_types);
$format = $flipped[$output];
}
return $format;
}
/**
* Sets the access level of a given resource
*
* @param string $resource Resource name
* @param string $access The access string (public or protected)
* @param string $method The request method for the resource
*
* @return boolean
*
* @since 1.0
*/
final public function setResourceAccess($resource, $access, $method = 'GET')
{
$method = strtoupper($method);
$this->resource_acl[$resource][$method] = $access;
return true;
}
/**
* Checks the access level of a given resource
*
* @param string $resource Resource name
* @param string $method The requested method for that resource
* @param boolean $returnParamsDefault Set to true to have the component parameters default access level returned if not explicitly set
*
* @return mixed
*
* @since 1.0
*/
final public function getResourceAccess($resource, $method = 'GET', $returnParamsDefault = true)
{
$method = strtoupper($method);
if (isset($this->resource_acl[$resource]) && isset($this->resource_acl[$resource][$method]))
{
return $this->resource_acl[$resource][$method];
}
else
{
if ($returnParamsDefault)
{
return $this->params->get('resource_access', 'protected');
}
else
{
return false;
}
}
}
/**
* Finds and calls the requested resource
*
* @param string $resource_name Requested resource name
*
* @return string
*
* @since 1.0
*/
final public function fetchResource($resource_name = null)
{
$this->log();
if ($resource_name == null)
{
$resource_name = $this->get('resource');
}
$resource_obj = ApiResource::getInstance($resource_name, $this);
if ($resource_obj === false)
{
$this->checkInternally($resource_name);
}
$user = APIAuthentication::authenticateRequest();
$this->set('user', $user);
$session = Factory::getSession();
$session->set('user', $user);
$access = $this->getResourceAccess($resource_name, $this->request_method);
if ($access == 'protected' && $user === false)
{
ApiError::raiseError(403, APIAuthentication::getAuthError(), 'APIUnauthorisedException');
}
if (! $this->checkRequestLimit())
{
ApiError::raiseError(403, Text::_('COM_API_RATE_LIMIT_EXCEEDED'), 'APIUnauthorisedException');
}
$this->lastUsed();
if ($resource_obj !== false)
{
$resource_obj->invoke();
}
else
{
call_user_func(array($this, $resource_name));
}
return $this;
}
/**
* Checks to see if resource exists as a method on the main plugin
*
* @param string $resource_name Requested resource name
*
* @return boolean
*
* @since 1.0
*/
private function checkInternally($resource_name)
{
if (! method_exists($this, $resource_name))
{
ApiError::raiseError(404, Text::sprintf('COM_API_PLUGIN_METHOD_NOT_FOUND', ucfirst($resource_name)), 'APINotFoundException');
}
if (! is_callable(array($this, $resource_name)))
{
ApiError::raiseError(404, Text::sprintf('COM_API_PLUGIN_METHOD_NOT_CALLABLE', ucfirst($resource_name)), 'APINotFoundException');
}
return true;
}
/**
* Determines whether or not a request is over the time limit
*
* @return boolean
*
* @since 1.0
*/
private function checkRequestLimit()
{
$app = Factory::getApplication();
$limit = $this->params->get('request_limit', 0);
if ($limit == 0)
{
return true;
}
$hash = $app->input->get('key', '', 'STRING');
$ip_address = $app->input->server->get('REMOTE_ADDR', '', 'STRING');
$time = $this->params->get('request_limit_time', 'hour');
switch ($time)
{
case 'day':
$offset = 60 * 60 * 24;
break;
case 'minute':
$offset = 60;
break;
case 'hour':
default:
$offset = 60 * 60;
break;
}
$query_time = time() - $offset;
$db = Factory::getDBO();
$query = $db->getQuery(true);
$query->select('COUNT(*)');
$query->from($db->quoteName('#__api_logs'));
$query->where($db->quoteName('time') . ' >= ' . $db->quote($query_time) . ' AND ' . $db->quoteName('hash') . ' = ' . $db->Quote($hash));
$db->setQuery($query);
$result = $db->loadResult();
if ($result >= $limit)
{
return false;
}
else
{
return true;
}
}
/**
* Logs the incoming request to the database
*
* @return mixed
*
* @since 1.0
*/
private function log()
{
if (! $this->params->get('log_requests'))
{
$this->response_id = uniqid();
return;
}
$app = Factory::getApplication();
// For exclude password from log
$params = ComponentHelper::getParams('com_api');
$excludes = $params->get('exclude_log');
$raw_post = file_get_contents('php://input');
$redactions = explode(",", $excludes);
$req_url = Uri::current() . '?' . Factory::getURI()->getQuery();
switch ($app->input->server->get('CONTENT_TYPE'))
{
case 'application/x-www-form-urlencoded':
default:
mb_parse_str($raw_post, $post_data);
array_walk(
$post_data, function(&$value, $key, $redactions) {
$value = in_array($key, $redactions) ? '**REDACTED**' : $value;
}, $redactions
);
break;
case 'application/json':
case 'application/javascript':
$post_data = json_decode($raw_post);
array_walk(
$post_data, function(&$value, $key, $redactions) {
$value = (is_string($value) && in_array($key, $redactions)) ? '**REDACTED**' : $value;
}, $redactions
);
$post_data = json_encode($post_data, JSON_PRETTY_PRINT);
break;
}
$table = Table::getInstance('Log', 'ApiTable');
$date = Factory::getDate();
$table->hash = $app->input->get('key', '', 'STRING');
$table->ip_address = $app->input->server->get('REMOTE_ADDR', '', 'STRING');
$table->time = $date->toSql();
$table->request = $req_url;
$table->request_method = $this->request_method;
$table->post_data = $post_data;
$table->store();
$this->response_id = $table->id;
}
/**
* Sets the last updated time for a key
*
* @return mixed
*
* @since 1.0
*/
private function lastUsed()
{
$app = Factory::getApplication();
$table = Table::getInstance('Key', 'ApiTable');
$hash = $app->input->get('key', '', 'STRING');
$table->setLastUsed($hash);
}
/**
* Setter method for $response instance variable
*
* @param STRING $data The plugin's output
*
* @return mixed
*
* @since 1.0
*/
public function setResponse($data)
{
// For backward compatability -- TODO
if (!isset($data->result) && !empty($data))
{
$data->result = clone $data;
}
$this->set('response', $data);
}
/**
* Setter method for $response instance variable
*
* @param STRING $error The plugin's output
*
* @param STRING $data The plugin's output
*
* @return mixed
*
* @since 2.0
*/
public function setApiResponse($error, $data)
{
$result = new stdClass;
$result->err_code = '';
$result->err_message = '';
$result->data = new stdClass;
if ($error)
{
$result->err_code = $this->err_code;
$result->err_message = Text::_($this->err_message);
}
else
{
$result->data = $data;
}
$this->set('response', $result);
}
/**
* Determines the method with which to encode the output based on the requested content type
*
* @return STRING
*
* @since 1.0
*/
public function encode()
{
$document = Factory::getDocument();
$document->setMimeEncoding($this->format);
$format_name = $this->content_types[$this->format];
$method = 'to' . ucfirst($format_name);
if (! method_exists($this, $method))
{
ApiError::raiseError(406, Text::_('COM_API_PLUGIN_NO_ENCODER'));
}
if (! is_callable(array($this, $method)))
{
ApiError::raiseError(404, Text::_('COM_API_PLUGIN_NO_ENCODER'));
}
return $this->$method();
}
/**
* Method to get current logged in API user
*
* @return User
*/
public function getUser()
{
return $this->user;
}
/**
* Method to get value of the property
*
* @return User
*/
public function get($property, $default = null)
{
if (!isset($this->$property))
{
return $default;
}
return $this->$property;
}
/**
* Method to set value of the property
*
* @return User
*/
public function set($property, $value = null)
{
$this->$property = $value;
}
}