/
front.php
732 lines (621 loc) · 16.8 KB
/
front.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
<?php //-->
/*
* This file is part of the Eden package.
* (c) 2009-2011 Christian Blanquera <cblanquera@gmail.com>
*
* Copyright and license information can be found at LICENSE.txt
* distributed with this package.
*/
require_once dirname(__FILE__).'/../library/eden.php';
/**
* The starting point of every application call. If you are only
* using the framework you can rename this function to whatever you
* like.
*
* @author Christian Blanquera <cblanquera@gmail.com>
* @version $Id: application.php 21 2010-01-06 01:19:17Z blanquera $
*/
function front() {
$class = Front::i();
if(func_num_args() == 0) {
return $class;
}
$args = func_get_args();
return $class->__invoke($args);
}
/**
* Defines the starting point of every site call.
* Starts laying out how classes and methods are handled.
*
* @package Eden
* @category site
* @author Christian Blanquera <cblanquera@gmail.com>
* @version $Id: application.php 9 2010-01-12 15:42:40Z blanquera $
*/
class Front extends Eden {
/* Constants
-------------------------------*/
/* Public Properties
-------------------------------*/
/* Protected Properties
-------------------------------*/
protected $_database = NULL;
protected $_cache = NULL;
protected $_registry = NULL;
protected $_pages = array();
/* Private Properties
-------------------------------*/
/* Get
-------------------------------*/
public static function i() {
return self::_getSingleton(__CLASS__);
}
/* Magic
-------------------------------*/
public function __construct() {
if(!self::$_active) {
self::$_active = $this;
}
$this->_root = dirname(__FILE__);
$this->setLoader();
//require registry
$this->_registry = Eden_Loader::i()
->addRoot(dirname(__FILE__).'/library')
->load('Eden_Registry')
->Eden_Registry();
}
/* Public R/R Methods
-------------------------------*/
/**
* Lets the framework handle exceptions.
* This is useful in the case that you
* use this framework on a server with
* no xdebug installed.
*
* @param string|null the error type to report
* @param bool|null true will turn debug on
* @return this
*/
public function setDebug($reporting = NULL, $default = NULL) {
Eden_Error::i()->argument(1, 'int', 'null')->argument(2, 'bool', 'null');
Eden_Loader::i()
->load('Eden_Template')
->Eden_Error_Event()
->when(!is_null($reporting), 1)
->setReporting($reporting)
->when($default === true, 4)
->setErrorHandler()
->setExceptionHandler()
->listen('error', $this, 'error')
->listen('exception', $this, 'error')
->when($default === false, 4)
->releaseErrorHandler()
->releaseExceptionHandler()
->unlisten('error', $this, 'error')
->unlisten('exception', $this, 'error');
return $this;
}
/**
* Sets the application absolute paths
* for later referencing
*
* @return this
*/
public function setPaths(array $paths = array()) {
$default = array(
'root' => $this->_root,
'model' => $this->_root.'/model',
'web' => $this->_root.'/web',
'assets' => $this->_root.'/web/assets',
'cache' => $this->_root.'/front/cache',
'config' => $this->_root.'/../../config',
'template' => $this->_root.'/front/template',
'upload' => realpath($this->_root.'/../../upload'));
//foreach default path
foreach($default as $key => $path) {
$this->_registry->set('path', $key, $path);
}
//for each path
foreach($paths as $key => $path) {
//make them absolute
$path = (string) Eden_Path::i($path)->absolute();
//set it
$this->_registry->set('path', $key, $path);
}
return $this;
}
/**
* Sets page aliases
*
* @return this
*/
public function setPages($pages, $absolute = false) {
Front_Error::i()
->argument(1, 'string', 'array')
->argument(2, 'bool');
if(is_string($pages)) {
if(!$absolute) {
$pages = $this->_registry->get('path', 'config').'/'.$pages;
}
$pages = include($pages);
}
$this->_pages = $pages;
return $this;
}
/**
* Sets request
*
* @param EdenRegistry|null the request object
* @return this
*/
public function setRequest(Eden_Registry $request = NULL) {
//if no request
if(is_null($request)) {
//set the request
$request = $this->_registry;
}
$path = '/';
if(isset($_GET['request_path'])) {
$path = $_GET['request_path'];
unset($_GET['request_path']);
}
//determine a request path
$path = str_replace('favicon.ico', '/', $path);
//fix the request path
$path = (string) Eden_Path::i($path);
//get the path array
$pathArray = explode('/', $path);
//determine the page suggestions
$suggestions = array();
//for each of the page pattern to paths
foreach($this->_pages as $pagePattern => $pagePath) {
//we need to replace % with .*
//so for example /page/%/edit is the same as /page/.*/edit
$pattern = '%'.str_replace('%', '.*', $pagePattern).'%';
//if the path matches the response path key
if(preg_match($pattern, $path)) {
//add the path and the length to the suggestions
//we do this because we need to sort the suggestions
//by relavancy
$suggestions[strlen($pagePattern)][] = array($pagePattern, $pagePath);
}
}
//by default the page is the home page
$page = NULL;
//when given a path like /page/1/edit
//and a pattern like /page/%/edit
//we can determine one of the path variables is 1
//make a place holder for path variables
//which we will find later
$variables = array();
//to do that we need suggestions
//so if we have suggestions
if(!empty($suggestions)) {
//sort suggestions by length because the more detailed the
//page link the more probable this is the page they actually want
krsort($suggestions);
//for the page to fetch we only care about the first suggestion and
//second index in array($pagePattern, $pagePath)
$suggestions = array_shift($suggestions);
$suggestions = array_shift($suggestions);
$page = $suggestions[1];
//lets determine the path variables
$variables = $this->_getPageVariables($path, $suggestions[0]);
} else {
$classBuffer = $pathArray;
while(count($classBuffer) > 1) {
$classParts = ucwords(implode(' ', $classBuffer));
$page = 'Front_Page'.str_replace(' ', '_', $classParts);
if(class_exists($page)) {
break;
}
$variable = array_pop($classBuffer);
array_unshift($variables, $variable);
}
if(count($classBuffer) == 1) {
$page = NULL;
}
}
$path = array(
'string' => $path,
'array' => $pathArray,
'variables' => $variables);
//set the request
$request->set('server', $_SERVER)
->set('cookie', $_COOKIE)
->set('get', $_GET)
->set('post', $_POST)
->set('files', $_FILES)
->set('request', $path)
->set('page', $page);
return $this;
}
/**
* Sets response
*
* @param EdenRegistry|null the request object
* @return this
*/
public function setResponse($default, Eden_Registry $request = NULL) {
//if no request
if(is_null($request)) {
//set the request
$request = $this->_registry;
}
$page = $request->get('page');
if(!$page || !class_exists($page)) {
$page = $default;
}
//set the response data
$response = $this->$page($request);
$request->set('response', $response);
return $this;
}
/**
* returns the response
*
* @param EdenRegistry|null the request object
* @return string
*/
public function getResponse(Eden_Registry $request = NULL) {
//if no request
if(is_null($request)) {
//set the request
$request = $this->_registry;
}
return $request->get('response');
}
/* Public Database Methods
-------------------------------*/
/**
* Sets up the default database connection
*
* @return this
*/
public function addDatabase($key, $type = NULL,
$host = NULL, $name = NULL,
$user = NULL, $pass = NULL,
$default = true) {
Front_Error::i()
->argument(1, 'string', 'array', 'null')
->argument(2, 'string', 'null')
->argument(3, 'string', 'null')
->argument(4, 'string', 'null')
->argument(5, 'string', 'null')
->argument(6, 'string', 'null')
->argument(7, 'bool');
if(is_array($key)) {
$type = isset($key['type']) ? $key['type'] : NULL;
$host = isset($key['host']) ? $key['host'] : NULL;
$name = isset($key['name']) ? $key['name'] : NULL;
$user = isset($key['user']) ? $key['user'] : NULL;
$pass = isset($key['pass']) ? $key['pass'] : NULL;
$default = isset($key['default']) ? $key['default'] : true;
$key = isset($key['key']) ? $key['key'] : NULL;
}
//connect to the data as described in the config
switch($type) {
case 'postgre':
$database = Eden_Pgsql::i($host, $name, $user, $pass);
break;
case 'mysql':
$database = Eden_Mysql::i($host, $name, $user, $pass);
break;
}
$this->_registry->set('database', $key, $database);
if($default) {
$this->_database = $database;
}
return $this;
}
/**
* Returns the default database instance
*
* @return Eden_Database_Abstract
*/
public function getDatabase($key = NULL) {
if(is_null($key)) {
//return the default database
return $this->_database;
}
return $this->_registry->get('database', $key);
}
/**
* Sets the default database
*
* @param string key
* @return this
*/
public function setDefaultDatabase($key) {
Front_Error::i()->argument(1, 'string');
$args = func_get_args();
//if the args are greater than 5
//they mean to add it
if(count($args) > 5) {
$this->addDatabase($args[0], $args[1], $args[2], $args[3], $args[4], $args[5]);
}
//now set it
$this->_database = $this->_registry->getValue('database', $key);
return $this;
}
/* Public Event Methods
-------------------------------*/
/**
* Starts filters. Filters will handle when to run.
*
* @param string|array handlers
* @return Eden_Application
*/
public function setFilters($filters) {
Front_Error::i()->argument(1, 'string', 'array');
if(is_string($filters)) {
$filters = include($filters);
}
//for each handler as class
foreach($filters as $class) {
//try to
try {
//instantiate the class
$this->$class($this);
//when there's an error do nothing
} catch(Exception $e){}
}
return $this;
}
/* Public Misc Methods
-------------------------------*/
/**
* Sets the cache
*
* @return this
*/
public function setCache($root) {
//we need Eden_Path to fix the path formatting
if(!class_exists('Eden_Path')) {
Eden_Loader::i()->load('Eden_Path');
}
//format the path
$root = (string) Eden_Path::i($root);
// Start the Global Cache
Eden_Cache::i($root);
return $this;
}
/**
* Returns or saves the config
* data given the key
*
* @param string
* @return array
*/
public function getConfig($key, $data = NULL) {
$path = $this->getPath('config');
$file = $this->Eden_File($path.'/'.$key.'.php');
if(is_array($data)) {
$file->setData($data);
return $this;
}
if(!file_exists($file)) {
return array();
}
$config = $file->getData();
if(isset($config[$data])) {
return $config[$data];
}
return $config;
}
/**
* Returns the absolute path
* given the key
*
* @param string
* @return string
*/
public function getPath($key) {
return $this->getRegistry()->get('path', $key);
}
/**
* Returns the current Registry
*
* @return Eden_Registry
*/
public function getRegistry() {
return $this->_registry;
}
/**
* Redirect
*
* @param string the path to redirect
* @return void
*/
public function redirect($path, $variables = array(), $local = true) {
if(is_array($variables) && !empty($variables)) {
$path = vsprintf($path, $variables);
}
if($local) {
$path = $this->getPath('url').$path;
}
header('Location: '.$path);
exit;
}
/**
* Returns the template loaded with specified data
*
* @param array
* @return Eden_Template
*/
public function template($file, array $data = array()) {
Front_Error::i()->argument(1, 'string');
return Eden_Template::i()->set($data)->parsePhp($file);
}
/**
* Returns the template loaded with specified data
*
* @param array
* @return Eden_Template
*/
public function block($name) {
Front_Error:: i()->argument(1, 'string');
$args = func_get_args();
$name = array_shift($args);
$class = 'Front_Block_'.ucwords($name);
if(class_exists($class)) {
return Eden_Route:: i()->getClass($class, $args);
}
$class = 'Eden_Block_'.ucwords($name);
if(class_exists($class)) {
return Eden_Route:: i()->getClass($class, $args);
}
return false;
}
public function output($variable) {
eden('debug')->output($variable);
}
/**
* Return the discount and the discounted amount
*
* @param numeric
* @param float | numeric
* return array containing the discount and discounted amount
*/
public function getDiscount($amount, $percent) {
$discount = $percent * 0.01;
$discountPrice = $amount * $discount;
return $discountPrice;
}
/**
* Returns a mysql model
*
* @param string
* @return Eden_Mysql_Model
*/
public function model($table, $data = NULL, $column = NULL) {
//argument test
Product_Error:: i()
->argument(1, 'string')
->argument(2, 'scalar', 'array', 'null')
->argument(3, 'string', 'null');
if(is_null($data)) {
$data = array();
}
if(is_array($data)) {
return $this->getDatabase()->model($data)->setTable($table);
}
$database = $this->getDatabase();
if(is_null($column)) {
$column = $database()->getPrimaryKey($table);
}
if(is_null($column)) {
return $database()->model()->setTable($table);
}
return $this->getDatabase()->getModel($table, $column, $data);
//if data is not null
if(!is_null($data)) {
$model->load($data, $column);
}
}
public function getQuery(array $query, $key, $value) {
if(isset($query[$key]) && is_array($query[$key]) && is_array($value)) {
$query[$key] = array_merge($query[$key], $value);
} else {
$query[$key] = $value;
}
return http_build_query($query);
}
public function getSortQuery(array $query, $sort, $default = 'ASC') {
if(!isset($query['sort']) || $query['sort'] != $sort) {
$query['sort'] = $sort;
$query['order'] = $default;
return http_build_query($query);
}
if($query['order'] == 'ASC') {
$query['order'] = 'DESC';
} else if(isset($query['order'], $query['sort'])) {
$query['order'] = $default;
}
return http_build_query($query);
}
public function charset($string) {
$string = str_replace("\0", '', utf8_encode($string));
//$string = iconv('UTF-8', 'ISO-8859-1//IGNORE', utf8_encode($string));
$string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x80-\xFF]/u', '', $string);
return $string;
}
/**
* Error trigger output
*
* @return void
*/
public function error($e, $event, $type, $level, $class, $file, $line, $message, $trace, $offset) {
Front_Error::i()->initError($e, $event, $type, $level, $class, $file, $line, $message, $trace, $offset);
exit;
}
/* Protected Methods
-------------------------------*/
protected function _getPageVariables($requestPath, $pagePath) {
//if requestPath is not string
if(!is_string($requestPath)) {
//throw exception
throw new Eden_Site_Exception(sprintf(Eden_Exception::NOT_STRING, 1));
}
//if pagePath is not string
if(!is_string($pagePath)) {
//throw exception
throw new Eden_Site_Exception(sprintf(Eden_Exception::NOT_STRING, 2));
}
$variables = array();
//fix paths
$requestPath = $this->getFormattedPath($requestPath);
//if the request path equals /
if($requestPath == '/') {
//there would be no page variables
return array();
}
$pagePath = $this->getFormattedPath($pagePath);
//get the arrays
$requestPathArray = explode('/', $requestPath);
$pagePathArray = explode('/', $pagePath);
//we do not need the first path because
// /page/1 is [null,page,1] in an array
array_shift($requestPathArray);
array_shift($pagePathArray);
//for each request path
foreach($requestPathArray as $i => $value) {
//if the page path is not set, is null or is '%'
if(!isset($pagePathArray[$i])
|| trim($pagePathArray[$i]) == NULL
|| $pagePathArray[$i] == '%') {
//then we can assume it's a variable
$variables[] = $requestPathArray[$i];
}
}
return $variables;
}
protected function _getArguments($arguments) {
if(empty($arguments)) {
return array();
}
//for each argument
foreach($arguments as $i => $argument) {
//is it a string ?
if(is_string($argument)) {
$argument = "'".$argument."'";
//is it an array ?
} else if(is_array($argument)) {
$argument = 'Array';
//is it an object ?
} else if(is_object($argument)) {
$argument = get_class($argument);
//is it a bool ?
} else if(is_bool($argument)) {
$argument = $argument ? 'true' : 'false';
//is it null ?
} else if(is_null($argument)) {
$argument = 'null';
}
$arguments[$i] = $argument;
}
return $arguments;
}
/* Private Methods
-------------------------------*/
}