-
Notifications
You must be signed in to change notification settings - Fork 177
/
Main.php
537 lines (478 loc) · 15.5 KB
/
Main.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
<?php
/**
* Main Controller
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://getfrapi.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@getfrapi.com so we can send you a copy immediately.
*
* This is the controller that contains what the Web services controllers
* are very likely to contain. It contains methods to help retrieve
* parameters, help around.. it's the main controller..
*
*
* @license New BSD
* @package frapi
*/
class Frapi_Controller_Main
{
/**
* Constant used to retrieve extra caching information
* through the headers. If this is set to true, you will
* receive the size of the reuqest, the size of each
* key in the cache and such information.
*
* @var bool Whether or not the webservice should be in debug mode.
*/
const MAIN_WEBSERVICE_DEBUG = false;
/**
* The request parameter
*
* The value of the superglobal $_REQUEST
* variable from the web server.
*
* @var array $request The $_REQUEST
*/
protected $request;
/**
* The parameters in the request.
*
* The request gave us a bunch of parameters.
*
* @var array An array of params coming straight from the
* $_REQUEST array.
*/
protected $params;
/**
* The Files handlers
*
* You can make multiform-data posts to the server
* so that is the files coming from the $_FILES array
* in the upload.
*
* @var array $files An array of file information ($_FILES);
*/
protected $files;
/**
* The output format
*
* The output format is defaulted to XML as this is
* at the time, the most widely used webservicer return format
* and the most flexible and portable.
*
* @var string $format The format in which you return the output.
*/
protected $format = 'xml';
/**
* @var bool indicates output format was determined by file extension in URL
*/
protected $formatSetByExtension = false;
/**
* @var string stores the mapped mimeType of the incoming content if found
*/
protected $inputFormat;
/**
*
* Each call has an action
*
* Each call has an action and it is stored in this
* variable to invoke the requested context.
*
* @var string $action The action invoked by the webservice.
*/
protected $action;
/**
* Output Encoding Charset
*
* This is the variable that keeps the value of the default
* encoding charset to be used when outputting the values returned
* by the webservice.
*
* @var string $encoding The encoding value, default 'utf8'
*/
protected $encoding = 'utf-8';
/**
* The output context
*
* After invoking an action the output context is retrieved
* and stored in this variable as the outputcontext object.
*
* @var Output $outputContext The output context object.
*/
protected $outputContext;
/**
* Action Context
*
* When you invoke an action, it's action context is invoked
* and the object of that context is saved in this variable.
*
* @var Action $actionContext The action context object.
*/
protected $actionContext;
/**
* Security Context
*
* When an action is invoked, no matter which one it is, it has to pass
* the security verifications. This is the security context module object.
*
* @var Security $security The security context
*/
protected $security;
/**
* Authorization Context
*
* When invoking an action, is has to be either authorized or simply approved.
* This is the object of the AuthorizationContext module.
*
* @var Authorization $authorization The authorization context
*/
protected $authorization;
/**
* A map of all the mimetypes to their output
* format. In order to add a new mimetype, add it's
* mimetype name and then add it's output as the associated
* value.
*
* @deprecated The list here is left for legacy installations. Defining
* @deprecated mimetypes in the admin will override these once defined.
*
* @var array An array of mimetypes and their output types.
*/
protected $mimeMaps = array(
'application/xml' => 'xml',
'text/xml' => 'xml',
'application/json' => 'json',
'text/json' => 'json',
'text/html' => 'html',
'text/plain' => 'json',
'application/javascript' => 'js',
'text/javascript' => 'js',
'text/php-printr' => 'printr'
);
/*
* @var array denotes which documents can be used as input
*/
protected $allowedInputTypes = array('xml', 'json');
/**
* Constructor
*
* Upon invoking of the constructor, a few objects need to be created
* in order to approve, authorize and secure the action contexts.
*
* This constructor sets up the Security, ErrorContainer, Authorization
* and also sets the request parameters, files parameters, the format of the output
* and of course the most important part which is the action/output contexts themselves.
*
* @warning IF-Clusterfuck.
*
* @see Security
* @see ErrorContainer
* @see Authorization
* @params object $customAuthorization optional custom authorization extending Frapi_Authorization
*/
public function __construct($customAuthorization=null)
{
try {
$this->security = new Frapi_Security();
$this->authorization = ($customAuthorization instanceof Frapi_Authorization) ? $customAuthorization : new Frapi_Authorization();
$this->router = new Frapi_Router();
$this->router->loadAndPrepareRoutes();
$this->setInputFormat();
$uri = $_SERVER['REQUEST_URI'];
// For some reason, this is now a fatal
// error in 5.3 and no longer a warning
// in php (parse_url() with an http:// in the URL_PATH)...
if (stristr($uri, '?') !== false) {
$uri = substr($uri, 0, strpos($uri, '?'));
}
$query_path = parse_url($uri, PHP_URL_PATH);
// @deprecated The use of extensions is considered deprecated
//Query ending in .xxx may or may not be an output format
$query_path_format = pathinfo($query_path, PATHINFO_EXTENSION);
$format = $this->getParam('format');
if (is_string($query_path_format) && strlen($query_path_format) || $format) {
$extension = ($query_path_format) ? $query_path_format : $format;
if ($query_path_format) {
$query_path = substr($query_path, 0, (strlen($extension) + 1)*-1);
}
if (Frapi_Rules::validateOutputType($extension) === true) {
$accept = Frapi_Output::getMimeTypeByFormat($extension);
if (isset($_SERVER['HTTP_ACCEPT'])) {
$_SERVER['HTTP_ACCEPT'] = $accept . ',' .$_SERVER['HTTP_ACCEPT'];
} else {
$_SERVER['HTTP_ACCEPT'] = $accept;
}
}
$query_path_format = $format = null;
}
if ($routed = $this->router->match($query_path)) {
$_REQUEST = array_merge($_REQUEST, $routed['params']);
$this->setAction(strtolower($routed['action']));
$this->setRequest($_REQUEST);
} else {
$this->setRequest($_REQUEST);
$this->setAction($this->getParam('action'));
}
$this->setFiles($_FILES);
$this->authorization->setAuthorizationParams($this->getParams());
} catch (Frapi_Exception $e) {
// Something RONG happened. Need to tell developers.
throw $e;
} catch (Exception $e) {
// Something else? Silence! I Keeel you.
}
}
/**
* Set Request
*
* This method returns the request
* ($_REQUEST) mostly.
*
* @return mixed Array or String depending on how it feels.
*
*/
public function setRequest($request)
{
$this->request = $request;
return $this;
}
/**
* Get Files (GETTER)
*
* This method returns the request
* ($_FILES) mostly.
*
* @return mixed Array or String depending
* On how it feels.
*
*/
public function getFiles()
{
return $this->files;
}
/**
* Set files
*
* This method will set the parameters in
* the filess variable.
*
* @param array $params The params to set.
* @return void
*/
private function setFiles($params)
{
$this->files = $params;
}
/**
* Get parameters
*
* This method returns an array of the parameters
* passed.
*
* Is this similar to getRequest ? I have to check tmrw.
* @todo ^
* @return Mixed An array or a string of parameters
*/
public function getParams()
{
$params = $this->request;
/**
* This certainly isn't a pure approach however it is a very
* practical approach that will suit most people most of the times.
*
* Unhappy? Remove me.
*/
$input = file_get_contents("php://input");
parse_str($input, $puts);
$inputFormat = $this->inputFormat;
if(empty($inputFormat)) {
$xmlJsonMatch = preg_grep('/\<|\{/i', array_keys($puts));
$inputFormat = $this->getFormat();
}
/**
* When doing parse_str("{json:string}") it creates an array like:
* array(
* "{json:string}" => ""
* )
*
* If args are also present along with the body, they are in the array
* before the body.
*
* Checks if the last argument is an empty string, this + inputForm is
* indicative of the body needing parsing.
*/
if (end($puts) == '' && !empty($inputFormat) || !empty($xmlJsonMatch)) {
/* attempt to parse the input */
reset($puts);
$requestBody = Frapi_Input_RequestBodyParser::parse(
$inputFormat,
$input
);
if (!empty($requestBody)) {
$rootElement = array_keys($requestBody);
// flatten the first element of the requestbody into the array
// if it is itself an array and the only element
// this handles a root element in the request body.
if(count($requestBody) == 1 && is_array($requestBody[$rootElement[0]])) {
$params[$rootElement[0]] = true;
$requestBody = $requestBody[$rootElement[0]];
}
$params = array_merge($params, $requestBody);
}
} else if (!empty($puts)) {
foreach ($puts as $put => $val) {
$params[$put] = $val;
}
}
$this->request = $params;
return $this->request;
}
/**
* Get a param
*
* This method will get a single param
* out of the request variable.
*
* @param string $key The key to extract
* @return Mixed Either value of the array key or false
*/
public function getParam($key)
{
if (isset($this->request[$key])) {
return $this->request[$key];
}
if (isset($this->files[$key])) {
return $this->files[$key];
}
return false;
}
/**
* Get the format
*
* Get the desired format. We are checking if it's
* a valid one in setFormat. Getformat is really dumb.
*
* @return string $this->format The format.
*/
public function getFormat()
{
return $this->format;
}
/**
* Get default format from configuration
*
* A format (output type) has not been supplied
* so try to get default from backend.
*
* @return String The format.
*/
public function getDefaultFormatFromConfiguration()
{
if ($default_output_format = Frapi_Internal::getCached('Output.default-format')) {
return $default_output_format;
}
$conf = Frapi_Internal::getConfiguration('outputs');
$row = $conf->getByField('output', 'default', '1');
if (isset($row) && isset($row['name'])) {
Frapi_Internal::setCached('Output.default-format', $row['name']);
return $row['name'];
}
return Frapi_Controller_Api::DEFAULT_OUTPUT_FORMAT;
}
/**
* Set format
*
* This method will check if the format is
* an acceptable one, if so it'll set it to the
* requested format.
*
* In the case where there are no format passed, we
* default the value to 'xml'
*
* @param string $format The format to use.
* @throws Frapi_Error
*/
protected function setOutputFormat($format = false)
{
$format = strtolower($format);
if ($format) {
$typeValid = Frapi_Rules::validateOutputType($format);
$this->format = $format;
} else {
throw new Frapi_Error (
Frapi_Error::ERROR_INVALID_URL_PROMPT_FORMAT_NAME,
Frapi_Error::ERROR_INVALID_URL_PROMPT_FORMAT_MSG,
Frapi_Error::ERROR_INVALID_URL_PROMPT_FORMAT_NO
);
}
}
/**
* @see self::setOutputFormat
*
* @deprecated
* @param string $format
*/
protected function setFormat($format = false)
{
$this->setOutputFormat($format);
}
/**
* Get action
*
* Get the action passed, this will be used
* in the ActionContext and OutputContext usage.
*
* Ex: getProfile, createAccount, login, etc.
*
* @return string $action The action
*/
public function getAction()
{
return $this->action;
}
/**
* Set the action
*
* This method is quite simple, it will set the
* action requested. If it finds it in the list of
* loginRequiredActions or PidRequiredActions it will
* do the check and if it is false, it'll set and error
*
* @param string $action The requested action.
*/
private function setAction($action = false)
{
$this->action = strtolower($action);
}
/**
* reads the Content-Type header; sets request body format if a valid mime type exists
*
* @return void
*/
public function setInputFormat()
{
$contentType = (isset($_SERVER['CONTENT_TYPE'])) ?
$_SERVER['CONTENT_TYPE'] :
null;
if(!empty($contentType) &&
isset($this->mimeMaps[$contentType]) &&
in_array($this->mimeMaps[$contentType], $this->allowedInputTypes)) {
$this->inputFormat = $this->mimeMaps[$contentType];
}
}
/**
* returns the expected input format
*
* @return string
*/
public function getInputFormat()
{
return $this->inputFormat;
}
}