This repository was archived by the owner on Dec 6, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathPlacid_RequestsService.php
executable file
·546 lines (465 loc) · 13.2 KB
/
Placid_RequestsService.php
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
<?php
/**
* Placid requests service class
*
* This class does most of the heavy lifting when it comes to making requests, authenticating
* and putting in querys, paths all that config stuff.
*
* @author Alec Ritson. <[email protected]>
* @copyright Copyright (c) 2014, Alec Ritson.
* @license http://buildwithcraft.com/license Craft License Agreement
* @link http://itsalec.co.uk
* @package craft.plugins.placid.services
* @since 0.8.0
*/
namespace Craft;
use Guzzle\Http\Client;
use Guzzle\Http\Message\EntityEnclosingRequest;
use Guzzle\Http\Exception\RequestException;
class Placid_RequestsService extends PlacidService
{
/**
* Placid plugin settings
* @var Array
*/
protected $placid_settings;
/**
* Placid request config
* @var Array
*/
protected $config;
/**
* The cache id of the request
* @var String
*/
protected $cacheId;
public function __construct()
{
parent::__construct();
$this->model = new Placid_RequestsModel;
$this->record = new Placid_RequestsRecord();
// Get the plugin settings
$this->placid_settings = $this->settings;
}
/**
* Make the request
*
* This method will create a new client and get a response from a Guzzle request
*
* @param string|null $handle The handle of the request record
*
* @return array the req
*/
public function request($handle = null, array $config = array())
{
// Get our request from the database...or not
if(!array_key_exists('url', $config))
{
$model = $this->findRequestByHandle($handle);
}
else
{
$model = null;
}
$this->config = array_merge(
array(
'method' => 'GET',
'cache' => ($model ? $model->cache : true),
'duration' => 3600, // 1 hour
),
$config
);
// Handle any changes to api gracefully
$this->_swapDeprecatedConfig('path', 'segments');
$this->_swapDeprecatedConfig('query', 'params');
// Create a new guzzle client
$client = new Client();
if($model)
{
$request = $this->_createRequest($client, $model);
}
else
{
$request = $client->createRequest($this->config['method'], $this->config['url']);
}
// Get a cached request
$cachedRequest = craft()->placid_cache->get($this->_getCacheId());
// Import the onBeforeRequest event
Craft::import('plugins.placid.events.PlacidBeforeRequestEvent');
$event = new PlacidBeforeRequestEvent($this, array('request' => $request));
craft()->placid_requests->onBeforeRequest($event);
// Check to make sure no other plugins have change anything
if($event->makeRequest)
{
if( (! $this->config['cache'] || ! $cachedRequest) && ! $event->bypassCache)
{
$response = $this->_getResponse($client, $request);
}
else
{
$response = $cachedRequest;
}
}
else {
return false;
}
Craft::import('plugins.placid.events.PlacidAfterRequestEvent');
$event = new PlacidAfterRequestEvent($this, array('response' => $response));
$this->onAfterRequest($event);
return $response;
}
/**
* Create a new model object of a request
*
* @param array $attributes The attributes to save against the model
*
* @return model returns Placid_RequestsModel object
*
*/
public function newRequest($attributes = array())
{
// Create the new Placid_RequestsModel
// -----------------------------------------------------------------------------
$model = new Placid_RequestsModel();
// Set the attributes from the array
$model->setAttributes($attributes);
// Return the Placid_RequestsModel model
return $model;
}
/**
* Get all placid requests
*
* @deprecated Deprecated in 1.3. Use {@link AppBehavior::getBuild() craft()->placid_requests->getAll()} instead. All these sort of methods are being combined for a more streamlined, DRY API.
*
* @return requests model object
*/
public function getAllRequests()
{
$args = array('order' => 't.id');
$records = $this->record->findAll($args);
return Placid_RequestsModel::populateModels($records, 'id');
}
/**
* Find request by ID
*
* @param string $id
*
* @deprecated Deprecated in 1.3. Use {@link AppBehavior::getBuild() craft()->placid_requests->getById()} instead. All these sort of methods are being combined for a more streamlined, DRY API.
*
* @return request model object
*/
public function findRequestById($id)
{
// Determine if there is a request record and return it
// -----------------------------------------------------------------------------
if($record = $this->record->findByPk($id))
{
return Placid_RequestsModel::populateModel($record);
}
}
/**
* Return the request
*
* @param string $handle
*
* @param array $options
*
* @throws Exception
*
* @return mixed
*/
public function findRequestByHandle($handle)
{
Craft::log(__METHOD__, LogLevel::Info, true);
// Get the request record by its handle
// ---------------------------------------------
$record = Placid_RequestsRecord::model()->find(
'handle=:handle',
array(
':handle' => $handle
)
);
if($record)
{
return Placid_RequestsModel::populateModel($record);
}
else
{
throw new Exception(Craft::t('Can\'t find request with handle "{handle}"', array('handle' => $handle)));
}
}
// Record Methods
// =============================================================================
/**
* Save a request
*
* @param object RequestsModel object
*
* @return bool true or false if request has been saved
*/
public function saveRequest(Placid_RequestsModel &$model)
{
// Determine whether this is an existing request or if we need to create a new one
// --------------------------------------------------------------------------------
if($id = $model->getAttribute('id'))
{
$record = $this->record->findByPk($id);
}
else
{
$record = new Placid_RequestsRecord();
}
// Get the attributes from the passed model
$attributes = $model->getAttributes();
// Set the new attributes to the record
$record->setAttributes($attributes, false);
// Save the new request
// -----------------------------------------------------------------------------
if($record->save())
{
$model->setAttribute('id', $record->getAttribute('id'));
return true;
}
else
{
$model->addErrors($record->getErrors());
return false;
}
}
/**
* Delete a request from the database.
*
* @param int $id
* @return int The number of rows affected
*/
public function deleteRecordById($id)
{
// Get all a users widgets
$this->_deleteWidgetsByRecord($id);
return $this->record->deleteByPk($id);
}
// Events
// =============================================================================
/**
* Fires an 'onBeforeRequest' event.
*
* @param PlacidBeforeRequestEvent $event
*/
public function onBeforeRequest(PlacidBeforeRequestEvent $event)
{
$this->raiseEvent('onBeforeRequest', $event);
}
/**
* Fires an 'onAfterRequest' event.
*
* @param PlacidAfterRequestEvent $event
*/
public function onAfterRequest(PlacidAfterRequestEvent $event)
{
$this->raiseEvent('onAfterRequest', $event);
}
// Private Methods
// =============================================================================
/**
* Create a new request object
*
* @param array $attributes The attributes to save against the model
*
* @return object returns EntityEnclosingRequest $request
*
*/
private function _createRequest($client, $record = null)
{
if($record && $recordUrl = $record->getAttribute('url'))
{
$this->config['url'] = $recordUrl;
}
$this->cacheId = $this->config['url'];
$request = $client->createRequest($this->config['method'], $this->config['url']);
if(array_key_exists('body', $this->config))
{
$request->setBody($this->config['body']);
}
// Is a new path set?
if(array_key_exists('path', $this->config))
{
$request->setPath($this->config['path']);
}
// Have headers been set in the admin area?
// If so add them in otherwise check if there are any passed through the template
$cpHeaders = $record->getAttribute('headers');
if($cpHeaders)
{
foreach($cpHeaders as $k => $q)
{
$request->addHeader($q['key'], $q['value']);
}
}
elseif(array_key_exists('headers', $this->config) && is_array($this->config['headers']))
{
foreach ($this->config['headers'] as $key => $value)
{
$request->addHeader($key, $value);
}
}
// Get the parameters from the record
$cpQuery = $record->getAttribute('params');
if($request->getMethod() == 'GET')
{
// Get the query from the request
$query = $request->getQuery();
}
else
{
$query = $request->getPostFields();
}
// If they exist, add them to the query
if($cpQuery && is_array($cpQuery))
{
foreach($cpQuery as $k => $q)
{
$query->set($q['key'], $q['value']);
}
}
elseif(array_key_exists('query', $this->config))
{
foreach($this->config['query'] as $key => $value)
{
$query->set($key, $value);
}
}
if($query)
{
$this->cacheId .= '?' . $query;
}
// Do we need to do some OAuth magic?
if($provider = $record->getAttribute('oauth'))
{
$this->_authenticate($request,$provider);
}
// Has the request got an access token we need to attach?
if($tokenId = $record->getAttribute('tokenId'))
{
$tokenModel = craft()->placid_token->findTokenById($tokenId);
$request->addHeader('Authorization', 'Bearer ' . $tokenModel->encoded_token);
}
return $request;
}
/**
* Get the response from a client and request
*
* @param Client $client a guzzle client
* @param object $request a guzzle request object
* @return array the response
*/
private function _getResponse(Client $client, $request)
{
try {
$response = $client->send($request);
} catch(RequestException $e) {
PlacidPlugin::log($e->getMessage(), LogLevel::Error);
$message = array('failed' => true);
if(method_exists($e, 'getResponse'))
{
$response = $e->getResponse();
$message['statusCode'] = $response->getStatusCode();
}
if(craft()->request->isAjaxRequest())
{
return $message;
}
else {
return null;
}
}
$contentType = preg_match('/.+?(?=;)/', $response->getContentType(), $matches);
$contentType = implode($matches, '');
if($contentType == 'text/xml')
{
try {
$output = $response->xml();
} catch (\Guzzle\Common\Exception\RuntimeException $e) {
PlacidPlugin::log($e->getMessage(), LogLevel::Error);
$output = null;
}
}
else
{
try {
$output = $response->json();
} catch (\Guzzle\Common\Exception\RuntimeException $e) {
PlacidPlugin::log($e->getMessage(), LogLevel::Error);
$output = null;
}
}
if($this->config['cache'])
{
craft()->placid_cache->set($this->_getCacheId(), $output, $this->config['duration']);
}
return $output;
}
/**
* Authenticate the request, used if OAuth provider is chosen on request creation
*
* @param string $auth
* @param object $client
* @return boolean
*/
private function _authenticate($client, $auth)
{
$provider = craft()->oauth->getProvider($auth);
$token = craft()->placid_oAuth->getToken($auth);
$provider->setToken($token);
$subscriber = $provider->getSubscriber();
$client->addSubscriber($subscriber);
}
/**
* If there have been any config naming changes, this function will handle it
* gracefully so templates don't start failing everywhere because I change my
* mind too much!
*
* @param String $new The new config key
* @param String $old The old config key to be replaced
* @return Bool Whether it was a success
*/
private function _swapDeprecatedConfig($new, $old)
{
// Segments is now called path, allow for templates still using segments
if(array_key_exists($old, $this->config))
{
$this->config[$new] = $this->config[$old];
unset($this->config[$old]);
}
return true;
}
/**
* Deletes a Widget based on the record
* @param Int $id The id of the record
* @return Bool True
*/
private function _deleteWidgetsByRecord($id)
{
$record = $this->record->findByPk($id);
$currentWidgets = craft()->dashboard->getUserWidgets();
foreach($currentWidgets as $widget)
{
$settings = $widget->settings;
if($settings && is_array($settings))
{
if(array_key_exists('request', $settings) && $settings['request'] == $record->handle)
{
craft()->dashboard->deleteUserWidgetById($widget->id);
}
}
}
return true;
}
/**
* Returns the encoded cacheId for this request
* @return String The cache id
*/
private function _getCacheId()
{
return base64_encode(urlencode($this->cacheId));
}
}