-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathController.php
More file actions
623 lines (545 loc) · 19.2 KB
/
Controller.php
File metadata and controls
623 lines (545 loc) · 19.2 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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
<?php
namespace Core;
use Exception;
use kernel;
use ReflectionMethod;
use Twig_Environment;
use Twig_Function;
use Twig_Loader_Filesystem;
/*! \addtogroup Core
* @{
*/
/******************************************************************************/
/**
* Controller class.
*/
class Controller extends \Core\Module
{
protected $action = null;
protected $name = null;
protected $config = null;
protected $local = null;
protected $routes = null;
protected $session = null;
protected $get = null;
protected $post = null;
protected $put = null;
protected $format = null;
protected $path = null;
protected $slugs = null;
public function __construct($name, $config, $path, $slugs)
{
parent::__construct();
if (!isset($config[ROUTE_KEY_CONTROLLER])) {
throw new Exception('Trying to create controller without name.');
}
if (!isset($config[ROUTE_KEY_ACTION])) {
throw new Exception('Trying to create controller without action.');
}
if (!isset($config[ROUTE_KEY_METHOD])) {
$config[ROUTE_KEY_METHOD] = false;
}
$this->action = $config['action'];
$this->name = $name;
$this->config = $this->kernel->config;
$this->routes = $this->kernel->routes;
$this->session = $this->kernel->session;
$this->get = $this->kernel->get;
$this->post = $this->kernel->post;
$this->put = $this->kernel->put;
$this->format = isset($config[ROUTE_KEY_FORMAT]) ? $config[ROUTE_KEY_FORMAT] : false;
if ($this->kernel->format !== false) {
if ($this->format === false) {
$this->format = $this->kernel->format;
} else if ($this->format != $this->kernel->format) {
throw new Exception('Cannot fullfill request, invalid format specified');
}
}
$this->path = $path;
$this->slugs = $slugs;
$this->local = $this->kernel->loadRouteConfig($path);
if (method_exists($this, 'init')) {
$this->init();
}
}
public function getName()
{
return $this->name;
}
public function method()
{
$methods = func_get_args();
if (in_array($this->kernel->method, $methods)) {
return true;
}
return false;
}
public function setGet($params)
{
$this->get = $params;
}
public function getFormat()
{
return $this->format;
}
public function setFormat($value)
{
$this->format = $value;
}
/**
* Fetch POST/GET parameter.
*
* POST is searched first (is method was even POST), and GET is secondary.
*
* @return Value set in POST or GET. If not found, returns null.
*/
public function inputRaw()
{
$args = func_get_args();
$value = null;
/* search POST */
if ($this->method('post')) {
$value = $this->post;
foreach ($args as $arg) {
if (isset($value[$arg])) {
$value = $value[$arg];
} else {
/* value was not found, check GET */
$value = null;
}
}
}
if ($value !== null) {
/* value found from POST, return it */
return $value;
}
/* search GET */
$value = $this->get;
foreach ($args as $arg) {
if (isset($value[$arg])) {
$value = $value[$arg];
} else {
/* value was not found, return null */
return null;
}
}
return $value;
}
public function inputRawDefault($default)
{
$method = new ReflectionMethod($this, 'inputRaw');
$args = func_get_args();
array_shift($args);
$value = $method->invokeArgs($this, $args);
if ($value === null) {
return $default;
}
return $value;
}
/**
* Fetch POST/GET parameter.
* String values are decoded (even post) using urldecode().
*
* POST is searched first (is method was even POST), and GET is secondary.
*
* @return Value set in POST or GET. If not found, returns null.
*/
public function input()
{
$method = new ReflectionMethod($this, 'inputRaw');
$args = func_get_args();
$value = $method->invokeArgs($this, $args);
if ($value === null) {
return null;
} else if (!is_string($value)) {
return $value;
}
return urldecode($value);
}
public function inputDefault($default)
{
$method = new ReflectionMethod($this, 'inputRaw');
$args = func_get_args();
array_shift($args);
$value = $method->invokeArgs($this, $args);
if ($value === null) {
return $default;
} else if (!is_string($value)) {
return $value;
}
return urldecode($value);
}
public function getDataDir($append = false)
{
$dir = $this->kernel->expand('{path:data}/' . $this->name);
/* creata data directory for current route if needed */
if (!file_exists($dir)) {
if (!@mkdir($dir, 0700, true)) {
throw new Exception('unable to create data directory for route ' . $this->name);
}
}
/* check that this directory exists as a directory */
if (is_dir($dir)) {
if ($append) {
$dir .= '/' . $append;
}
if (!file_exists($dir)) {
if (!@mkdir($dir, 0700, true)) {
throw new Exception('unable to create data directory under route ' . $this->name);
}
}
return $dir;
}
throw new Exception('data directory for route ' . $this->name . ' is invalid ' . $dir);
}
public function loadCustomConfig($config)
{
return $this->kernel->loadRouteCustomConfig($this->path, $config);
}
public function render($template = null, $params = array())
{
if ($this->format === 'json') {
$ret = array(
'success' => true,
'data' => $params,
);
return json_encode($ret);
} else {
if ($template === null) {
/* just return true for empty content if template is null */
return true;
}
/**
* @todo enable rendering of templates from another routes?
*/
// $parts = explode(':', $template, 2);
// if (count($parts) == 2)
// {
// }
$twig = $this->twigGet();
return $twig->render($template, $params);
}
return false;
}
public function display($template = null, $params = array())
{
$view = $this->render($template, $params);
if ($view === false) {
return false;
}
if ($this->format === 'json') {
header('Content-Type: application/json');
}
echo $view;
return true;
}
public function renderRaw($content, $params = array())
{
if ($this->format === 'json') {
$ret = array(
'success' => true,
'data' => $params,
'raw' => $content,
);
return json_encode($ret);
} else {
return $content;
}
return false;
}
public function renderMethodResolve(&$args)
{
$args = array();
$actionMethodName = $this->action . CONTROLLER_ACTION_EXTENSION;
if (!method_exists($this, $actionMethodName)) {
throw new Exception('invalid action ' . $this->action);
}
$method = new ReflectionMethod($this, $actionMethodName);
foreach ($method->getParameters() as $parameter) {
$name = $parameter->getName();
if (!isset($this->slugs[$name])) {
if (!$parameter->isOptional()) {
throw new Exception('action ' . $this->action . ' wants parameter named ' . $name);
}
} else {
$args[] = $this->slugs[$name]['value'];
}
}
return $method;
}
public function renderAction()
{
$method = $this->renderMethodResolve($args);
return $method->invokeArgs($this, $args);
}
public function renderRoute($route, $slugs = array(), $get = false)
{
$slugs_converted = array();
foreach ($slugs as $name => $slug) {
$slugs_converted[$name] = array('slug' => $name, 'value' => $slug);
}
if (strpos($route, ':') === false) {
$route = $this->name . ':' . $route;
}
$controller = $this->kernel->route($route, false, $get, $slugs_converted);
return $this->kernel->render($controller);
}
public function renderErrorException($e)
{
if ($this->format === 'json') {
$ret = array(
'success' => false,
'msg' => $e->getMessage(),
'code' => $e->getCode(),
'file' => $e->getFile(),
'line' => $e->getLine(),
);
return json_encode($ret);
} else {
$params['msg'] = $e->getMessage();
$params['code'] = $e->getCode();
$params['file'] = $e->getFile();
$params['line'] = $e->getLine();
return $this->twigGet()->render('error-exception.html', $params);
}
return false;
}
public function twigGet($extra_paths = false)
{
$templates = array();
if ($this->path) {
$templates[] = $this->path . '/views';
}
$templates[] = $this->kernel->expand('{path:views}');
$common = $this->kernel->expand('{path:routes}') . '/common/views';
if (is_dir($common)) {
$templates[] = $common;
}
$templates[] = $this->kernel->expand('{path:routes}');
if (is_array($extra_paths)) {
$templates = array_merge($templates, $extra_paths);
}
$twig_loader = new Twig_Loader_Filesystem($templates);
$config = $this->getConfigValue('twig');
if (!$config) {
$config = array('cache' => false);
}
if (isset($config['cache']) && $config['cache'] !== false) {
/* expand twig cache path */
$config['cache'] = $this->kernel->expand($config['cache']);
}
$twig = new Twig_Environment($twig_loader, $config);
/* add all custom functions to twig here */
//$twig->addExtension($this);
$twig->addFunction(new Twig_Function('route', array($this, 'route')));
$twig->addFunction(new Twig_Function('tr', array($this, 'tr')));
$twig->addFunction(new Twig_Function('trJs', array($this, 'trJs'), array('is_safe' => array('all'))));
$twig->addFunction(new Twig_Function('path', array($this, 'linkPath')));
/* assets */
$twig->addFunction(new Twig_Function('asset', array($this, 'linkAsset')));
$twig->addFunction(new Twig_Function('image', array($this, 'linkImage')));
$twig->addFunction(new Twig_Function('css', array($this, 'linkCss')));
$twig->addFunction(new Twig_Function('js', array($this, 'linkJavascript')));
$twig->addFunction(new Twig_Function('javascript', array($this, 'linkJavascript')));
$twig->addFunction(new Twig_Function('render', array($this, 'renderRoute')));
$twig->addFunction(new Twig_Function('username', array($this, 'username')));
$twig->addFunction(new Twig_Function('name', array($this, 'twigName')));
$twig->addFunction(new Twig_Function('authorize', array($this, 'authorize')));
$twig->addFunction(new Twig_Function('lang', array($this, 'lang')));
$twig->addFunction(new Twig_Function('msg', array($this->kernel, 'msgGet')));
$twig->addFunction(new Twig_Function('config', array($this->kernel, 'getConfigValue')));
$twig->addFunction(new Twig_Function('expand', array($this->kernel, 'expand')));
$twig->addFunction(new Twig_Function('bytes_to_human', array($this, 'twigBytesToHuman')));
return $twig;
}
public function route($route, $slugs = array(), $get = array(), $options = array())
{
$slugs_converted = array();
foreach ($slugs as $name => $slug) {
$slugs_converted[$name] = array('slug' => $name, 'value' => $slug);
}
if (strpos($route, ':') === false) {
$route = $this->name . ':' . $route;
}
return $this->kernel->route($route, true, $get, $slugs_converted, $options);
}
public function routePath($route)
{
if (strpos($route, ':') === false) {
$route = $this->name . ':' . $route;
}
return $this->kernel->routePath($route);
}
public function tr($text)
{
$method = new ReflectionMethod('kernel', 'tr');
$args = func_get_args();
return $method->invokeArgs($this->kernel, $args);
}
public function trJs($text)
{
$text = htmlentities($this->tr($text));
/* if there are more parameters, try to print them into the text */
if (func_num_args() > 1) {
$vars = func_get_args();
array_shift($vars);
foreach ($vars as &$var) {
$var = '"+' . $var . '+"';
}
$text = vsprintf($text, $vars);
}
return $text;
}
public function linkPath($path)
{
return $this->kernel->url($path);
}
public function linkAsset($asset, $route = false, $postdir = false)
{
$list = explode(':', $asset, 2);
if (count($list) == 2) {
$route = $list[0];
$asset = $list[1];
}
return $this->kernel->url(($route ? '/' . $route : '') . ($postdir ? '/' . $postdir : '') . '/' . $asset);
}
public function pathAsset($asset, $route, $postdir, &$webdir = null)
{
$list = explode(':', $asset, 2);
if (count($list) == 2) {
$route = $list[0];
$asset = $list[1];
}
$path = false;
if ($route) {
$webdir = $route . ($postdir ? '/' . $postdir : '') . '/' . $asset;
$path = $this->kernel->expand('{path:routes}') . '/' . $route . '/public' . ($postdir ? '/' . $postdir : '') . '/' . $asset;
} else {
$webdir = ($postdir ? $postdir . '/' : '') . $asset;
$path = $this->kernel->expand('{path:web}') . '/' . $webdir;
}
if (!file_exists($path)) {
$this->kernel->log(LOG_ERR, 'Invalid asset, file not found: ' . $path);
}
return $path;
}
public function linkImage($image, $global = false)
{
return $this->linkAsset($image, ($global ? false : $this->name), 'images');
}
public function linkCss($css = false, $global = false)
{
/* return single url */
if ($css !== false) {
return $this->linkAsset($css, ($global ? false : $this->name), 'css');
}
/*
* return list of css files defined in configuration
*/
$values = array();
$this->expandConfigAssets($this->config, 'assets', '', $values, false, '.css');
$this->expandConfigAssets($this->config, 'css', 'css', $values, false, false);
return $values;
}
public function linkJavascript($js = false, $global = false)
{
/* return single url */
if ($js !== false) {
return $this->linkAsset($js, ($global ? false : $this->name), 'js');
}
/*
* return list of javascript files defined in configuration
*/
$values = array();
$this->expandConfigAssets($this->config, 'assets', '', $values, false, '.js');
$this->expandConfigAssets($this->config, 'javascript', 'js', $values, false, false);
return $values;
}
public function expandConfigAssets($config, $key, $postdir, &$values, $route, $postfix)
{
if (!isset($config[$key])) {
return false;
}
// if ($key == 'assets' && $postfix == '.js')
// {
// die('moi ' . $postfix);
// }
foreach ($config[$key] as $value) {
if (is_string($value) && substr($value, -1) == '*') {
/* this is a template style asset */
/* wildcard append from route config */
list($subroute) = explode(':', $value, 2);
$routepath = $this->kernel->expand('{path:routes}/' . $subroute);
$subconfig = $this->kernel->loadRouteConfig($routepath);
if (isset($subconfig[$key])) {
$this->expandConfigAssets($subconfig, $key, $postdir, $values, $subroute, $postfix);
}
} else if (is_string($value) && $postfix && substr($value, -strlen($postfix)) != $postfix) {
continue;
} else if (is_string($value) && (strpos($value, 'http://') === 0 || strpos($value, 'https://') === 0)) {
/* external urls */
$values[] = array(
'type' => 'url',
'path' => null,
'url' => $value,
'route' => null,
'relative' => null,
);
} else {
/* just simple static one */
$type = 'static';
if (isset($value['twig'])) {
$type = 'twig';
$value = $value['twig'];
}
/* get path and url */
$path = $this->pathAsset($value, $route, $postdir, $webdir);
$url = $this->linkAsset($value, $route, $postdir);
/* check route */
$realroute = $route;
$list = explode(':', $value, 2);
if (count($list) == 2) {
$realroute = $list[0];
}
/* add */
$values[] = array(
'type' => $type,
'path' => $path,
'url' => $url,
'route' => $realroute,
'web' => $webdir,
);
}
}
return true;
}
public function username()
{
return $this->session->get('username');
}
public function twigName()
{
$user = $this->session->getUser();
$name = null;
if ($user) {
$name = $user->get('name');
}
if (empty($name)) {
$name = $this->session->get('username');
}
return $name;
}
public function authorize($access, $user = null)
{
return $this->session->authorize($access, $user);
}
public function lang()
{
return $this->kernel->lang;
}
public function twigBytesToHuman($bytes, $decimals = 2, $divider = 1024)
{
return Compose::bytesToHuman($bytes, $decimals, $divider);
}
}
/*! @} endgroup Core */