-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.php
executable file
·2874 lines (2503 loc) · 102 KB
/
index.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
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Atomik Framework
* Copyright (c) 2008-2009 Maxime Bouroumeau-Fuseau
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package Atomik
* @author Maxime Bouroumeau-Fuseau
* @copyright 2008-2009 (c) Maxime Bouroumeau-Fuseau
* @license http://www.opensource.org/licenses/mit-license.php
* @link http://www.atomikframework.com
*/
define('ATOMIK_VERSION', '2.2.2');
!defined('ATOMIK_APP_ROOT') && define('ATOMIK_APP_ROOT', './app');
/* -------------------------------------------------------------------------------------------
* APPLICATION CONFIGURATION
* ------------------------------------------------------------------------------------------ */
Atomik::reset(array(
'app' => array(
/* @var string */
'default_action' => 'index',
/* The name of the layout
* Add multiple layouts using an array (will be rendered in reverse order)
* @var array|bool|string */
'layout' => false,
/* @var bool */
'disable_layout' => false,
/* An array where keys are route names and their value is an associative
* array of default values
* @see Atomik::route()
* @var array */
'routes' => array(),
/* @var bool */
'force_uri_extension' => false,
/* List of escaping profiles where keys are profile names and their
* value an array of callbacks
* @see Atomik::escape()
* @var array */
'escaping' => array(
'default' => array('htmlspecialchars', 'nl2br')
),
/* @see Atomik::filter()
* @var array */
'filters' => array(
/* @var array */
'rules' => array(),
/* @var array */
'callbacks' => array(),
/* @var string */
'default_message' => 'The %s field failed to validate',
/* @var string */
'required_message' => 'The %s field must be filled'
),
/* @see Atomik::render()
* @var array */
'views' => array(
/* @var string */
'file_extension' => '.html',
/* Alternative rendering engine
* @see Atomik::_render()
* @var callback */
'engine' => false,
/* @var string */
'default_context' => 'html',
/* The GET parameter to retrieve the current context
* @var string */
'context_param' => 'format',
/* List of contexts where keys are the context name.
* Contexts can specify:
* - prefix (string): the view filename's extension prefix
* - layout (bool): whether the layout should be rendered
* - content_type (string): the HTTP response content type
* @var array */
'contexts' => array(
'html' => array(
'prefix' => '',
'layout' => true,
'content_type' => 'text/html'
),
'ajax' => array(
'prefix' => '',
'layout' => false,
'content_type' => 'text/html'
),
'xml' => array(
'prefix' => 'xml',
'layout' => false,
'content_type' => 'text/xml'
),
'json' => array(
'prefix' => 'json',
'layout' => false,
'content_type' => 'application/json'
)
)
),
/* A parameter in the route that will allow to specify the http method
* (override the request's method). False to disable
* @var string */
'http_method_param' => '_method',
/* @var array */
'allowed_http_methods' => array('GET', 'POST', 'PUT', 'DELETE', 'TRACE', 'HEAD', 'OPTIONS', 'CONNECT')
)
));
/* -------------------------------------------------------------------------------------------
* CORE CONFIGURATION
* ------------------------------------------------------------------------------------------ */
Atomik::set(array(
/* @var array */
'plugins' => array(),
/* @var array */
'atomik' => array(
/* Atomik's filename
* @var string */
'scriptname' => __FILE__,
/* Base url, set to null for auto detection
* @var string */
'base_url' => null,
/* Whether url rewriting is activated on the server
* @var bool */
'url_rewriting' => false,
/* @var bool */
'debug' => false,
/* The GET parameter used to retreive the action
* @var string */
'trigger' => 'action',
/* Whether to register the class autoloader
* @var bool */
'class_autoload' => true,
/* @var bool */
'start_session' => true,
/* Plugin's assets path template.
* %s will be replaced by the plugin's name
* @see Atomik::pluginAsset()
* @var string */
'plugin_assets_tpl' => 'app/plugins/%s/assets/',
/* @var array */
'log' => array(
/* @var bool */
'register_default' => false,
/* From which level to start logging messages
* @var int */
'level' => LOG_WARNING,
/* Message template for the default logger
* @see Atomik::logToFile()
* @var string */
'message_template' => '[%date%] [%level%] %message%'
),
/* @var array */
'dirs' => array(
'app' => ATOMIK_APP_ROOT,
'plugins' => array(ATOMIK_APP_ROOT . '/modules', ATOMIK_APP_ROOT . '/plugins/'),
'actions' => ATOMIK_APP_ROOT . '/actions/',
'views' => ATOMIK_APP_ROOT . '/views/',
'layouts' => array(ATOMIK_APP_ROOT . '/layouts', ATOMIK_APP_ROOT . '/views'),
'helpers' => ATOMIK_APP_ROOT . '/helpers/',
'includes' => array(ATOMIK_APP_ROOT . '/includes/', ATOMIK_APP_ROOT . '/libraries/'),
'overrides' => ATOMIK_APP_ROOT . '/overrides/'
),
/* @var array */
'files' => array(
'index' => 'index.php',
'config' => ATOMIK_APP_ROOT . '/config', // without extension
'bootstrap' => ATOMIK_APP_ROOT . '/bootstrap.php',
'pre_dispatch' => ATOMIK_APP_ROOT . '/pre_dispatch.php',
'post_dispatch' => ATOMIK_APP_ROOT . '/post_dispatch.php',
'404' => ATOMIK_APP_ROOT . '/404.php',
'error' => ATOMIK_APP_ROOT . '/error.php',
'log' => ATOMIK_APP_ROOT . '/log.txt'
),
/* @var bool */
'catch_errors' => false,
/* @var bool */
'display_errors' => true,
/* @var array */
'error_report_attrs' => array(
'atomik-error' => 'style="padding: 10px"',
'atomik-error-title' => 'style="font-size: 1.3em; font-weight: bold; color: #FF0000"',
'atomik-error-lines' => 'style="width: 100%; margin-bottom: 20px; background-color: #fff;'
. 'border: 1px solid #000; font-size: 0.8em"',
'atomik-error-line' => '',
'atomik-error-line-error' => 'style="background-color: #ffe8e7"',
'atomik-error-line-number' => 'style="background-color: #eeeeee"',
'atomik-error-line-text' => '',
'atomik-error-stack' => ''
)
),
/* @var int */
'start_time' => time() + microtime()
));
/* -------------------------------------------------------------------------------------------
* CORE
* ------------------------------------------------------------------------------------------ */
// creates the A function (shortcut to Atomik::get)
if (!function_exists('A')) {
/**
* Shortcut function to Atomik::get()
* Useful when dealing with selectors
*
* @see Atomik::get()
* @return mixed
*/
function A()
{
$args = func_get_args();
return call_user_func_array(array('Atomik', 'get'), $args);
}
}
// starts Atomik unless ATOMIK_AUTORUN is set to false
if (!defined('ATOMIK_AUTORUN') || ATOMIK_AUTORUN === true) {
Atomik::run();
}
/**
* Exception class for Atomik
*
* @package Atomik
*/
class Atomik_Exception extends Exception {}
/**
* Atomik Framework Main class
*
* @package Atomik
*/
final class Atomik
{
/**
* Global store
*
* This property is used to stored all data accessed using get(), set()...
*
* @var array
*/
public static $store = array();
/**
* Global store to reset to
*
* @var array
*/
private static $reset = array();
/**
* Loaded plugins
*
* When a plugin is loaded, its name is saved in this array to
* avoid loading it twice.
*
* @var array
*/
private static $plugins = array();
/**
* Registered events
*
* The array keys are event names and their value is an array with
* the event callbacks
*
* @var array
*/
private static $events = array();
/**
* Selectors namespaces
*
* The array keys are the namespace name and the associated value is
* the callback to call when the namespace is used
*
* @var array
*/
private static $namespaces = array('flash' => array('Atomik', '_getFlashMessages'));
/**
* Execution contexts
*
* Each call to Atomik::execute() creates a context.
*
* @var array
*/
private static $execContexts = array();
/**
* Pluggable applications
*
* @var array
*/
private static $pluggableApplications = array();
/**
* Registered methods
*
* @var array
*/
private static $methods = array();
/**
* Already loaded helpers
*
* @var array
*/
private static $loadedHelpers = array();
/**
* Starts Atomik
*
* If dispatch is false, you will have to manually dispatch the request and exit.
*
* @param string $uri
* @param bool $dispatch Whether to dispatch
*/
public static function run($uri = null, $dispatch = true)
{
// wrap the whole app inside a try/catch block to catch all errors
try {
@chdir(dirname(A('atomik/scriptname')));
// loads the config file
if (file_exists($filename = self::get('atomik/files/config') . '.php')) {
// PHP
if (is_array($config = include($filename))) {
self::set($config);
}
} else if (file_exists($filename = self::get('atomik/files/config') . '.ini')) {
// INI
if (($data = parse_ini_file($filename, true)) === false) {
throw new Atomik_Exception('INI configuration malformed');
}
self::set(self::_dimensionizeArray($data, '.'), null, false);
} else if (file_exists($filename = self::get('atomik/files/config') . '.json')) {
// JSON
if (($config = json_decode(file_get_contents($filename), true)) === null) {
throw new Atomik_Exception('JSON configuration malformed');
}
self::set($config);
}
// adds includes dirs to php include path
$includePaths = self::path(self::get('atomik/dirs/includes', array()), true);
$includePaths[] = get_include_path();
set_include_path(implode(PATH_SEPARATOR, $includePaths));
// registers the error handler
if (self::get('atomik/catch_errors', true) == true) {
set_error_handler('Atomik::_errorHandler');
}
// sets the error reporting to all errors if debug mode is on
if (self::get('atomik/debug', false) == true) {
error_reporting(E_ALL | E_STRICT);
}
// default logger
if (self::get('atomik/log/register_default', false) == true) {
self::listenEvent('Atomik::Log', 'Atomik::logToFile');
}
// starts the session
if (self::get('atomik/start_session', true) == true) {
session_start();
self::$store['session'] = &$_SESSION;
}
// registers the class autoload handler
if (self::get('atomik/class_autoload', true) == true) {
if (!function_exists('spl_autoload_register')) {
throw new Atomik_Exception('Missing spl_autoload_register function');
}
spl_autoload_register('Atomik::autoload');
}
// cleans the plugins array
$plugins = array();
foreach (self::get('plugins', array()) as $key => $value) {
if (!is_string($key)) {
$key = $value;
$value = array();
}
$plugins[ucfirst($key)] = (array) $value;
}
self::set('plugins', $plugins, false);
// loads plugins
// this method allows plugins that are being loaded to modify the plugins array
$disabledPlugins = array();
while (count($pluginsToLoad = array_diff(array_keys(self::get('plugins')), self::getLoadedPlugins(), $disabledPlugins)) > 0) {
foreach ($pluginsToLoad as $plugin) {
if (self::loadPlugin($plugin) === false) {
$disabledPlugins[] = $plugin;
}
}
}
// loads bootstrap file
if (file_exists($filename = self::get('atomik/files/bootstrap'))) {
require($filename);
}
// core is starting
self::fireEvent('Atomik::Start', array(&$cancel));
if ($cancel) {
self::end(true);
}
self::log('Starting', LOG_DEBUG);
// checks if url rewriting is used
if (!self::has('atomik/url_rewriting')) {
self::set('atomik/url_rewriting', isset($_SERVER['REDIRECT_URL']) || isset($_SERVER['REDIRECT_URI']));
}
// dispatches
if ($dispatch) {
if (!self::dispatch($uri)) {
self::trigger404();
}
// end
self::end(true);
}
} catch (Exception $e) {
self::log('Exception caught: ' . $e->getMessage(), LOG_ERR);
// checks if we really want to catch errors
if (!self::get('atomik/catch_errors', true)) {
throw $e;
}
self::fireEvent('Atomik::Error', array($e));
header('Location: ', false, 500);
self::renderException($e);
self::end(false);
}
}
/**
* Dispatches the request
*
* It takes an URI, applies routes, executes the action and renders the view.
* If $uri is null, the value of the GET parameter specified as the trigger
* will be used.
*
* @param string $uri
* @param bool $allowPluggableApplication Whether to allow plugin application to be loaded
*/
public static function dispatch($uri = null, $allowPluggableApplication = true)
{
self::fireEvent('Atomik::Dispatch::Start', array(&$uri, &$allowPluggableApplication, &$cancel));
if ($cancel) {
return true;
}
// checks if it's needed to auto discover the uri
if ($uri === null) {
// retreives the requested uri
$trigger = self::get('atomik/trigger', 'action');
if (isset($_GET[$trigger]) && !empty($_GET[$trigger])) {
$uri = trim($_GET[$trigger], '/');
}
// retreives the base url
if (self::get('atomik/base_url', null) === null) {
if (self::get('atomik/url_rewriting') && (isset($_SERVER['REDIRECT_URL']) || isset($_SERVER['REDIRECT_URI']))) {
// finds the base url from the redirected url
$redirectUrl = isset($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : $_SERVER['REDIRECT_URI'];
self::set('atomik/base_url', substr($redirectUrl, 0, -strlen($_GET[$trigger])));
} else {
// finds the base url from the script name
self::set('atomik/base_url', rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\') . '/');
}
}
} else {
// sets the user defined request
// retreives the base url
if (self::get('atomik/base_url', null) === null) {
// finds the base url from the script name
self::set('atomik/base_url', rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\') . '/');
}
}
// default uri
if (empty($uri)) {
$uri = self::get('app/default_action', 'index');
}
// routes the request
if (($request = self::route($uri, $_GET)) === false) {
return false;
}
// checking if no dot are in the action name to avoid any hack attempt and if no
// underscore is use as first character in a segment
if (strpos($request['action'], '..') !== false || substr($request['action'], 0, 1) == '_'
|| strpos($request['action'], '/_') !== false) {
return false;
}
self::set('request_uri', $uri);
self::set('request', $request);
if (!self::has('full_request_uri')) {
self::set('full_request_uri', $uri);
}
self::fireEvent('Atomik::Dispatch::Uri', array(&$uri, &$request, &$cancel));
if ($cancel) {
return true;
}
// checks if the uri triggers a pluggable application
if ($allowPluggableApplication) {
foreach (self::$pluggableApplications as $plugin => $pluggAppConfig) {
if (!self::uriMatch($pluggAppConfig['route'], $uri)) {
continue;
}
// rewrite uri
$baseAction = trim($pluggAppConfig['route'], '/*');
$uri = substr(trim($uri, '/'), strlen($baseAction));
if ($uri == self::get('app/default_action')) {
$uri = '';
}
self::set('atomik/base_action', $baseAction);
// dispatches the pluggable application
return self::dispatchPluggableApplication($plugin, $uri, $pluggAppConfig['config']);
}
}
// fetches the http method
$httpMethod = $_SERVER['REQUEST_METHOD'];
if (($param = self::get('app/http_method_param', false)) !== false) {
// checks if the route parameter to override the method is defined
$httpMethod = self::get($param, $httpMethod, $request);
}
if (!in_array($httpMethod, self::get('app/allowed_http_methods'))) {
// specified method not allowed
return false;
}
self::set('app/http_method', strtoupper($httpMethod));
// fetches the view context
$viewContext = self::get(self::get('app/views/context_param', 'format'),
self::get('app/views/default_context', 'html'), $request);
self::set('app/view_context', $viewContext);
// retreives view context params and prepare the response
if (($viewContextParams = self::get('app/views/contexts/' . $viewContext, false)) !== false) {
if ($viewContextParams['layout'] !== true) {
self::set('app/layout', $viewContextParams['layout']);
}
header('Content-type: ' . self::get('content-type', 'text/html', $viewContextParams));
}
// configuration is ok, ready to dispatch
self::fireEvent('Atomik::Dispatch::Before', array(&$cancel));
if ($cancel) {
return true;
}
self::log('Dispatching action ' . $request['action'], LOG_DEBUG);
// pre dispatch action
if (file_exists($filename = self::get('atomik/files/pre_dispatch'))) {
require($filename);
}
// executes the action
ob_start();
if (($content = self::execute(self::get('request/action'), $viewContext, false)) === false) {
return false;
}
$content = ob_get_clean() . $content;
// renders the layouts if enable
if (($layouts = self::get('app/layout', false)) !== false) {
if (!empty($layouts) && !self::get('app/disable_layout', false)) {
foreach (array_reverse((array) $layouts) as $layout) {
$content = self::renderLayout($layout, $content);
}
}
}
// echoes the content
self::fireEvent('Atomik::Output::Before', array(&$content));
echo $content;
self::fireEvent('Atomik::Output::After', array($content));
// dispatch done
self::fireEvent('Atomik::Dispatch::After');
// post dispatch action
if (file_exists($filename = self::get('atomik/files/post_dispatch'))) {
require($filename);
}
return true;
}
/**
* Checks if an uri matches the pattern. The pattern can contain the * wildcard at the
* end to specify that it matches the target and all its child segments.
*
* @param string $pattern
* @param string $uri Default is the current request uri
* @return bool
*/
public static function uriMatch($pattern, $uri = null)
{
if ($uri === null) {
$uri = self::get('request_uri');
}
$uri = trim($uri, '/');
$pattern = trim($pattern, '/');
if (substr($pattern, -1) == '*') {
$pattern = rtrim($pattern, '/*');
return strlen($uri) >= strlen($pattern) && substr($uri, 0, strlen($pattern)) == $pattern;
} else {
return $uri == $pattern;
}
}
/**
* Parses an uri to extract parameters
*
* Routes defines how to extract parameters from an uri. They can
* have additional default parameters.
* There are two kind of routes:
*
* - segments:
* the uri is divided into path segments. Each segment can be
* either static or a parameter (indicated by :).
* eg: /archives/:year/:month
*
* - regexp:
* uses a regexp against the uri. Must be enclosed using # instead of
* slashes parameters must be specified as named subpattern.
* eg: #^archives/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})$#
*
* If no route matches, the default route (ie :action) will automatically be used.
* Unless you're using regexps, any additional segments will be added as parameters
* eg: /archives/2009/01/id/1, will also have the id=1 parameter
*
* You can also name your routes using the @name parameter (which won't be included
* in the returned params). Named route can then be use with Atomik::url()
*
* @param string $uri
* @param array $params Additional parameters which are not in the uri
* @param array $routes Uses app/routes if null
* @return array|boolean Route parameters or false if it fails
*/
public static function route($uri, $params = array(), $routes = null)
{
if ($routes === null) {
$routes = self::get('app/routes');
}
self::fireEvent('Atomik::Router::Start', array(&$uri, &$routes, &$params));
// extracts uri information
$components = parse_url($uri);
$uri = trim($components['path'], '/');
$uriSegments = explode('/', $uri);
$uriExtension = false;
if (isset($components['query'])) {
parse_str($components['query'], $query);
$params = array_merge($query, $params);
}
// extract the file extension from the uri
$lastSegment = array_pop($uriSegments);
if (($dot = strrpos($lastSegment, '.')) !== false) {
$uriExtension = substr($lastSegment, $dot + 1);
$lastSegment = substr($lastSegment, 0, $dot);
}
$uriSegments[] = $lastSegment;
// checks if the extension must be present
if (self::get('app/force_uri_extension', false) && $uriExtension === false) {
return false;
}
// searches for a route matching the uri
$found = false;
$request = array();
foreach ($routes as $route => $default) {
if (!is_string($route)) {
$route = $default;
$default = array();
}
// removes the route name from the default params
if (isset($default['@name'])) {
unset($default['@name']);
}
// regexp
if ($route{0} == '#') {
if (!preg_match($route, $uri, $matches)) {
continue;
}
unset($matches[0]);
$found = true;
$request = array_merge($default, $matches);
break;
}
$valid = true;
$segments = explode('/', trim($route, '/'));
$request = $default;
$extension = false;
// extract the file extension from the route
$lastSegment = array_pop($segments);
if (($dot = strrpos($lastSegment, '.')) !== false) {
$extension = substr($lastSegment, $dot + 1);
$lastSegment = substr($lastSegment, 0, $dot);
}
$segments[] = $lastSegment;
// checks the extension
if ($extension !== false) {
if ($extension{0} == ':') {
// extension is a parameter
if ($uriExtension !== false) {
$request[substr($extension, 1)] = $uriExtension;
} else if (!isset($request[substr($extension, 1)])) {
// no uri extension and no default value
continue;
}
} else if ($extension != $uriExtension) {
continue;
}
}
for ($i = 0, $count = count($segments); $i < $count; $i++) {
if (substr($segments[$i], 0, 1) == ':') {
// segment is a parameter
if (isset($uriSegments[$i])) {
// this segment is defined in the uri
$request[substr($segments[$i], 1)] = $uriSegments[$i];
$segments[$i] = $uriSegments[$i];
} else if (!array_key_exists(substr($segments[$i], 1), $default)) {
// not defined in the uri and no default value
$valid = false;
break;
}
} else {
// fixed segment
if (!isset($uriSegments[$i]) || $uriSegments[$i] != $segments[$i]) {
$valid = false;
break;
}
}
}
// checks if route is valid and if the action param is set
if ($valid && isset($request['action'])) {
$found = true;
// if there's remaining segments in the uri, adding them as params
if (($count = count($uriSegments)) > ($start = count($segments))) {
for ($i = $start; $i < $count; $i += 2) {
if (isset($uriSegments[$i + 1])) {
$request[$uriSegments[$i]] = $uriSegments[$i + 1];
}
}
}
break;
}
}
if (!$found) {
// route not found, creating default route
$request = array(
'action' => implode('/', $uriSegments),
self::get('app/views/context_param', 'format') => $uriExtension === false ?
self::get('app/views/default_context', 'html') : $uriExtension
);
}
$request = array_merge($params, $request);
self::fireEvent('Atomik::Router::End', array($uri, &$request));
return $request;
}
/**
* Executes an action
*
* Searches for a file called after the action (with the php extension) inside
* directories set under atomik/dirs/actions. If no file is found, it will search
* for a view and render it. If neither of them are found, it will throw an exception.
*
* @see Atomik::render()
* @param string $action The action name. The HTTP method can be prefixed after a dot
* @param bool|string $viewContext The view context. Set to false to not render the view and return the variables or to true for the request's context
* @param bool $triggerError Whether to throw an exception if an error occurs
* @return mixed The output of the view or an array of variables or false if an error occured
*/
public static function execute($action, $viewContext = true, $triggerError = true)
{
$view = $action;
$vars = array();
$render = $viewContext !== false;
if (is_bool($viewContext)) {
// using the request's context
$viewContext = self::get('app/view_context');
}
// appends the context's prefix to the view name
$prefix = self::get('app/views/contexts/' . $viewContext . '/prefix', $viewContext);
if (!empty($prefix)) {
$view .= '.' . $prefix;
}
// creates the execution context
$context = array('action' => &$action, 'view' => &$view, 'render' => &$render);
self::$execContexts[] =& $context;
self::fireEvent('Atomik::Execute::Start', array(&$action, &$context, &$triggerError));
if ($action === false) {
return false;
}
// checks if the method is specified in $action
if (($dot = strrpos($action, '.')) !== false) {
// it is, extract it
$methodAction = $action;
$method = substr($action, $dot + 1);
$action = substr($action, 0, $dot);
} else {
// use the current request's http method
$method = strtolower(self::get('app/http_method'));
$methodAction = $action . '.' . $method;
}
// filenames
$actionFilename = self::actionFilename($action);
$methodActionFilename = self::actionFilename($methodAction);
$viewFilename = self::viewFilename($view);
// checks if at least one of the action files or the view file is defined
if ($actionFilename === false && $methodActionFilename === false && $viewFilename === false) {
if ($triggerError) {
throw new Atomik_Exception('Action ' . $action . ' does not exist');
}
return false;
}
if ($viewFilename === false) {
// no view files, disabling view
$view = false;
}
self::fireEvent('Atomik::Execute::Before', array(&$action, &$context, &$actionFilename, &$methodActionFilename, &$triggerError));
// class name if using a class
$className = str_replace(' ', '_', ucwords(str_replace('/', ' ', $action)));
// executes the global action
if ($actionFilename !== false) {
// executes the action in its own scope and fetches defined variables
$vars = self::executeFile($actionFilename, array(), $className . 'Action');
}
// executes the method specific action
if ($methodActionFilename !== false) {
// executes the action in its own scope and fetches defined variables
$vars = self::executeFile($methodActionFilename, $vars, $className . ucfirst($method) . 'Action');
}
self::fireEvent('Atomik::Execute::After', array($action, &$context, &$vars, &$triggerError));
// deletes the execution context
array_pop(self::$execContexts);
// returns $vars if the view should not be rendered
if ($render === false) {
return $vars;
}
// no view
if ($view === false) {
return '';
}
// renders the view associated to the action
return self::render($view, $vars, $triggerError);
}
/**
* Executes the action file inside a clean scope and returns defined variables
*
* @see Atomik::_execute()
* @param string $actionFilename
* @param array $vars Variables that will be available in the scope
* @param string $className If a class name is specified, it will try to execute its execute() static method
* @return array
*/
public static function executeFile($actionFilename, $vars = array(), $className = null)
{
self::fireEvent('Atomik::Executefile', array(&$actionFilename, &$vars));
$atomik = new self();
$vars = $atomik->_execute($actionFilename, $vars, $className);
$atomik = null;
return $vars;
}
/**
* Executes a file inside a clean scope and returns defined variables
*
* @internal
* @param string $__filename Filename
* @param array $__vars An array containing key/value pairs that will be transformed to variables accessible inside the file
* @return string View output
*/
private function _execute($__filename, $__vars = array(), $__className = null)
{
extract($__vars);
require($__filename);
$vars = array();
// checks if a class is used
if ($__className !== null && class_exists($__className, false) && method_exists($__className, 'execute')) {
// call the class execute() static method
if (($vars = call_user_func(array($__className, 'execute'))) === null) {
$vars = array();
}
$vars = array_merge(get_class_vars($__className), $vars);
}
// retreives "public" variables (not prefixed with an underscore)
$definedVars = get_defined_vars();
foreach ($definedVars as $name => $value) {
if (substr($name, 0, 1) != '_') {
$vars[$name] = $value;
}
}