Passed
Push — 1.0.0-dev ( 2a3084...8edc19 )
by nguereza
02:58
created
core/libraries/FormValidation.php 1 patch
Indentation   +94 added lines, -94 removed lines patch added patch discarded remove patch
@@ -22,10 +22,10 @@  discard block
 block discarded – undo
22 22
      * You should have received a copy of the GNU General Public License
23 23
      * along with this program; if not, write to the Free Software
24 24
      * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-    */
25
+     */
26 26
 
27 27
 
28
-     class FormValidation{
28
+        class FormValidation{
29 29
 		 
30 30
         /**
31 31
          * The form validation status
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
          */
61 61
         protected $_eachErrorDelimiter   = array('<p class="error">', '</p>');
62 62
         
63
-		/**
63
+        /**
64 64
          * Indicated if need force the validation to be failed
65 65
          * @var boolean
66 66
          */
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
             $this->logger =& class_loader('Log', 'classes');
101 101
             $this->logger->setLogger('Library::FormValidation');
102 102
            
103
-		   //Load form validation language message
103
+            //Load form validation language message
104 104
             Loader::lang('form_validation');
105 105
             $obj = & get_instance();
106 106
             $this->_errorsMessages  = array(
@@ -162,13 +162,13 @@  discard block
 block discarded – undo
162 162
         /**
163 163
          * Set the form validation data
164 164
          * @param array $data the values to be validated
165
-		 *
165
+         *
166 166
          * @return FormValidation Current instance of object.
167 167
          */
168 168
         public function setData(array $data){
169 169
             $this->logger->debug('Setting the form validation data, the values are: ' . stringfy_vars($data));
170 170
             $this->data = $data;
171
-			return $this;
171
+            return $this;
172 172
         }
173 173
 
174 174
         /**
@@ -179,11 +179,11 @@  discard block
 block discarded – undo
179 179
             return $this->data;
180 180
         }
181 181
 
182
-		/**
183
-		* Get the validation function name to validate a rule
184
-		*
185
-		* @return string the function name
186
-		*/
182
+        /**
183
+         * Get the validation function name to validate a rule
184
+         *
185
+         * @return string the function name
186
+         */
187 187
         protected function _toCallCase($funcName, $prefix='_validate') {
188 188
             $funcName = strtolower($funcName);
189 189
             $finalFuncName = $prefix;
@@ -253,12 +253,12 @@  discard block
 block discarded – undo
253 253
             $this->_forceFail = false;
254 254
 
255 255
             foreach ($this->getData() as $inputName => $inputVal) {
256
-    			if(is_array($this->data[$inputName])){
257
-    				$this->data[$inputName] = array_map('trim', $this->data[$inputName]);
258
-    			}
259
-    			else{
260
-    				$this->data[$inputName] = trim($this->data[$inputName]);
261
-    			}
256
+                if(is_array($this->data[$inputName])){
257
+                    $this->data[$inputName] = array_map('trim', $this->data[$inputName]);
258
+                }
259
+                else{
260
+                    $this->data[$inputName] = trim($this->data[$inputName]);
261
+                }
262 262
 
263 263
                 if (array_key_exists($inputName, $this->_rules)) {
264 264
                     foreach ($this->_parseRuleString($this->_rules[$inputName]) as $eachRule) {
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
          *
275 275
          * @param string $inputField Name of the field or the data key to add a rule to
276 276
          * @param string $ruleSets PIPE seperated string of rules
277
-		 *
277
+         *
278 278
          * @return FormValidation Current instance of object.
279 279
          */
280 280
         public function setRule($inputField, $inputLabel, $ruleSets) {
@@ -288,8 +288,8 @@  discard block
 block discarded – undo
288 288
          * Takes an array of rules and uses setRule() to set them, accepts an array
289 289
          * of rule names rather than a pipe-delimited string as well.
290 290
          * @param array $ruleSets
291
-		 *
292
-		 * @return FormValidation Current instance of object.
291
+         *
292
+         * @return FormValidation Current instance of object.
293 293
          */
294 294
         public function setRules(array $ruleSets) {
295 295
             foreach ($ruleSets as $ruleSet) {
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
          * @param string $start Before block of errors gets displayed, HTML allowed.
312 312
          * @param string $end After the block of errors gets displayed, HTML allowed.
313 313
          *
314
-		 * @return FormValidation Current instance of object.
314
+         * @return FormValidation Current instance of object.
315 315
          */
316 316
         public function setErrorsDelimiter($start, $end) {
317 317
             $this->_allErrorsDelimiter[0] = $start;
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
          * @param string $start Displayed before each error.
327 327
          * @param string $end Displayed after each error.
328 328
          * 
329
-		 * @return FormValidation Current instance of object.
329
+         * @return FormValidation Current instance of object.
330 330
          */
331 331
         public function setErrorDelimiter($start, $end) {
332 332
             $this->_eachErrorDelimiter[0] = $start;
@@ -334,21 +334,21 @@  discard block
 block discarded – undo
334 334
             return $this;
335 335
         }
336 336
 
337
-		/**
338
-		* Get the each errors delimiters
339
-		*
340
-		* @return array
341
-		*/
342
-    	public function getErrorDelimiter() {
337
+        /**
338
+         * Get the each errors delimiters
339
+         *
340
+         * @return array
341
+         */
342
+        public function getErrorDelimiter() {
343 343
             return $this->_eachErrorDelimiter;
344 344
         }
345 345
 
346
-		/**
347
-		* Get the all errors delimiters
348
-		*
349
-		* @return array
350
-		*/
351
-    	public function getErrorsDelimiter() {
346
+        /**
347
+         * Get the all errors delimiters
348
+         *
349
+         * @return array
350
+         */
351
+        public function getErrorsDelimiter() {
352 352
             return $this->_allErrorsDelimiter;
353 353
         }
354 354
 
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
          *
387 387
          * @param string $inputName The form input name or data key
388 388
          * @param string $errorMessage Error to display
389
-		 *
389
+         *
390 390
          * @return formValidation Current instance of the object
391 391
          */
392 392
         public function setCustomError($inputName, $errorMessage) {
@@ -423,17 +423,17 @@  discard block
 block discarded – undo
423 423
          *
424 424
          * @param boolean $limit number of error to display or return
425 425
          * @param boolean $echo Whether or not the values are to be returned or displayed
426
-		 *
426
+         *
427 427
          * @return string Errors formatted for output
428 428
          */
429 429
         public function displayErrors($limit = null, $echo = true) {
430 430
             list($errorsStart, $errorsEnd) = $this->_allErrorsDelimiter;
431 431
             list($errorStart, $errorEnd) = $this->_eachErrorDelimiter;
432 432
             $errorOutput = $errorsStart;
433
-    		$i = 0;
433
+            $i = 0;
434 434
             if (!empty($this->_errors)) {
435 435
                 foreach ($this->_errors as $fieldName => $error) {
436
-        	    	if ($i === $limit) { 
436
+                    if ($i === $limit) { 
437 437
                         break; 
438 438
                     }
439 439
                     $errorOutput .= $errorStart;
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
          * Breaks up a PIPE seperated string of rules, and puts them into an array.
462 462
          *
463 463
          * @param string $ruleString String to be parsed.
464
-		 *
464
+         *
465 465
          * @return array Array of each value in original string.
466 466
          */
467 467
         protected function _parseRuleString($ruleString) {
@@ -474,10 +474,10 @@  discard block
 block discarded – undo
474 474
                 $rule = '#regex\[\/(.*)\/([a-zA-Z0-9]?)\]#';
475 475
                 preg_match($rule, $ruleString, $regexRule);
476 476
                 $ruleStringTemp = preg_replace($rule, '', $ruleString);
477
-                 if(!empty($regexRule[0])){
478
-                     $ruleSets[] = $regexRule[0];
479
-                 }
480
-                 $ruleStringRegex = explode('|', $ruleStringTemp);
477
+                    if(!empty($regexRule[0])){
478
+                        $ruleSets[] = $regexRule[0];
479
+                    }
480
+                    $ruleStringRegex = explode('|', $ruleStringTemp);
481 481
                 foreach ($ruleStringRegex as $rule) {
482 482
                     $rule = trim($rule);
483 483
                     if($rule){
@@ -493,7 +493,7 @@  discard block
 block discarded – undo
493 493
                 } else {
494 494
                     $ruleSets[] = $ruleString;
495 495
                 }
496
-             }
496
+                }
497 497
             return $ruleSets;
498 498
         }
499 499
 
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
          * Returns whether or not a field obtains the rule "required".
502 502
          *
503 503
          * @param string $fieldName Field to check if required.
504
-		 *
504
+         *
505 505
          * @return boolean Whether or not the field is required.
506 506
          */
507 507
         protected function _fieldIsRequired($fieldName) {
@@ -536,13 +536,13 @@  discard block
 block discarded – undo
536 536
             return;
537 537
         }
538 538
 
539
-		/**
540
-		* Set error for the given field or key
541
-		*
542
-		* @param string $inputName the input or key name
543
-		* @param string $ruleName the rule name
544
-		* @param array|string $replacements
545
-		*/
539
+        /**
540
+         * Set error for the given field or key
541
+         *
542
+         * @param string $inputName the input or key name
543
+         * @param string $ruleName the rule name
544
+         * @param array|string $replacements
545
+         */
546 546
         protected function _setError($inputName, $ruleName, $replacements = array()) {
547 547
             $rulePhraseKeyParts = explode(',', $ruleName);
548 548
             $rulePhrase = null;
@@ -559,7 +559,7 @@  discard block
 block discarded – undo
559 559
             }
560 560
             // Type cast to array in case it's a string
561 561
             $replacements = (array) $replacements;
562
-			$replacementCount = count($replacements);
562
+            $replacementCount = count($replacements);
563 563
             for ($i = 1; $i <= $replacementCount; $i++) {
564 564
                 $key = $i - 1;
565 565
                 $rulePhrase = str_replace('%' . $i, $replacements[$key], $rulePhrase);
@@ -577,11 +577,11 @@  discard block
 block discarded – undo
577 577
          *
578 578
          * @param type $inputArg
579 579
          * @param string $callbackFunc
580
-		 *
580
+         *
581 581
          * @return mixed
582 582
          */
583 583
         protected function _runCallback($inputArg, $callbackFunc) {
584
-			return eval('return ' . $callbackFunc . '("' . $inputArg . '");');
584
+            return eval('return ' . $callbackFunc . '("' . $inputArg . '");');
585 585
         }
586 586
 
587 587
         /**
@@ -590,7 +590,7 @@  discard block
 block discarded – undo
590 590
          * arguments.
591 591
          *
592 592
          * @param string $callbackFunc
593
-		 *
593
+         *
594 594
          * @return mixed
595 595
          */
596 596
         protected function _runEmptyCallback($callbackFunc) {
@@ -601,7 +601,7 @@  discard block
 block discarded – undo
601 601
          * Gets a specific label of a specific field input name.
602 602
          *
603 603
          * @param string $inputName
604
-		 *
604
+         *
605 605
          * @return string
606 606
          */
607 607
         protected function _getLabel($inputName) {
@@ -614,7 +614,7 @@  discard block
 block discarded – undo
614 614
          * @param  string $ruleName  the rule name for this validation ("required")
615 615
          * @param  array  $ruleArgs  the rules argument
616 616
          */
617
-		protected function _validateRequired($inputName, $ruleName, array $ruleArgs) {
617
+        protected function _validateRequired($inputName, $ruleName, array $ruleArgs) {
618 618
             $inputVal = $this->post($inputName);
619 619
             if(array_key_exists(1, $ruleArgs) && function_exists($ruleArgs[1])) {
620 620
                 $callbackReturn = $this->_runEmptyCallback($ruleArgs[1]);
@@ -622,8 +622,8 @@  discard block
 block discarded – undo
622 622
                     $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
623 623
                 }
624 624
             } 
625
-			else if($inputVal == '') {
626
-				$this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
625
+            else if($inputVal == '') {
626
+                $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
627 627
             }
628 628
         }
629 629
 
@@ -647,10 +647,10 @@  discard block
 block discarded – undo
647 647
          */
648 648
         protected function _validateCallback($inputName, $ruleName, array $ruleArgs) {
649 649
             if (function_exists($ruleArgs[1]) && !empty($this->data[$inputName])) {
650
-				$result = $this->_runCallback($this->data[$inputName], $ruleArgs[1]);
651
-				if(! $result){
652
-					$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
653
-				}
650
+                $result = $this->_runCallback($this->data[$inputName], $ruleArgs[1]);
651
+                if(! $result){
652
+                    $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
653
+                }
654 654
             }
655 655
         }
656 656
 
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
                         continue;
683 683
                     }
684 684
                 } 
685
-				else{
685
+                else{
686 686
                     if ($inputVal == $doNotEqual) {
687 687
                         $this->_setError($inputName, $ruleName . ',string', array($this->_getLabel($inputName), $doNotEqual));
688 688
                         continue;
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
          * @param  string $ruleName  the rule name for this validation ("less_than")
775 775
          * @param  array  $ruleArgs  the rules argument
776 776
          */
777
-    	protected function _validateLessThan($inputName, $ruleName, array $ruleArgs) {
777
+        protected function _validateLessThan($inputName, $ruleName, array $ruleArgs) {
778 778
             $inputVal = $this->post($inputName);
779 779
             if ($inputVal >= $ruleArgs[1]) { 
780 780
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
@@ -790,7 +790,7 @@  discard block
 block discarded – undo
790 790
          * @param  string $ruleName  the rule name for this validation ("greater_than")
791 791
          * @param  array  $ruleArgs  the rules argument
792 792
          */
793
-    	protected function _validateGreaterThan($inputName, $ruleName, array $ruleArgs) {
793
+        protected function _validateGreaterThan($inputName, $ruleName, array $ruleArgs) {
794 794
             $inputVal = $this->post($inputName);
795 795
             if ($inputVal <= $ruleArgs[1]) {
796 796
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
@@ -806,7 +806,7 @@  discard block
 block discarded – undo
806 806
          * @param  string $ruleName  the rule name for this validation ("numeric")
807 807
          * @param  array  $ruleArgs  the rules argument
808 808
          */
809
-    	protected function _validateNumeric($inputName, $ruleName, array $ruleArgs) {
809
+        protected function _validateNumeric($inputName, $ruleName, array $ruleArgs) {
810 810
             $inputVal = $this->post($inputName);
811 811
             if (! is_numeric($inputVal)) {
812 812
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
@@ -822,18 +822,18 @@  discard block
 block discarded – undo
822 822
          * @param  string $ruleName  the rule name for this validation ("exists")
823 823
          * @param  array  $ruleArgs  the rules argument
824 824
          */
825
-		protected function _validateExists($inputName, $ruleName, array $ruleArgs) {
825
+        protected function _validateExists($inputName, $ruleName, array $ruleArgs) {
826 826
             $inputVal = $this->post($inputName);
827
-    		if (! is_object($this->databaseInstance)){
827
+            if (! is_object($this->databaseInstance)){
828 828
                 $obj = & get_instance();
829 829
                 if(isset($obj->database)){
830 830
                     $this->databaseInstance = $obj->database;
831 831
                 } 
832 832
             }
833
-    		list($table, $column) = explode('.', $ruleArgs[1]);
834
-    		$this->databaseInstance->getQueryBuilder()->from($table)
835
-    			                                       ->where($column, $inputVal);
836
-    		$this->databaseInstance->get();
833
+            list($table, $column) = explode('.', $ruleArgs[1]);
834
+            $this->databaseInstance->getQueryBuilder()->from($table)
835
+                                                        ->where($column, $inputVal);
836
+            $this->databaseInstance->get();
837 837
             if ($this->databaseInstance->numRows() <= 0) {
838 838
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
839 839
                     return;
@@ -848,7 +848,7 @@  discard block
 block discarded – undo
848 848
          * @param  string $ruleName  the rule name for this validation ("is_unique")
849 849
          * @param  array  $ruleArgs  the rules argument
850 850
          */
851
-    	protected function _validateIsUnique($inputName, $ruleName, array $ruleArgs) {
851
+        protected function _validateIsUnique($inputName, $ruleName, array $ruleArgs) {
852 852
             $inputVal = $this->post($inputName);
853 853
             if (! is_object($this->databaseInstance)){
854 854
                 $obj = & get_instance();
@@ -856,11 +856,11 @@  discard block
 block discarded – undo
856 856
                     $this->databaseInstance = $obj->database;
857 857
                 } 
858 858
             }
859
-    		list($table, $column) = explode('.', $ruleArgs[1]);
860
-    		$this->databaseInstance->getQueryBuilder()->from($table)
861
-    			                                      ->where($column, $inputVal);
862
-    		$this->databaseInstance->get();
863
-    		if ($this->databaseInstance->numRows() > 0) {
859
+            list($table, $column) = explode('.', $ruleArgs[1]);
860
+            $this->databaseInstance->getQueryBuilder()->from($table)
861
+                                                        ->where($column, $inputVal);
862
+            $this->databaseInstance->get();
863
+            if ($this->databaseInstance->numRows() > 0) {
864 864
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
865 865
                     return;
866 866
                 }
@@ -874,25 +874,25 @@  discard block
 block discarded – undo
874 874
          * @param  string $ruleName  the rule name for this validation ("is_unique_update")
875 875
          * @param  array  $ruleArgs  the rules argument
876 876
          */
877
-    	protected function _validateIsUniqueUpdate($inputName, $ruleName, array $ruleArgs) {
877
+        protected function _validateIsUniqueUpdate($inputName, $ruleName, array $ruleArgs) {
878 878
             $inputVal = $this->post($inputName);
879
-    		if (! is_object($this->databaseInstance)){
879
+            if (! is_object($this->databaseInstance)){
880 880
                 $obj = & get_instance();
881 881
                 if(isset($obj->database)){
882 882
                     $this->databaseInstance = $obj->database;
883 883
                 } 
884 884
             }
885
-    		$data = explode(',', $ruleArgs[1]);
886
-    		if(count($data) < 2){
887
-    			return;
888
-    		}
889
-    		list($table, $column) = explode('.', $data[0]);
890
-    		list($field, $val)    = explode('=', $data[1]);
891
-    		$this->databaseInstance->getQueryBuilder()->from($table)
892
-                                			          ->where($column, $inputVal)
893
-                                            		  ->where($field, '!=', trim($val));
885
+            $data = explode(',', $ruleArgs[1]);
886
+            if(count($data) < 2){
887
+                return;
888
+            }
889
+            list($table, $column) = explode('.', $data[0]);
890
+            list($field, $val)    = explode('=', $data[1]);
891
+            $this->databaseInstance->getQueryBuilder()->from($table)
892
+                                                        ->where($column, $inputVal)
893
+                                                        ->where($field, '!=', trim($val));
894 894
             $this->databaseInstance->get();
895
-    		if ($this->databaseInstance->numRows() > 0) {
895
+            if ($this->databaseInstance->numRows() > 0) {
896 896
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
897 897
                     return;
898 898
                 }
@@ -908,7 +908,7 @@  discard block
 block discarded – undo
908 908
          */
909 909
         protected function _validateInList($inputName, $ruleName, array $ruleArgs) {
910 910
             $inputVal = $this->post($inputName);
911
-    		$list = explode(',', $ruleArgs[1]);
911
+            $list = explode(',', $ruleArgs[1]);
912 912
             $list = array_map('trim', $list);
913 913
             if (! in_array($inputVal, $list)) {
914 914
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
@@ -926,7 +926,7 @@  discard block
 block discarded – undo
926 926
          */
927 927
         protected function _validateRegex($inputName, $ruleName, array $ruleArgs) {
928 928
             $inputVal = $this->post($inputName);
929
-    		$regex = $ruleArgs[1];
929
+            $regex = $ruleArgs[1];
930 930
             if (! preg_match($regex, $inputVal)) {
931 931
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
932 932
                     return;
Please login to merge, or discard this patch.
core/libraries/Pagination.php 1 patch
Indentation   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -1,32 +1,32 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
     defined('ROOT_PATH') || exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26 26
 
27 27
     class Pagination{
28 28
         
29
-		/**
29
+        /**
30 30
          * The list of loaded config
31 31
          * @var array
32 32
          */
@@ -49,15 +49,15 @@  discard block
 block discarded – undo
49 49
                 if (empty($config) || ! is_array($config)){
50 50
                     show_error('No configuration found in ' . CONFIG_PATH . 'config_pagination.php');
51 51
                 }
52
-				else{
53
-					if (! empty($overwriteConfig)){
54
-						$config = array_merge($config, $overwriteConfig);
55
-					}
56
-					$this->config = $config;
52
+                else{
53
+                    if (! empty($overwriteConfig)){
54
+                        $config = array_merge($config, $overwriteConfig);
55
+                    }
56
+                    $this->config = $config;
57 57
                     //put it gobally
58
-					Config::setAll($config);
59
-					unset($config);
60
-				}
58
+                    Config::setAll($config);
59
+                    unset($config);
60
+                }
61 61
             }
62 62
             else{
63 63
                 show_error('Unable to find the pagination configuration file');
@@ -94,11 +94,11 @@  discard block
 block discarded – undo
94 94
             return $this->paginationQueryString;
95 95
         }
96 96
 
97
-         /**
98
-         * Set the value of the pagination query string
99
-         * @param string $paginationQueryString the new value
100
-         * @return object
101
-         */
97
+            /**
98
+             * Set the value of the pagination query string
99
+             * @param string $paginationQueryString the new value
100
+             * @return object
101
+             */
102 102
         public function setPaginationQueryString($paginationQueryString){
103 103
             $this->paginationQueryString = $paginationQueryString;
104 104
             return $this;
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
             $queryString = Url::queryString();
118 118
             $currentUrl = Url::current();
119 119
             $query = '';
120
-             if ($queryString == ''){
120
+                if ($queryString == ''){
121 121
                 $query = '?' . $pageQueryName . '=';
122 122
             }
123 123
             else{
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
          */
151 151
         public function getLink($totalRows, $currentPageNumber){
152 152
             $numberOfLink = $this->config['nb_link'];
153
-			$numberOfRowPerPage = $this->config['pagination_per_page'];
153
+            $numberOfRowPerPage = $this->config['pagination_per_page'];
154 154
             if (empty($this->paginationQueryString)){
155 155
                 //determine the pagination query string value
156 156
                 $this->determinePaginationQueryStringValue();
@@ -164,8 +164,8 @@  discard block
 block discarded – undo
164 164
             $numberOfRowPerPage = (int) $numberOfRowPerPage;
165 165
 			
166 166
             if ($currentPageNumber <= 0){
167
-				$currentPageNumber = 1;
168
-			}
167
+                $currentPageNumber = 1;
168
+            }
169 169
             if ($numberOfPage <= 1 || $numberOfLink <= 0 || $numberOfRowPerPage <= 0) {
170 170
                 return $navbar;
171 171
             }
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
                 $navbar .= $this->buildPaginationLinkForMiddlePage($begin, $end, $currentPageNumber);
207 207
             }
208 208
             else if ($currentPageNumber == $numberOfPage){
209
-               $navbar .= $this->buildPaginationLinkForLastPage($begin, $end, $currentPageNumber);
209
+                $navbar .= $this->buildPaginationLinkForLastPage($begin, $end, $currentPageNumber);
210 210
             }
211 211
             $navbar = $this->config['pagination_open'] . $navbar . $this->config['pagination_close'];
212 212
             return $navbar;
Please login to merge, or discard this patch.
core/libraries/Browser.php 1 patch
Indentation   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -1669,34 +1669,34 @@
 block discarded – undo
1669 1669
         protected function checkPlatform()
1670 1670
         {
1671 1671
             $platformMaps = array(
1672
-              'windows' => self::PLATFORM_WINDOWS,
1673
-              'iPad' => self::PLATFORM_IPAD,
1674
-              'iPod' => self::PLATFORM_IPOD,
1675
-              'iPhone' => self::PLATFORM_IPHONE,
1676
-              'mac' => self::PLATFORM_APPLE,
1677
-              'android' => self::PLATFORM_ANDROID,
1678
-              'Silk' => self::PLATFORM_FIRE_OS,
1679
-              'linux_smarttv' => self::PLATFORM_LINUX .'/'.self::PLATFORM_SMART_TV,
1680
-              'linux' => self::PLATFORM_LINUX,
1681
-              'Nokia' => self::PLATFORM_NOKIA,
1682
-              'BlackBerry' => self::PLATFORM_BLACKBERRY,
1683
-              'FreeBSD' => self::PLATFORM_FREEBSD,
1684
-              'OpenBSD' => self::PLATFORM_OPENBSD,
1685
-              'NetBSD' => self::PLATFORM_NETBSD,
1686
-              'OpenSolaris' => self::PLATFORM_OPENSOLARIS,
1687
-              'SunOS' => self::PLATFORM_SUNOS,
1688
-              'OS\/2' => self::PLATFORM_OS2,
1689
-              'BeOS' => self::PLATFORM_BEOS,
1690
-              'win' => self::PLATFORM_WINDOWS,
1691
-              'Playstation' => self::PLATFORM_PLAYSTATION,
1692
-              'Roku' => self::PLATFORM_ROKU,
1693
-              'iOS' => self::PLATFORM_IPHONE . '/' . self::PLATFORM_IPAD,
1694
-              'tvOS' => self::PLATFORM_APPLE_TV,
1695
-              'curl' => self::PLATFORM_TERMINAL,
1696
-              'CrOS' => self::PLATFORM_CHROME_OS,
1697
-              'okhttp' => self::PLATFORM_JAVA_ANDROID,
1698
-              'PostmanRuntime' => self::PLATFORM_POSTMAN,
1699
-              'Iframely' => self::PLATFORM_I_FRAME
1672
+                'windows' => self::PLATFORM_WINDOWS,
1673
+                'iPad' => self::PLATFORM_IPAD,
1674
+                'iPod' => self::PLATFORM_IPOD,
1675
+                'iPhone' => self::PLATFORM_IPHONE,
1676
+                'mac' => self::PLATFORM_APPLE,
1677
+                'android' => self::PLATFORM_ANDROID,
1678
+                'Silk' => self::PLATFORM_FIRE_OS,
1679
+                'linux_smarttv' => self::PLATFORM_LINUX .'/'.self::PLATFORM_SMART_TV,
1680
+                'linux' => self::PLATFORM_LINUX,
1681
+                'Nokia' => self::PLATFORM_NOKIA,
1682
+                'BlackBerry' => self::PLATFORM_BLACKBERRY,
1683
+                'FreeBSD' => self::PLATFORM_FREEBSD,
1684
+                'OpenBSD' => self::PLATFORM_OPENBSD,
1685
+                'NetBSD' => self::PLATFORM_NETBSD,
1686
+                'OpenSolaris' => self::PLATFORM_OPENSOLARIS,
1687
+                'SunOS' => self::PLATFORM_SUNOS,
1688
+                'OS\/2' => self::PLATFORM_OS2,
1689
+                'BeOS' => self::PLATFORM_BEOS,
1690
+                'win' => self::PLATFORM_WINDOWS,
1691
+                'Playstation' => self::PLATFORM_PLAYSTATION,
1692
+                'Roku' => self::PLATFORM_ROKU,
1693
+                'iOS' => self::PLATFORM_IPHONE . '/' . self::PLATFORM_IPAD,
1694
+                'tvOS' => self::PLATFORM_APPLE_TV,
1695
+                'curl' => self::PLATFORM_TERMINAL,
1696
+                'CrOS' => self::PLATFORM_CHROME_OS,
1697
+                'okhttp' => self::PLATFORM_JAVA_ANDROID,
1698
+                'PostmanRuntime' => self::PLATFORM_POSTMAN,
1699
+                'Iframely' => self::PLATFORM_I_FRAME
1700 1700
             );
1701 1701
 
1702 1702
             foreach ($platformMaps as $name => $value) {
Please login to merge, or discard this patch.
core/functions/function_string.php 1 patch
Indentation   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -1,71 +1,71 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') || exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
2
+    defined('ROOT_PATH') || exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26 26
 
27
-	/**
28
-	 *  @file function_string.php
29
-	 *
30
-	 *  This file contains the definition of the functions relating to the processing of strings characters.
31
-	 *
32
-	 *  @package	core
33
-	 *  @author	Tony NGUEREZA
34
-	 *  @copyright	Copyright (c) 2017
35
-	 *  @license	https://opensource.org/licenses/gpl-3.0.html GNU GPL License (GPL)
36
-	 *  @link	http://www.iacademy.cf
37
-	 *  @version 1.0.0
38
-	 *  @since 1.0.0
39
-	 *  @filesource
40
-	 */
27
+    /**
28
+     *  @file function_string.php
29
+     *
30
+     *  This file contains the definition of the functions relating to the processing of strings characters.
31
+     *
32
+     *  @package	core
33
+     *  @author	Tony NGUEREZA
34
+     *  @copyright	Copyright (c) 2017
35
+     *  @license	https://opensource.org/licenses/gpl-3.0.html GNU GPL License (GPL)
36
+     *  @link	http://www.iacademy.cf
37
+     *  @version 1.0.0
38
+     *  @since 1.0.0
39
+     *  @filesource
40
+     */
41 41
 
42
-	if(! function_exists('get_random_string')){
43
-		/**
44
-		 * Generate a random string
45
-		 * @param  string $type the type of generation. It can take the values: "alpha" for alphabetic characters,
46
-		 * "alnum" for alpha-numeric characters and "num" for numbers.
47
-		 * By default it is "alnum".
48
-		 * @param  integer $length the length of the string to generate. By default it is 10.
49
-		 * @param  boolean $lower if we return the generated string in lowercase (true). By default it's false.
50
-		 * @return string the generated string.
51
-		 */
52
-		function get_random_string($type = 'alnum', $length = 10, $lower = false){
53
-			$chars = array(
54
-							'alpha' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
55
-							'alnum' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',
56
-							'num' => '1234567890'
57
-						);
58
-			$str = null;
59
-			if(isset($chars[$type])){
60
-				$str = $chars[$type];
61
-			}
62
-			$random = null;
63
-			for($i = 0; $i < $length; $i++){
64
-				$random .= $str[mt_rand() % strlen($str)];
65
-			}
66
-			if($lower){
67
-				$random = strtolower($random);
68
-			}
69
-			return $random;
70
-		}
71
-	}
42
+    if(! function_exists('get_random_string')){
43
+        /**
44
+         * Generate a random string
45
+         * @param  string $type the type of generation. It can take the values: "alpha" for alphabetic characters,
46
+         * "alnum" for alpha-numeric characters and "num" for numbers.
47
+         * By default it is "alnum".
48
+         * @param  integer $length the length of the string to generate. By default it is 10.
49
+         * @param  boolean $lower if we return the generated string in lowercase (true). By default it's false.
50
+         * @return string the generated string.
51
+         */
52
+        function get_random_string($type = 'alnum', $length = 10, $lower = false){
53
+            $chars = array(
54
+                            'alpha' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
55
+                            'alnum' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',
56
+                            'num' => '1234567890'
57
+                        );
58
+            $str = null;
59
+            if(isset($chars[$type])){
60
+                $str = $chars[$type];
61
+            }
62
+            $random = null;
63
+            for($i = 0; $i < $length; $i++){
64
+                $random .= $str[mt_rand() % strlen($str)];
65
+            }
66
+            if($lower){
67
+                $random = strtolower($random);
68
+            }
69
+            return $random;
70
+        }
71
+    }
Please login to merge, or discard this patch.
tests/include/testsUtil.php 1 patch
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -1,18 +1,18 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-	/**
4
-	* Function to test private & protected method
5
-	*/
6
-	function run_private_protected_method($object, $method, array $args = array()){
7
-		$r = new ReflectionClass(get_class($object));
8
-		$m = $r->getMethod($method);
9
-		$m->setAccessible(true);
10
-		return $m->invokeArgs($object, $args);
11
-	}
3
+    /**
4
+     * Function to test private & protected method
5
+     */
6
+    function run_private_protected_method($object, $method, array $args = array()){
7
+        $r = new ReflectionClass(get_class($object));
8
+        $m = $r->getMethod($method);
9
+        $m->setAccessible(true);
10
+        return $m->invokeArgs($object, $args);
11
+    }
12 12
     
13 13
     /**
14
-	* Function to return the correct database configuration
15
-	*/
14
+     * Function to return the correct database configuration
15
+     */
16 16
     function get_db_config(){
17 17
         return array(
18 18
                     'driver'    =>  'sqlite',
Please login to merge, or discard this patch.
tests/tnhfw/classes/DBSessionHandlerTest.php 1 patch
Indentation   +199 added lines, -199 removed lines patch added patch discarded remove patch
@@ -1,222 +1,222 @@
 block discarded – undo
1 1
 <?php 
2 2
 
3
-	use PHPUnit\Framework\TestCase;
3
+    use PHPUnit\Framework\TestCase;
4 4
 
5
-	class DBSessionHandlerTest extends TestCase
6
-	{	
5
+    class DBSessionHandlerTest extends TestCase
6
+    {	
7 7
 	
8
-		private $db = null;
8
+        private $db = null;
9 9
 		
10
-		private $model = null;
10
+        private $model = null;
11 11
 		
12
-		private $secret = 'bXlzZWNyZXQ';
12
+        private $secret = 'bXlzZWNyZXQ';
13 13
 		
14
-		private static $config = null;
14
+        private static $config = null;
15 15
 		
16
-		public function __construct(){
16
+        public function __construct(){
17 17
             $cfg = get_db_config();
18
-			$this->db = new Database($cfg);
18
+            $this->db = new Database($cfg);
19 19
             $qr = new DatabaseQueryRunner($this->db->getPdo());
20 20
             $qr->setBenchmark(new Benchmark());
21 21
             $qr->setDriver('sqlite');
22 22
             $this->db->setQueryRunner($qr);
23
-		}
23
+        }
24 24
 		
25
-		public static function setUpBeforeClass()
26
-		{
27
-			require APPS_MODEL_PATH . 'DBSessionModel.php';
28
-			self::$config = new Config();
29
-			self::$config->init();
30
-		}
25
+        public static function setUpBeforeClass()
26
+        {
27
+            require APPS_MODEL_PATH . 'DBSessionModel.php';
28
+            self::$config = new Config();
29
+            self::$config->init();
30
+        }
31 31
 		
32 32
 		
33
-		public static function tearDownAfterClass()
34
-		{
33
+        public static function tearDownAfterClass()
34
+        {
35 35
 			
36
-		}
36
+        }
37 37
 		
38
-		protected function setUp()
39
-		{
40
-			$this->model = new DBSessionModel($this->db);
38
+        protected function setUp()
39
+        {
40
+            $this->model = new DBSessionModel($this->db);
41 41
             //to prevent old data conflict
42
-			$this->model->truncate();
43
-		}
42
+            $this->model->truncate();
43
+        }
44 44
 
45
-		protected function tearDown()
46
-		{
47
-		}
45
+        protected function tearDown()
46
+        {
47
+        }
48 48
 
49 49
 		
50 50
 		
51
-		public function testUsingSessionConfiguration(){
52
-			//using value in the configuration
53
-			self::$config->set('session_save_path', 'DBSessionModel');
54
-			self::$config->set('session_secret', $this->secret);
55
-			$dbsh = new DBSessionHandler();
56
-			//assign Database instance manually
57
-			$o = &get_instance();
58
-			$o->database = $this->db;
59
-			
60
-			$this->assertTrue($dbsh->open(null, null));
61
-			$this->assertTrue($dbsh->close());
62
-			$this->assertNull($dbsh->read('foo'));
63
-			$this->assertTrue($dbsh->write('foo', '444'));
64
-			$this->assertNotEmpty($dbsh->read('foo'));
65
-			$this->assertEquals($dbsh->read('foo'), '444');
66
-			//do update of existing data
67
-			$this->assertTrue($dbsh->write('foo', '445'));
68
-			$this->assertEquals($dbsh->read('foo'), '445');	
69
-			$this->assertTrue($dbsh->destroy('foo'));
70
-			$this->assertNull($dbsh->read('foo'));
71
-			$this->assertTrue($dbsh->gc(13));
72
-			$encoded = $dbsh->encode('foo');
73
-			$this->assertNotEmpty($encoded);
74
-			$this->assertEquals($dbsh->decode($encoded), 'foo');
75
-		}
76
-		
77
-		public function testWhenDataIsExpired(){
78
-			$dbsh = new DBSessionHandler($this->model);
79
-			$dbsh->setSessionSecret($this->secret);
80
-			
81
-			$this->assertTrue($dbsh->open(null, null));
82
-			$this->assertTrue($dbsh->write('foo', '444'));
83
-			$this->assertNotEmpty($dbsh->read('foo'));
84
-			$this->assertEquals($dbsh->read('foo'), '444');
85
-			//put it in expired
86
-			$this->model->update('foo', array('s_time' => 1234567));
87
-			$this->assertNull($dbsh->read('foo'));
88
-		}
89
-		
90
-		public function testWhenDataAlreadyExistDoUpdate(){
91
-			$dbsh = new DBSessionHandler($this->model);
92
-			$dbsh->setSessionSecret($this->secret);
93
-			
94
-			$this->assertTrue($dbsh->open(null, null));
95
-			$this->assertTrue($dbsh->write('foo', '444'));
96
-			$this->assertNotEmpty($dbsh->read('foo'));
97
-			$this->assertEquals($dbsh->read('foo'), '444');
98
-			//do update of existing data
99
-			$this->assertTrue($dbsh->write('foo', '445'));
100
-			$this->assertEquals($dbsh->read('foo'), '445');	
101
-		}
102
-		
103
-		public function testUsingCustomModelInstance(){
104
-			$dbsh = new DBSessionHandler($this->model);
105
-			$dbsh->setSessionSecret($this->secret);
106
-			
107
-			$this->assertTrue($dbsh->open(null, null));
108
-			$this->assertTrue($dbsh->close());
109
-			$this->assertNull($dbsh->read('foo'));
110
-			$this->assertTrue($dbsh->write('foo', '444'));
111
-			$this->assertNotEmpty($dbsh->read('foo'));
112
-			$this->assertEquals($dbsh->read('foo'), '444');
113
-			//put it in expired
114
-			$this->model->update('foo', array('s_time' => 1234567));
115
-			
116
-			$this->assertNull($dbsh->read('foo'));
117
-			$this->assertTrue($dbsh->write('foo', '444'));
118
-			
119
-			//do update of existing data
120
-			$this->assertTrue($dbsh->write('foo', '445'));
121
-			$this->assertEquals($dbsh->read('foo'), '445');	
122
-			$this->assertTrue($dbsh->destroy('foo'));
123
-			$this->assertNull($dbsh->read('foo'));
124
-			$this->assertTrue($dbsh->gc(13));
125
-			$encoded = $dbsh->encode('foo');
126
-			$this->assertNotEmpty($encoded);
127
-			$this->assertEquals($dbsh->decode($encoded), 'foo');
128
-		}
129
-			
130
-			
131
-		public function testUsingCustomLogInstance(){
132
-			$dbsh = new DBSessionHandler($this->model, new Log());
133
-			$dbsh->setSessionSecret($this->secret);
134
-			
135
-			$this->assertTrue($dbsh->open(null, null));
136
-			$this->assertTrue($dbsh->close());
137
-			$this->assertNull($dbsh->read('foo'));
138
-			$this->assertTrue($dbsh->write('foo', '444'));
139
-			$this->assertNotEmpty($dbsh->read('foo'));
140
-			$this->assertEquals($dbsh->read('foo'), '444');
141
-			//put it in expired
142
-			$this->model->update('foo', array('s_time' => 1234567));
143
-			
144
-			$this->assertNull($dbsh->read('foo'));
145
-			$this->assertTrue($dbsh->write('foo', '444'));
146
-			
147
-			//do update of existing data
148
-			$this->assertTrue($dbsh->write('foo', '445'));
149
-			$this->assertEquals($dbsh->read('foo'), '445');	
150
-			$this->assertTrue($dbsh->destroy('foo'));
151
-			$this->assertNull($dbsh->read('foo'));
152
-			$this->assertTrue($dbsh->gc(13));
153
-			$encoded = $dbsh->encode('foo');
154
-			$this->assertNotEmpty($encoded);
155
-			$this->assertEquals($dbsh->decode($encoded), 'foo');
156
-		}
157
-		
158
-		public function testUsingCustomLoaderInstance(){
159
-			$dbsh = new DBSessionHandler($this->model, null, new Loader());
160
-			$dbsh->setSessionSecret($this->secret);
161
-			
162
-			$this->assertTrue($dbsh->open(null, null));
163
-			$this->assertTrue($dbsh->close());
164
-			$this->assertNull($dbsh->read('foo'));
165
-			$this->assertTrue($dbsh->write('foo', '444'));
166
-			$this->assertNotEmpty($dbsh->read('foo'));
167
-			$this->assertEquals($dbsh->read('foo'), '444');
168
-			//put it in expired
169
-			$this->model->update('foo', array('s_time' => 1234567));
170
-			
171
-			$this->assertNull($dbsh->read('foo'));
172
-			$this->assertTrue($dbsh->write('foo', '444'));
173
-			
174
-			//do update of existing data
175
-			$this->assertTrue($dbsh->write('foo', '445'));
176
-			$this->assertEquals($dbsh->read('foo'), '445');	
177
-			$this->assertTrue($dbsh->destroy('foo'));
178
-			$this->assertNull($dbsh->read('foo'));
179
-			$this->assertTrue($dbsh->gc(13));
180
-			$encoded = $dbsh->encode('foo');
181
-			$this->assertNotEmpty($encoded);
182
-			$this->assertEquals($dbsh->decode($encoded), 'foo');
183
-		}
184
-		
185
-		
186
-		public function testWhenModelInsanceIsNotSet(){
187
-			$dbsh = new DBSessionHandler(null, null, new Loader());
188
-			$dbsh->setSessionSecret($this->secret);
189
-			
190
-			$this->assertTrue($dbsh->open(null, null));
191
-			$this->assertTrue($dbsh->close());
192
-			$this->assertNull($dbsh->read('foo'));
193
-			$this->assertTrue($dbsh->write('foo', '444'));
194
-			$this->assertNotEmpty($dbsh->read('foo'));
195
-			$this->assertEquals($dbsh->read('foo'), '444');
196
-			//put it in expired
197
-			$this->model->update('foo', array('s_time' => 1234567));
198
-			
199
-			$this->assertNull($dbsh->read('foo'));
200
-			$this->assertTrue($dbsh->write('foo', '444'));
201
-			
202
-			//do update of existing data
203
-			$this->assertTrue($dbsh->write('tnh', '445'));
204
-			$this->assertTrue($dbsh->write('foo', '445'));
205
-			$this->assertEquals($dbsh->read('foo'), '445');	
206
-			$this->assertTrue($dbsh->destroy('foo'));
207
-			$this->assertNull($dbsh->read('foo'));
208
-			$this->assertTrue($dbsh->gc(13));
209
-			$encoded = $dbsh->encode('foo');
210
-			$this->assertNotEmpty($encoded);
211
-			$this->assertEquals($dbsh->decode($encoded), 'foo');
212
-		}
213
-		
214
-		public function testWhenModelTableColumnsIsNotSet(){
215
-			//session table is empty
216
-			$this->model->setSessionTableColumns(array());
217
-			$dbsh = new DBSessionHandler($this->model);
218
-			$this->assertTrue($dbsh->open(null, null));
219
-		}
220
-		
221
-		
222
-	}
223 51
\ No newline at end of file
52
+        public function testUsingSessionConfiguration(){
53
+            //using value in the configuration
54
+            self::$config->set('session_save_path', 'DBSessionModel');
55
+            self::$config->set('session_secret', $this->secret);
56
+            $dbsh = new DBSessionHandler();
57
+            //assign Database instance manually
58
+            $o = &get_instance();
59
+            $o->database = $this->db;
60
+			
61
+            $this->assertTrue($dbsh->open(null, null));
62
+            $this->assertTrue($dbsh->close());
63
+            $this->assertNull($dbsh->read('foo'));
64
+            $this->assertTrue($dbsh->write('foo', '444'));
65
+            $this->assertNotEmpty($dbsh->read('foo'));
66
+            $this->assertEquals($dbsh->read('foo'), '444');
67
+            //do update of existing data
68
+            $this->assertTrue($dbsh->write('foo', '445'));
69
+            $this->assertEquals($dbsh->read('foo'), '445');	
70
+            $this->assertTrue($dbsh->destroy('foo'));
71
+            $this->assertNull($dbsh->read('foo'));
72
+            $this->assertTrue($dbsh->gc(13));
73
+            $encoded = $dbsh->encode('foo');
74
+            $this->assertNotEmpty($encoded);
75
+            $this->assertEquals($dbsh->decode($encoded), 'foo');
76
+        }
77
+		
78
+        public function testWhenDataIsExpired(){
79
+            $dbsh = new DBSessionHandler($this->model);
80
+            $dbsh->setSessionSecret($this->secret);
81
+			
82
+            $this->assertTrue($dbsh->open(null, null));
83
+            $this->assertTrue($dbsh->write('foo', '444'));
84
+            $this->assertNotEmpty($dbsh->read('foo'));
85
+            $this->assertEquals($dbsh->read('foo'), '444');
86
+            //put it in expired
87
+            $this->model->update('foo', array('s_time' => 1234567));
88
+            $this->assertNull($dbsh->read('foo'));
89
+        }
90
+		
91
+        public function testWhenDataAlreadyExistDoUpdate(){
92
+            $dbsh = new DBSessionHandler($this->model);
93
+            $dbsh->setSessionSecret($this->secret);
94
+			
95
+            $this->assertTrue($dbsh->open(null, null));
96
+            $this->assertTrue($dbsh->write('foo', '444'));
97
+            $this->assertNotEmpty($dbsh->read('foo'));
98
+            $this->assertEquals($dbsh->read('foo'), '444');
99
+            //do update of existing data
100
+            $this->assertTrue($dbsh->write('foo', '445'));
101
+            $this->assertEquals($dbsh->read('foo'), '445');	
102
+        }
103
+		
104
+        public function testUsingCustomModelInstance(){
105
+            $dbsh = new DBSessionHandler($this->model);
106
+            $dbsh->setSessionSecret($this->secret);
107
+			
108
+            $this->assertTrue($dbsh->open(null, null));
109
+            $this->assertTrue($dbsh->close());
110
+            $this->assertNull($dbsh->read('foo'));
111
+            $this->assertTrue($dbsh->write('foo', '444'));
112
+            $this->assertNotEmpty($dbsh->read('foo'));
113
+            $this->assertEquals($dbsh->read('foo'), '444');
114
+            //put it in expired
115
+            $this->model->update('foo', array('s_time' => 1234567));
116
+			
117
+            $this->assertNull($dbsh->read('foo'));
118
+            $this->assertTrue($dbsh->write('foo', '444'));
119
+			
120
+            //do update of existing data
121
+            $this->assertTrue($dbsh->write('foo', '445'));
122
+            $this->assertEquals($dbsh->read('foo'), '445');	
123
+            $this->assertTrue($dbsh->destroy('foo'));
124
+            $this->assertNull($dbsh->read('foo'));
125
+            $this->assertTrue($dbsh->gc(13));
126
+            $encoded = $dbsh->encode('foo');
127
+            $this->assertNotEmpty($encoded);
128
+            $this->assertEquals($dbsh->decode($encoded), 'foo');
129
+        }
130
+			
131
+			
132
+        public function testUsingCustomLogInstance(){
133
+            $dbsh = new DBSessionHandler($this->model, new Log());
134
+            $dbsh->setSessionSecret($this->secret);
135
+			
136
+            $this->assertTrue($dbsh->open(null, null));
137
+            $this->assertTrue($dbsh->close());
138
+            $this->assertNull($dbsh->read('foo'));
139
+            $this->assertTrue($dbsh->write('foo', '444'));
140
+            $this->assertNotEmpty($dbsh->read('foo'));
141
+            $this->assertEquals($dbsh->read('foo'), '444');
142
+            //put it in expired
143
+            $this->model->update('foo', array('s_time' => 1234567));
144
+			
145
+            $this->assertNull($dbsh->read('foo'));
146
+            $this->assertTrue($dbsh->write('foo', '444'));
147
+			
148
+            //do update of existing data
149
+            $this->assertTrue($dbsh->write('foo', '445'));
150
+            $this->assertEquals($dbsh->read('foo'), '445');	
151
+            $this->assertTrue($dbsh->destroy('foo'));
152
+            $this->assertNull($dbsh->read('foo'));
153
+            $this->assertTrue($dbsh->gc(13));
154
+            $encoded = $dbsh->encode('foo');
155
+            $this->assertNotEmpty($encoded);
156
+            $this->assertEquals($dbsh->decode($encoded), 'foo');
157
+        }
158
+		
159
+        public function testUsingCustomLoaderInstance(){
160
+            $dbsh = new DBSessionHandler($this->model, null, new Loader());
161
+            $dbsh->setSessionSecret($this->secret);
162
+			
163
+            $this->assertTrue($dbsh->open(null, null));
164
+            $this->assertTrue($dbsh->close());
165
+            $this->assertNull($dbsh->read('foo'));
166
+            $this->assertTrue($dbsh->write('foo', '444'));
167
+            $this->assertNotEmpty($dbsh->read('foo'));
168
+            $this->assertEquals($dbsh->read('foo'), '444');
169
+            //put it in expired
170
+            $this->model->update('foo', array('s_time' => 1234567));
171
+			
172
+            $this->assertNull($dbsh->read('foo'));
173
+            $this->assertTrue($dbsh->write('foo', '444'));
174
+			
175
+            //do update of existing data
176
+            $this->assertTrue($dbsh->write('foo', '445'));
177
+            $this->assertEquals($dbsh->read('foo'), '445');	
178
+            $this->assertTrue($dbsh->destroy('foo'));
179
+            $this->assertNull($dbsh->read('foo'));
180
+            $this->assertTrue($dbsh->gc(13));
181
+            $encoded = $dbsh->encode('foo');
182
+            $this->assertNotEmpty($encoded);
183
+            $this->assertEquals($dbsh->decode($encoded), 'foo');
184
+        }
185
+		
186
+		
187
+        public function testWhenModelInsanceIsNotSet(){
188
+            $dbsh = new DBSessionHandler(null, null, new Loader());
189
+            $dbsh->setSessionSecret($this->secret);
190
+			
191
+            $this->assertTrue($dbsh->open(null, null));
192
+            $this->assertTrue($dbsh->close());
193
+            $this->assertNull($dbsh->read('foo'));
194
+            $this->assertTrue($dbsh->write('foo', '444'));
195
+            $this->assertNotEmpty($dbsh->read('foo'));
196
+            $this->assertEquals($dbsh->read('foo'), '444');
197
+            //put it in expired
198
+            $this->model->update('foo', array('s_time' => 1234567));
199
+			
200
+            $this->assertNull($dbsh->read('foo'));
201
+            $this->assertTrue($dbsh->write('foo', '444'));
202
+			
203
+            //do update of existing data
204
+            $this->assertTrue($dbsh->write('tnh', '445'));
205
+            $this->assertTrue($dbsh->write('foo', '445'));
206
+            $this->assertEquals($dbsh->read('foo'), '445');	
207
+            $this->assertTrue($dbsh->destroy('foo'));
208
+            $this->assertNull($dbsh->read('foo'));
209
+            $this->assertTrue($dbsh->gc(13));
210
+            $encoded = $dbsh->encode('foo');
211
+            $this->assertNotEmpty($encoded);
212
+            $this->assertEquals($dbsh->decode($encoded), 'foo');
213
+        }
214
+		
215
+        public function testWhenModelTableColumnsIsNotSet(){
216
+            //session table is empty
217
+            $this->model->setSessionTableColumns(array());
218
+            $dbsh = new DBSessionHandler($this->model);
219
+            $this->assertTrue($dbsh->open(null, null));
220
+        }
221
+		
222
+		
223
+    }
224 224
\ No newline at end of file
Please login to merge, or discard this patch.
core/classes/Config.php 1 patch
Indentation   +175 added lines, -175 removed lines patch added patch discarded remove patch
@@ -1,190 +1,190 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') || exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
2
+    defined('ROOT_PATH') || exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26 26
 
27
-	class Config{
27
+    class Config{
28 28
 		
29
-		/**
30
-		 * The list of loaded configuration
31
-		 * @var array
32
-		 */
33
-		private static $config = array();
29
+        /**
30
+         * The list of loaded configuration
31
+         * @var array
32
+         */
33
+        private static $config = array();
34 34
 
35
-		/**
36
-		 * The logger instance
37
-		 * @var object
38
-		 */
39
-		private static $logger;
35
+        /**
36
+         * The logger instance
37
+         * @var object
38
+         */
39
+        private static $logger;
40 40
 
41
-		/**
42
-		 * The signleton of the logger
43
-		 * @return Object the Log instance
44
-		 */
45
-		private static function getLogger(){
46
-			if(self::$logger == null){
47
-				$logger = array();
48
-				$logger[0] =& class_loader('Log', 'classes');
49
-				$logger[0]->setLogger('Library::Config');
50
-				self::$logger = $logger[0];
51
-			}
52
-			return self::$logger;			
53
-		}
41
+        /**
42
+         * The signleton of the logger
43
+         * @return Object the Log instance
44
+         */
45
+        private static function getLogger(){
46
+            if(self::$logger == null){
47
+                $logger = array();
48
+                $logger[0] =& class_loader('Log', 'classes');
49
+                $logger[0]->setLogger('Library::Config');
50
+                self::$logger = $logger[0];
51
+            }
52
+            return self::$logger;			
53
+        }
54 54
 
55
-		/**
56
-		 * Set the log instance for future use
57
-		 * @param object $logger the log object
58
-		 * @return object the log instance
59
-		 */
60
-		public static function setLogger($logger){
61
-			self::$logger = $logger;
62
-			return self::$logger;
63
-		}
55
+        /**
56
+         * Set the log instance for future use
57
+         * @param object $logger the log object
58
+         * @return object the log instance
59
+         */
60
+        public static function setLogger($logger){
61
+            self::$logger = $logger;
62
+            return self::$logger;
63
+        }
64 64
 
65
-		/**
66
-		 * Initialize the configuration by loading all the configuration from config file
67
-		 */
68
-		public static function init(){
69
-			$logger = static::getLogger();
70
-			$logger->debug('Initialization of the configuration');
71
-			self::$config = & load_configurations();
72
-			self::setBaseUrlUsingServerVar();
73
-			if(ENVIRONMENT == 'production' && in_array(strtolower(self::$config['log_level']), array('debug', 'info','all'))){
74
-				$logger->warning('You are in production environment, please set log level to WARNING, ERROR, FATAL to increase the application performance');
75
-			}
76
-			$logger->info('Configuration initialized successfully');
77
-			$logger->info('The application configuration are listed below: ' . stringfy_vars(self::$config));
78
-		}
65
+        /**
66
+         * Initialize the configuration by loading all the configuration from config file
67
+         */
68
+        public static function init(){
69
+            $logger = static::getLogger();
70
+            $logger->debug('Initialization of the configuration');
71
+            self::$config = & load_configurations();
72
+            self::setBaseUrlUsingServerVar();
73
+            if(ENVIRONMENT == 'production' && in_array(strtolower(self::$config['log_level']), array('debug', 'info','all'))){
74
+                $logger->warning('You are in production environment, please set log level to WARNING, ERROR, FATAL to increase the application performance');
75
+            }
76
+            $logger->info('Configuration initialized successfully');
77
+            $logger->info('The application configuration are listed below: ' . stringfy_vars(self::$config));
78
+        }
79 79
 
80
-		/**
81
-		 * Get the configuration item value
82
-		 * @param  string $item    the configuration item name to get
83
-		 * @param  mixed $default the default value to use if can not find the config item in the list
84
-		 * @return mixed          the config value if exist or the default value
85
-		 */
86
-		public static function get($item, $default = null){
87
-			$logger = static::getLogger();
88
-			if(array_key_exists($item, self::$config)){
89
-				return self::$config[$item];
90
-			}
91
-			$logger->warning('Cannot find config item ['.$item.'] using the default value ['.$default.']');
92
-			return $default;
93
-		}
80
+        /**
81
+         * Get the configuration item value
82
+         * @param  string $item    the configuration item name to get
83
+         * @param  mixed $default the default value to use if can not find the config item in the list
84
+         * @return mixed          the config value if exist or the default value
85
+         */
86
+        public static function get($item, $default = null){
87
+            $logger = static::getLogger();
88
+            if(array_key_exists($item, self::$config)){
89
+                return self::$config[$item];
90
+            }
91
+            $logger->warning('Cannot find config item ['.$item.'] using the default value ['.$default.']');
92
+            return $default;
93
+        }
94 94
 
95
-		/**
96
-		 * Set the configuration item value
97
-		 * @param string $item  the config item name to set
98
-		 * @param mixed $value the config item value
99
-		 */
100
-		public static function set($item, $value){
101
-			self::$config[$item] = $value;
102
-		}
95
+        /**
96
+         * Set the configuration item value
97
+         * @param string $item  the config item name to set
98
+         * @param mixed $value the config item value
99
+         */
100
+        public static function set($item, $value){
101
+            self::$config[$item] = $value;
102
+        }
103 103
 
104
-		/**
105
-		 * Get all the configuration values
106
-		 * @return array the config values
107
-		 */
108
-		public static function getAll(){
109
-			return self::$config;
110
-		}
104
+        /**
105
+         * Get all the configuration values
106
+         * @return array the config values
107
+         */
108
+        public static function getAll(){
109
+            return self::$config;
110
+        }
111 111
 
112
-		/**
113
-		 * Set the configuration values bu merged with the existing configuration
114
-		 * @param array $config the config values to add in the configuration list
115
-		 */
116
-		public static function setAll(array $config = array()){
117
-			self::$config = array_merge(self::$config, $config);
118
-		}
112
+        /**
113
+         * Set the configuration values bu merged with the existing configuration
114
+         * @param array $config the config values to add in the configuration list
115
+         */
116
+        public static function setAll(array $config = array()){
117
+            self::$config = array_merge(self::$config, $config);
118
+        }
119 119
 
120
-		/**
121
-		 * Delete the configuration item in the list
122
-		 * @param  string $item the config item name to be deleted
123
-		 * @return boolean true if the item exists and is deleted successfully otherwise will return false.
124
-		 */
125
-		public static function delete($item){
126
-			$logger = static::getLogger();
127
-			if(array_key_exists($item, self::$config)){
128
-				$logger->info('Delete config item ['.$item.']');
129
-				unset(self::$config[$item]);
130
-				return true;
131
-			}
132
-			else{
133
-				$logger->warning('Config item ['.$item.'] to be deleted does not exists');
134
-				return false;
135
-			}
136
-		}
120
+        /**
121
+         * Delete the configuration item in the list
122
+         * @param  string $item the config item name to be deleted
123
+         * @return boolean true if the item exists and is deleted successfully otherwise will return false.
124
+         */
125
+        public static function delete($item){
126
+            $logger = static::getLogger();
127
+            if(array_key_exists($item, self::$config)){
128
+                $logger->info('Delete config item ['.$item.']');
129
+                unset(self::$config[$item]);
130
+                return true;
131
+            }
132
+            else{
133
+                $logger->warning('Config item ['.$item.'] to be deleted does not exists');
134
+                return false;
135
+            }
136
+        }
137 137
 
138
-		/**
139
-		 * Load the configuration file. This an alias to Loader::config()
140
-		 * @param  string $config the config name to be loaded
141
-		 */
142
-		public static function load($config){
143
-			Loader::config($config);
144
-		}
138
+        /**
139
+         * Load the configuration file. This an alias to Loader::config()
140
+         * @param  string $config the config name to be loaded
141
+         */
142
+        public static function load($config){
143
+            Loader::config($config);
144
+        }
145 145
 
146
-		/**
147
-		 * Set the configuration for "base_url" if is not set in the configuration
148
-		 */
149
-		private static function setBaseUrlUsingServerVar(){
150
-			$logger = static::getLogger();
151
-			if (! isset(self::$config['base_url']) || ! is_url(self::$config['base_url'])){
152
-				if(ENVIRONMENT == 'production'){
153
-					$logger->warning('Application base URL is not set or invalid, please set application base URL to increase the application loading time');
154
-				}
155
-				$baseUrl = null;
156
-				$protocol = 'http';
157
-				if(is_https()){
158
-					$protocol = 'https';
159
-				}
160
-				$protocol .='://';
146
+        /**
147
+         * Set the configuration for "base_url" if is not set in the configuration
148
+         */
149
+        private static function setBaseUrlUsingServerVar(){
150
+            $logger = static::getLogger();
151
+            if (! isset(self::$config['base_url']) || ! is_url(self::$config['base_url'])){
152
+                if(ENVIRONMENT == 'production'){
153
+                    $logger->warning('Application base URL is not set or invalid, please set application base URL to increase the application loading time');
154
+                }
155
+                $baseUrl = null;
156
+                $protocol = 'http';
157
+                if(is_https()){
158
+                    $protocol = 'https';
159
+                }
160
+                $protocol .='://';
161 161
 
162
-				if (isset($_SERVER['SERVER_ADDR'])){
163
-					$baseUrl = $_SERVER['SERVER_ADDR'];
164
-					//check if the server is running under IPv6
165
-					if (strpos($_SERVER['SERVER_ADDR'], ':') !== FALSE){
166
-						$baseUrl = '['.$_SERVER['SERVER_ADDR'].']';
167
-					}
168
-					$serverPort = 80;
169
-					if (isset($_SERVER['SERVER_PORT'])) {
170
-						$serverPort = $_SERVER['SERVER_PORT'];
171
-					}
172
-					$port = '';
173
-					if($serverPort && ((is_https() && $serverPort != 443) || (!is_https() && $serverPort != 80))){
174
-						$port = ':'.$serverPort;
175
-					}
176
-					$baseUrl = $protocol . $baseUrl . $port . substr(
177
-																		$_SERVER['SCRIPT_NAME'], 
178
-																		0, 
179
-																		strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME']))
180
-																	);
181
-				}
182
-				else{
183
-					$logger->warning('Can not determine the application base URL automatically, use http://localhost as default');
184
-					$baseUrl = 'http://localhost/';
185
-				}
186
-				self::set('base_url', $baseUrl);
187
-			}
188
-			self::$config['base_url'] = rtrim(self::$config['base_url'], '/') .'/';
189
-		}
190
-	}
162
+                if (isset($_SERVER['SERVER_ADDR'])){
163
+                    $baseUrl = $_SERVER['SERVER_ADDR'];
164
+                    //check if the server is running under IPv6
165
+                    if (strpos($_SERVER['SERVER_ADDR'], ':') !== FALSE){
166
+                        $baseUrl = '['.$_SERVER['SERVER_ADDR'].']';
167
+                    }
168
+                    $serverPort = 80;
169
+                    if (isset($_SERVER['SERVER_PORT'])) {
170
+                        $serverPort = $_SERVER['SERVER_PORT'];
171
+                    }
172
+                    $port = '';
173
+                    if($serverPort && ((is_https() && $serverPort != 443) || (!is_https() && $serverPort != 80))){
174
+                        $port = ':'.$serverPort;
175
+                    }
176
+                    $baseUrl = $protocol . $baseUrl . $port . substr(
177
+                                                                        $_SERVER['SCRIPT_NAME'], 
178
+                                                                        0, 
179
+                                                                        strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME']))
180
+                                                                    );
181
+                }
182
+                else{
183
+                    $logger->warning('Can not determine the application base URL automatically, use http://localhost as default');
184
+                    $baseUrl = 'http://localhost/';
185
+                }
186
+                self::set('base_url', $baseUrl);
187
+            }
188
+            self::$config['base_url'] = rtrim(self::$config['base_url'], '/') .'/';
189
+        }
190
+    }
Please login to merge, or discard this patch.
core/classes/Loader.php 1 patch
Indentation   +622 added lines, -622 removed lines patch added patch discarded remove patch
@@ -1,660 +1,660 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') || exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
26
-	class Loader{
2
+    defined('ROOT_PATH') || exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26
+    class Loader{
27 27
 		
28
-		/**
29
-		 * List of loaded resources
30
-		 * @var array
31
-		 */
32
-		public static $loaded = array();
28
+        /**
29
+         * List of loaded resources
30
+         * @var array
31
+         */
32
+        public static $loaded = array();
33 33
 		
34
-		/**
35
-		 * The logger instance
36
-		 * @var object
37
-		 */
38
-		private static $logger;
34
+        /**
35
+         * The logger instance
36
+         * @var object
37
+         */
38
+        private static $logger;
39 39
 
40 40
 
41
-		public function __construct(){
42
-			//add the resources already loaded during application bootstrap
43
-			//in the list to prevent duplicate or loading the resources again.
44
-			static::$loaded = class_loaded();
41
+        public function __construct(){
42
+            //add the resources already loaded during application bootstrap
43
+            //in the list to prevent duplicate or loading the resources again.
44
+            static::$loaded = class_loaded();
45 45
 			
46
-			//Load resources from autoload configuration
47
-			$this->loadResourcesFromAutoloadConfig();
48
-		}
46
+            //Load resources from autoload configuration
47
+            $this->loadResourcesFromAutoloadConfig();
48
+        }
49 49
 
50
-		/**
51
-		 * The signleton of the logger
52
-		 * @return object the Log instance
53
-		 */
54
-		private static function getLogger(){
55
-			if(self::$logger == null){
56
-				$logger = array();
57
-				$logger[0] =& class_loader('Log', 'classes');
58
-				$logger[0]->setLogger('Library::Loader');
59
-				self::$logger = $logger[0];
60
-			}
61
-			return self::$logger;			
62
-		}
50
+        /**
51
+         * The signleton of the logger
52
+         * @return object the Log instance
53
+         */
54
+        private static function getLogger(){
55
+            if(self::$logger == null){
56
+                $logger = array();
57
+                $logger[0] =& class_loader('Log', 'classes');
58
+                $logger[0]->setLogger('Library::Loader');
59
+                self::$logger = $logger[0];
60
+            }
61
+            return self::$logger;			
62
+        }
63 63
 
64
-		/**
65
-		 * Set the log instance for future use
66
-		 * @param object $logger the log object
67
-		 * @return object the log instance
68
-		 */
69
-		public static function setLogger($logger){
70
-			self::$logger = $logger;
71
-			return self::$logger;
72
-		}
64
+        /**
65
+         * Set the log instance for future use
66
+         * @param object $logger the log object
67
+         * @return object the log instance
68
+         */
69
+        public static function setLogger($logger){
70
+            self::$logger = $logger;
71
+            return self::$logger;
72
+        }
73 73
 
74 74
 		
75
-		/**
76
-		 * Load the model class
77
-		 *
78
-		 * @param  string $class    the class name to be loaded
79
-		 * @param  string $instance the name of the instance to use in super object
80
-		 *
81
-		 * @return void
82
-		 */
83
-		public static function model($class, $instance = null){
84
-			$logger = static::getLogger();
85
-			$class = str_ireplace('.php', '', $class);
86
-			$class = trim($class, '/\\');
87
-			$file = ucfirst($class).'.php';
88
-			$logger->debug('Loading model [' . $class . '] ...');
89
-			//************
90
-			if (! $instance){
91
-				$instance = self::getModelLibraryInstanceName($class);
92
-			}
93
-			//****************
94
-			if (isset(static::$loaded[$instance])){
95
-				$logger->info('Model [' . $class . '] already loaded no need to load it again, cost in performance');
96
-				return;
97
-			}
98
-			$classFilePath = APPS_MODEL_PATH . $file;
99
-			//first check if this model is in the module
100
-			$logger->debug('Checking model [' . $class . '] from module list ...');
101
-			//check if the request class contains module name
102
-			$moduleInfo = self::getModuleInfoForModelLibrary($class);
103
-			$module = $moduleInfo['module'];
104
-			$class  = $moduleInfo['class'];
75
+        /**
76
+         * Load the model class
77
+         *
78
+         * @param  string $class    the class name to be loaded
79
+         * @param  string $instance the name of the instance to use in super object
80
+         *
81
+         * @return void
82
+         */
83
+        public static function model($class, $instance = null){
84
+            $logger = static::getLogger();
85
+            $class = str_ireplace('.php', '', $class);
86
+            $class = trim($class, '/\\');
87
+            $file = ucfirst($class).'.php';
88
+            $logger->debug('Loading model [' . $class . '] ...');
89
+            //************
90
+            if (! $instance){
91
+                $instance = self::getModelLibraryInstanceName($class);
92
+            }
93
+            //****************
94
+            if (isset(static::$loaded[$instance])){
95
+                $logger->info('Model [' . $class . '] already loaded no need to load it again, cost in performance');
96
+                return;
97
+            }
98
+            $classFilePath = APPS_MODEL_PATH . $file;
99
+            //first check if this model is in the module
100
+            $logger->debug('Checking model [' . $class . '] from module list ...');
101
+            //check if the request class contains module name
102
+            $moduleInfo = self::getModuleInfoForModelLibrary($class);
103
+            $module = $moduleInfo['module'];
104
+            $class  = $moduleInfo['class'];
105 105
 			
106
-			$moduleModelFilePath = Module::findModelFullPath($class, $module);
107
-			if ($moduleModelFilePath){
108
-				$logger->info('Found model [' . $class . '] from module [' .$module. '], the file path is [' .$moduleModelFilePath. '] we will used it');
109
-				$classFilePath = $moduleModelFilePath;
110
-			}
111
-			else{
112
-				$logger->info('Cannot find model [' . $class . '] from modules using the default location');
113
-			}
114
-			$logger->info('The model file path to be loaded is [' . $classFilePath . ']');
115
-			if (file_exists($classFilePath)){
116
-				require_once $classFilePath;
117
-				if (class_exists($class)){
118
-					$c = new $class();
119
-					$obj = & get_instance();
120
-					$obj->{$instance} = $c;
121
-					static::$loaded[$instance] = $class;
122
-					$logger->info('Model [' . $class . '] --> ' . $classFilePath . ' loaded successfully.');
123
-				}
124
-				else{
125
-					show_error('The file '.$classFilePath.' exists but does not contain the class ['. $class . ']');
126
-				}
127
-			}
128
-			else{
129
-				show_error('Unable to find the model [' . $class . ']');
130
-			}
131
-		}
106
+            $moduleModelFilePath = Module::findModelFullPath($class, $module);
107
+            if ($moduleModelFilePath){
108
+                $logger->info('Found model [' . $class . '] from module [' .$module. '], the file path is [' .$moduleModelFilePath. '] we will used it');
109
+                $classFilePath = $moduleModelFilePath;
110
+            }
111
+            else{
112
+                $logger->info('Cannot find model [' . $class . '] from modules using the default location');
113
+            }
114
+            $logger->info('The model file path to be loaded is [' . $classFilePath . ']');
115
+            if (file_exists($classFilePath)){
116
+                require_once $classFilePath;
117
+                if (class_exists($class)){
118
+                    $c = new $class();
119
+                    $obj = & get_instance();
120
+                    $obj->{$instance} = $c;
121
+                    static::$loaded[$instance] = $class;
122
+                    $logger->info('Model [' . $class . '] --> ' . $classFilePath . ' loaded successfully.');
123
+                }
124
+                else{
125
+                    show_error('The file '.$classFilePath.' exists but does not contain the class ['. $class . ']');
126
+                }
127
+            }
128
+            else{
129
+                show_error('Unable to find the model [' . $class . ']');
130
+            }
131
+        }
132 132
 
133 133
 		
134
-		/**
135
-		 * Load the library class
136
-		 *
137
-		 * @param  string $class    the library class name to be loaded
138
-		 * @param  string $instance the instance name to use in super object
139
-		 * @param mixed $params the arguments to pass to the constructor
140
-		 *
141
-		 * @return void
142
-		 */
143
-		public static function library($class, $instance = null, array $params = array()){
144
-			$logger = static::getLogger();
145
-			$class = str_ireplace('.php', '', $class);
146
-			$class = trim($class, '/\\');
147
-			$file = ucfirst($class) .'.php';
148
-			$logger->debug('Loading library [' . $class . '] ...');
149
-			if (! $instance){
150
-				$instance = self::getModelLibraryInstanceName($class);
151
-			}
152
-			if (isset(static::$loaded[$instance])){
153
-				$logger->info('Library [' . $class . '] already loaded no need to load it again, cost in performance');
154
-				return;
155
-			}
156
-			$obj = & get_instance();
157
-			//Check and load Database library
158
-			if (strtolower($class) == 'database'){
159
-				$logger->info('This is the Database library ...');
160
-				$obj->{$instance} = & class_loader('Database', 'classes/database', $params);
161
-				static::$loaded[$instance] = $class;
162
-				$logger->info('Library Database loaded successfully.');
163
-				return;
164
-			}
165
-			$libraryFilePath = null;
166
-			$logger->debug('Check if this is a system library ...');
167
-			if (file_exists(CORE_LIBRARY_PATH . $file)){
168
-				$libraryFilePath = CORE_LIBRARY_PATH . $file;
169
-				$class = ucfirst($class);
170
-				$logger->info('This library is a system library');
171
-			}
172
-			else{
173
-				$logger->info('This library is not a system library');	
174
-				//first check if this library is in the module
175
-				$libraryFilePath = self::getLibraryPathUsingModuleInfo($class);
176
-				//***************
177
-			}
178
-			if (! $libraryFilePath && file_exists(LIBRARY_PATH . $file)){
179
-				$libraryFilePath = LIBRARY_PATH . $file;
180
-			}
181
-			$logger->info('The library file path to be loaded is [' . $libraryFilePath . ']');
182
-			//*************************
183
-			self::loadLibrary($libraryFilePath, $class, $instance, $params);
184
-		}
134
+        /**
135
+         * Load the library class
136
+         *
137
+         * @param  string $class    the library class name to be loaded
138
+         * @param  string $instance the instance name to use in super object
139
+         * @param mixed $params the arguments to pass to the constructor
140
+         *
141
+         * @return void
142
+         */
143
+        public static function library($class, $instance = null, array $params = array()){
144
+            $logger = static::getLogger();
145
+            $class = str_ireplace('.php', '', $class);
146
+            $class = trim($class, '/\\');
147
+            $file = ucfirst($class) .'.php';
148
+            $logger->debug('Loading library [' . $class . '] ...');
149
+            if (! $instance){
150
+                $instance = self::getModelLibraryInstanceName($class);
151
+            }
152
+            if (isset(static::$loaded[$instance])){
153
+                $logger->info('Library [' . $class . '] already loaded no need to load it again, cost in performance');
154
+                return;
155
+            }
156
+            $obj = & get_instance();
157
+            //Check and load Database library
158
+            if (strtolower($class) == 'database'){
159
+                $logger->info('This is the Database library ...');
160
+                $obj->{$instance} = & class_loader('Database', 'classes/database', $params);
161
+                static::$loaded[$instance] = $class;
162
+                $logger->info('Library Database loaded successfully.');
163
+                return;
164
+            }
165
+            $libraryFilePath = null;
166
+            $logger->debug('Check if this is a system library ...');
167
+            if (file_exists(CORE_LIBRARY_PATH . $file)){
168
+                $libraryFilePath = CORE_LIBRARY_PATH . $file;
169
+                $class = ucfirst($class);
170
+                $logger->info('This library is a system library');
171
+            }
172
+            else{
173
+                $logger->info('This library is not a system library');	
174
+                //first check if this library is in the module
175
+                $libraryFilePath = self::getLibraryPathUsingModuleInfo($class);
176
+                //***************
177
+            }
178
+            if (! $libraryFilePath && file_exists(LIBRARY_PATH . $file)){
179
+                $libraryFilePath = LIBRARY_PATH . $file;
180
+            }
181
+            $logger->info('The library file path to be loaded is [' . $libraryFilePath . ']');
182
+            //*************************
183
+            self::loadLibrary($libraryFilePath, $class, $instance, $params);
184
+        }
185 185
 
186
-		/**
187
-		 * Load the helper
188
-		 *
189
-		 * @param  string $function the helper name to be loaded
190
-		 *
191
-		 * @return void
192
-		 */
193
-		public static function functions($function){
194
-			$logger = static::getLogger();
195
-			$function = str_ireplace('.php', '', $function);
196
-			$function = trim($function, '/\\');
197
-			$function = str_ireplace('function_', '', $function);
198
-			$file = 'function_'.$function.'.php';
199
-			$logger->debug('Loading helper [' . $function . '] ...');
200
-			if (isset(static::$loaded['function_' . $function])){
201
-				$logger->info('Helper [' . $function . '] already loaded no need to load it again, cost in performance');
202
-				return;
203
-			}
204
-			$functionFilePath = null;
205
-			//first check if this helper is in the module
206
-			$logger->debug('Checking helper [' . $function . '] from module list ...');
207
-			$moduleInfo = self::getModuleInfoForFunction($function);
208
-			$module    = $moduleInfo['module'];
209
-			$function  = $moduleInfo['function'];
210
-			if(! empty($moduleInfo['file'])){
211
-				$file = $moduleInfo['file'];
212
-			}
213
-			$moduleFunctionPath = Module::findFunctionFullPath($function, $module);
214
-			if ($moduleFunctionPath){
215
-				$logger->info('Found helper [' . $function . '] from module [' .$module. '], the file path is [' .$moduleFunctionPath. '] we will used it');
216
-				$functionFilePath = $moduleFunctionPath;
217
-			}
218
-			else{
219
-				$logger->info('Cannot find helper [' . $function . '] from modules using the default location');
220
-			}
221
-			if (! $functionFilePath){
222
-				$searchDir = array(FUNCTIONS_PATH, CORE_FUNCTIONS_PATH);
223
-				foreach($searchDir as $dir){
224
-					$filePath = $dir . $file;
225
-					if (file_exists($filePath)){
226
-						$functionFilePath = $filePath;
227
-						//is already found not to continue
228
-						break;
229
-					}
230
-				}
231
-			}
232
-			$logger->info('The helper file path to be loaded is [' . $functionFilePath . ']');
233
-			if ($functionFilePath){
234
-				require_once $functionFilePath;
235
-				static::$loaded['function_' . $function] = $functionFilePath;
236
-				$logger->info('Helper [' . $function . '] --> ' . $functionFilePath . ' loaded successfully.');
237
-			}
238
-			else{
239
-				show_error('Unable to find helper file [' . $file . ']');
240
-			}
241
-		}
186
+        /**
187
+         * Load the helper
188
+         *
189
+         * @param  string $function the helper name to be loaded
190
+         *
191
+         * @return void
192
+         */
193
+        public static function functions($function){
194
+            $logger = static::getLogger();
195
+            $function = str_ireplace('.php', '', $function);
196
+            $function = trim($function, '/\\');
197
+            $function = str_ireplace('function_', '', $function);
198
+            $file = 'function_'.$function.'.php';
199
+            $logger->debug('Loading helper [' . $function . '] ...');
200
+            if (isset(static::$loaded['function_' . $function])){
201
+                $logger->info('Helper [' . $function . '] already loaded no need to load it again, cost in performance');
202
+                return;
203
+            }
204
+            $functionFilePath = null;
205
+            //first check if this helper is in the module
206
+            $logger->debug('Checking helper [' . $function . '] from module list ...');
207
+            $moduleInfo = self::getModuleInfoForFunction($function);
208
+            $module    = $moduleInfo['module'];
209
+            $function  = $moduleInfo['function'];
210
+            if(! empty($moduleInfo['file'])){
211
+                $file = $moduleInfo['file'];
212
+            }
213
+            $moduleFunctionPath = Module::findFunctionFullPath($function, $module);
214
+            if ($moduleFunctionPath){
215
+                $logger->info('Found helper [' . $function . '] from module [' .$module. '], the file path is [' .$moduleFunctionPath. '] we will used it');
216
+                $functionFilePath = $moduleFunctionPath;
217
+            }
218
+            else{
219
+                $logger->info('Cannot find helper [' . $function . '] from modules using the default location');
220
+            }
221
+            if (! $functionFilePath){
222
+                $searchDir = array(FUNCTIONS_PATH, CORE_FUNCTIONS_PATH);
223
+                foreach($searchDir as $dir){
224
+                    $filePath = $dir . $file;
225
+                    if (file_exists($filePath)){
226
+                        $functionFilePath = $filePath;
227
+                        //is already found not to continue
228
+                        break;
229
+                    }
230
+                }
231
+            }
232
+            $logger->info('The helper file path to be loaded is [' . $functionFilePath . ']');
233
+            if ($functionFilePath){
234
+                require_once $functionFilePath;
235
+                static::$loaded['function_' . $function] = $functionFilePath;
236
+                $logger->info('Helper [' . $function . '] --> ' . $functionFilePath . ' loaded successfully.');
237
+            }
238
+            else{
239
+                show_error('Unable to find helper file [' . $file . ']');
240
+            }
241
+        }
242 242
 
243
-		/**
244
-		 * Load the configuration file
245
-		 *
246
-		 * @param  string $filename the configuration filename located at CONFIG_PATH or MODULE_PATH/config
247
-		 *
248
-		 * @return void
249
-		 */
250
-		public static function config($filename){
251
-			$logger = static::getLogger();
252
-			$filename = str_ireplace('.php', '', $filename);
253
-			$filename = trim($filename, '/\\');
254
-			$filename = str_ireplace('config_', '', $filename);
255
-			$file = 'config_'.$filename.'.php';
256
-			$logger->debug('Loading configuration [' . $filename . '] ...');
257
-			if (isset(static::$loaded['config_' . $filename])){
258
-				$logger->info('Configuration [' . $file . '] already loaded no need to load it again, cost in performance');
259
-				return;
260
-			}
261
-			$configFilePath = CONFIG_PATH . $file;
262
-			//first check if this config is in the module
263
-			$logger->debug('Checking config [' . $filename . '] from module list ...');
264
-			$moduleInfo = self::getModuleInfoForConfig($filename);
265
-			$module    = $moduleInfo['module'];
266
-			$filename  = $moduleInfo['filename'];
267
-			$moduleConfigPath = Module::findConfigFullPath($filename, $module);
268
-			if ($moduleConfigPath){
269
-				$logger->info('Found config [' . $filename . '] from module [' .$module. '], the file path is [' .$moduleConfigPath. '] we will used it');
270
-				$configFilePath = $moduleConfigPath;
271
-			}
272
-			else{
273
-				$logger->info('Cannot find config [' . $filename . '] from modules using the default location');
274
-			}
275
-			$logger->info('The config file path to be loaded is [' . $configFilePath . ']');
276
-			$config = array();
277
-			if (file_exists($configFilePath)){
278
-				require_once $configFilePath;
279
-				if (! empty($config) && is_array($config)){
280
-					Config::setAll($config);
281
-					static::$loaded['config_' . $filename] = $configFilePath;
282
-					$logger->info('Configuration [' . $configFilePath . '] loaded successfully.');
283
-					$logger->info('The custom application configuration loaded are listed below: ' . stringfy_vars($config));
284
-					unset($config);
285
-				}
286
-			}
287
-			else{
288
-				show_error('Unable to find config file ['. $configFilePath . ']');
289
-			}
290
-		}
243
+        /**
244
+         * Load the configuration file
245
+         *
246
+         * @param  string $filename the configuration filename located at CONFIG_PATH or MODULE_PATH/config
247
+         *
248
+         * @return void
249
+         */
250
+        public static function config($filename){
251
+            $logger = static::getLogger();
252
+            $filename = str_ireplace('.php', '', $filename);
253
+            $filename = trim($filename, '/\\');
254
+            $filename = str_ireplace('config_', '', $filename);
255
+            $file = 'config_'.$filename.'.php';
256
+            $logger->debug('Loading configuration [' . $filename . '] ...');
257
+            if (isset(static::$loaded['config_' . $filename])){
258
+                $logger->info('Configuration [' . $file . '] already loaded no need to load it again, cost in performance');
259
+                return;
260
+            }
261
+            $configFilePath = CONFIG_PATH . $file;
262
+            //first check if this config is in the module
263
+            $logger->debug('Checking config [' . $filename . '] from module list ...');
264
+            $moduleInfo = self::getModuleInfoForConfig($filename);
265
+            $module    = $moduleInfo['module'];
266
+            $filename  = $moduleInfo['filename'];
267
+            $moduleConfigPath = Module::findConfigFullPath($filename, $module);
268
+            if ($moduleConfigPath){
269
+                $logger->info('Found config [' . $filename . '] from module [' .$module. '], the file path is [' .$moduleConfigPath. '] we will used it');
270
+                $configFilePath = $moduleConfigPath;
271
+            }
272
+            else{
273
+                $logger->info('Cannot find config [' . $filename . '] from modules using the default location');
274
+            }
275
+            $logger->info('The config file path to be loaded is [' . $configFilePath . ']');
276
+            $config = array();
277
+            if (file_exists($configFilePath)){
278
+                require_once $configFilePath;
279
+                if (! empty($config) && is_array($config)){
280
+                    Config::setAll($config);
281
+                    static::$loaded['config_' . $filename] = $configFilePath;
282
+                    $logger->info('Configuration [' . $configFilePath . '] loaded successfully.');
283
+                    $logger->info('The custom application configuration loaded are listed below: ' . stringfy_vars($config));
284
+                    unset($config);
285
+                }
286
+            }
287
+            else{
288
+                show_error('Unable to find config file ['. $configFilePath . ']');
289
+            }
290
+        }
291 291
 
292 292
 
293
-		/**
294
-		 * Load the language
295
-		 *
296
-		 * @param  string $language the language name to be loaded
297
-		 *
298
-		 * @return void
299
-		 */
300
-		public static function lang($language){
301
-			$logger = static::getLogger();
302
-			$language = str_ireplace('.php', '', $language);
303
-			$language = trim($language, '/\\');
304
-			$language = str_ireplace('lang_', '', $language);
305
-			$file = 'lang_'.$language.'.php';
306
-			$logger->debug('Loading language [' . $language . '] ...');
307
-			if (isset(static::$loaded['lang_' . $language])){
308
-				$logger->info('Language [' . $language . '] already loaded no need to load it again, cost in performance');
309
-				return;
310
-			}
311
-			//get the current language
312
-			$appLang = self::getAppLang();
313
-			$languageFilePath = null;
314
-			//first check if this language is in the module
315
-			$logger->debug('Checking language [' . $language . '] from module list ...');
316
-			$moduleInfo = self::getModuleInfoForLanguage($language);
317
-			$module    = $moduleInfo['module'];
318
-			$language  = $moduleInfo['language'];
319
-			if(! empty($moduleInfo['file'])){
320
-				$file = $moduleInfo['file'];
321
-			}
322
-			$moduleLanguagePath = Module::findLanguageFullPath($language, $module, $appLang);
323
-			if ($moduleLanguagePath){
324
-				$logger->info('Found language [' . $language . '] from module [' .$module. '], the file path is [' .$moduleLanguagePath. '] we will used it');
325
-				$languageFilePath = $moduleLanguagePath;
326
-			}
327
-			else{
328
-				$logger->info('Cannot find language [' . $language . '] from modules using the default location');
329
-			}
330
-			if (! $languageFilePath){
331
-				$searchDir = array(APP_LANG_PATH, CORE_LANG_PATH);
332
-				foreach($searchDir as $dir){
333
-					$filePath = $dir . $appLang . DS . $file;
334
-					if (file_exists($filePath)){
335
-						$languageFilePath = $filePath;
336
-						//already found no need continue
337
-						break;
338
-					}
339
-				}
340
-			}
341
-			$logger->info('The language file path to be loaded is [' . $languageFilePath . ']');
342
-			self::loadLanguage($languageFilePath, $language);
343
-		}
293
+        /**
294
+         * Load the language
295
+         *
296
+         * @param  string $language the language name to be loaded
297
+         *
298
+         * @return void
299
+         */
300
+        public static function lang($language){
301
+            $logger = static::getLogger();
302
+            $language = str_ireplace('.php', '', $language);
303
+            $language = trim($language, '/\\');
304
+            $language = str_ireplace('lang_', '', $language);
305
+            $file = 'lang_'.$language.'.php';
306
+            $logger->debug('Loading language [' . $language . '] ...');
307
+            if (isset(static::$loaded['lang_' . $language])){
308
+                $logger->info('Language [' . $language . '] already loaded no need to load it again, cost in performance');
309
+                return;
310
+            }
311
+            //get the current language
312
+            $appLang = self::getAppLang();
313
+            $languageFilePath = null;
314
+            //first check if this language is in the module
315
+            $logger->debug('Checking language [' . $language . '] from module list ...');
316
+            $moduleInfo = self::getModuleInfoForLanguage($language);
317
+            $module    = $moduleInfo['module'];
318
+            $language  = $moduleInfo['language'];
319
+            if(! empty($moduleInfo['file'])){
320
+                $file = $moduleInfo['file'];
321
+            }
322
+            $moduleLanguagePath = Module::findLanguageFullPath($language, $module, $appLang);
323
+            if ($moduleLanguagePath){
324
+                $logger->info('Found language [' . $language . '] from module [' .$module. '], the file path is [' .$moduleLanguagePath. '] we will used it');
325
+                $languageFilePath = $moduleLanguagePath;
326
+            }
327
+            else{
328
+                $logger->info('Cannot find language [' . $language . '] from modules using the default location');
329
+            }
330
+            if (! $languageFilePath){
331
+                $searchDir = array(APP_LANG_PATH, CORE_LANG_PATH);
332
+                foreach($searchDir as $dir){
333
+                    $filePath = $dir . $appLang . DS . $file;
334
+                    if (file_exists($filePath)){
335
+                        $languageFilePath = $filePath;
336
+                        //already found no need continue
337
+                        break;
338
+                    }
339
+                }
340
+            }
341
+            $logger->info('The language file path to be loaded is [' . $languageFilePath . ']');
342
+            self::loadLanguage($languageFilePath, $language);
343
+        }
344 344
 
345
-		/**
346
-		 * Return the current app language by default will use the value from cookie 
347
-		 * if can not found will use the default value from configuration
348
-		 * @return string the app language like "en", "fr"
349
-		 */
350
-		protected static function getAppLang(){
351
-			//determine the current language
352
-			$appLang = get_config('default_language');
353
-			//if the language exists in the cookie use it
354
-			$cfgKey = get_config('language_cookie_name');
355
-			$objCookie = & class_loader('Cookie');
356
-			$cookieLang = $objCookie->get($cfgKey);
357
-			if ($cookieLang){
358
-				$appLang = $cookieLang;
359
-			}
360
-			return $appLang;
361
-		}
362
-		/**
363
-		 * Get the module information for the model and library to load
364
-		 * @param  string $class the full class name like moduleName/className, className,
365
-		 * @return array        the module information
366
-		 * array(
367
-		 * 	'module'=> 'module_name'
368
-		 * 	'class' => 'class_name'
369
-		 * )
370
-		 */
371
-		protected static function getModuleInfoForModelLibrary($class){
372
-			$module = null;
373
-			$obj = & get_instance();
374
-			if (strpos($class, '/') !== false){
375
-				$path = explode('/', $class);
376
-				if (isset($path[0]) && in_array($path[0], Module::getModuleList())){
377
-					$module = $path[0];
378
-					$class = ucfirst($path[1]);
379
-				}
380
-			}
381
-			else{
382
-				$class = ucfirst($class);
383
-			}
384
-			if (! $module && !empty($obj->moduleName)){
385
-				$module = $obj->moduleName;
386
-			}
387
-			return array(
388
-						'class' => $class,
389
-						'module' => $module
390
-					);
391
-		}
345
+        /**
346
+         * Return the current app language by default will use the value from cookie 
347
+         * if can not found will use the default value from configuration
348
+         * @return string the app language like "en", "fr"
349
+         */
350
+        protected static function getAppLang(){
351
+            //determine the current language
352
+            $appLang = get_config('default_language');
353
+            //if the language exists in the cookie use it
354
+            $cfgKey = get_config('language_cookie_name');
355
+            $objCookie = & class_loader('Cookie');
356
+            $cookieLang = $objCookie->get($cfgKey);
357
+            if ($cookieLang){
358
+                $appLang = $cookieLang;
359
+            }
360
+            return $appLang;
361
+        }
362
+        /**
363
+         * Get the module information for the model and library to load
364
+         * @param  string $class the full class name like moduleName/className, className,
365
+         * @return array        the module information
366
+         * array(
367
+         * 	'module'=> 'module_name'
368
+         * 	'class' => 'class_name'
369
+         * )
370
+         */
371
+        protected static function getModuleInfoForModelLibrary($class){
372
+            $module = null;
373
+            $obj = & get_instance();
374
+            if (strpos($class, '/') !== false){
375
+                $path = explode('/', $class);
376
+                if (isset($path[0]) && in_array($path[0], Module::getModuleList())){
377
+                    $module = $path[0];
378
+                    $class = ucfirst($path[1]);
379
+                }
380
+            }
381
+            else{
382
+                $class = ucfirst($class);
383
+            }
384
+            if (! $module && !empty($obj->moduleName)){
385
+                $module = $obj->moduleName;
386
+            }
387
+            return array(
388
+                        'class' => $class,
389
+                        'module' => $module
390
+                    );
391
+        }
392 392
 
393
-		/**
394
-		 * Get the module information for the function to load
395
-		 * @param  string $function the function name like moduleName/functionName, functionName,
396
-		 * @return array        the module information
397
-		 * array(
398
-		 * 	'module'=> 'module_name'
399
-		 * 	'function' => 'function'
400
-		 * 	'file' => 'file'
401
-		 * )
402
-		 */
403
-		protected static function getModuleInfoForFunction($function){
404
-			$module = null;
405
-			$file = null;
406
-			$obj = & get_instance();
407
-			//check if the request class contains module name
408
-			if (strpos($function, '/') !== false){
409
-				$path = explode('/', $function);
410
-				if (isset($path[0]) && in_array($path[0], Module::getModuleList())){
411
-					$module = $path[0];
412
-					$function = 'function_' . $path[1];
413
-					$file = $path[0] . DS . $function.'.php';
414
-				}
415
-			}
416
-			if (! $module && !empty($obj->moduleName)){
417
-				$module = $obj->moduleName;
418
-			}
419
-			return array(
420
-						'function' => $function,
421
-						'module' => $module,
422
-						'file' => $file
423
-					);
424
-		}
393
+        /**
394
+         * Get the module information for the function to load
395
+         * @param  string $function the function name like moduleName/functionName, functionName,
396
+         * @return array        the module information
397
+         * array(
398
+         * 	'module'=> 'module_name'
399
+         * 	'function' => 'function'
400
+         * 	'file' => 'file'
401
+         * )
402
+         */
403
+        protected static function getModuleInfoForFunction($function){
404
+            $module = null;
405
+            $file = null;
406
+            $obj = & get_instance();
407
+            //check if the request class contains module name
408
+            if (strpos($function, '/') !== false){
409
+                $path = explode('/', $function);
410
+                if (isset($path[0]) && in_array($path[0], Module::getModuleList())){
411
+                    $module = $path[0];
412
+                    $function = 'function_' . $path[1];
413
+                    $file = $path[0] . DS . $function.'.php';
414
+                }
415
+            }
416
+            if (! $module && !empty($obj->moduleName)){
417
+                $module = $obj->moduleName;
418
+            }
419
+            return array(
420
+                        'function' => $function,
421
+                        'module' => $module,
422
+                        'file' => $file
423
+                    );
424
+        }
425 425
 
426
-		/**
427
-		 * Get the module information for the language to load
428
-		 * @param  string $language the language name like moduleName/languageName, languageName,
429
-		 * @return array        the module information
430
-		 * array(
431
-		 * 	'module'=> 'module_name'
432
-		 * 	'language' => 'language'
433
-		 * 	'file' => 'file'
434
-		 * )
435
-		 */
436
-		protected static function getModuleInfoForLanguage($language){
437
-			$module = null;
438
-			$file = null;
439
-			$obj = & get_instance();
440
-			//check if the request class contains module name
441
-			if (strpos($language, '/') !== false){
442
-				$path = explode('/', $language);
443
-				if (isset($path[0]) && in_array($path[0], Module::getModuleList())){
444
-					$module = $path[0];
445
-					$language = 'lang_' . $path[1] . '.php';
446
-					$file = $path[0] . DS .$language;
447
-				}
448
-			}
449
-			if (! $module && !empty($obj->moduleName)){
450
-				$module = $obj->moduleName;
451
-			}
452
-			return array(
453
-						'language' => $language,
454
-						'module' => $module,
455
-						'file' => $file
456
-					);
457
-		}
426
+        /**
427
+         * Get the module information for the language to load
428
+         * @param  string $language the language name like moduleName/languageName, languageName,
429
+         * @return array        the module information
430
+         * array(
431
+         * 	'module'=> 'module_name'
432
+         * 	'language' => 'language'
433
+         * 	'file' => 'file'
434
+         * )
435
+         */
436
+        protected static function getModuleInfoForLanguage($language){
437
+            $module = null;
438
+            $file = null;
439
+            $obj = & get_instance();
440
+            //check if the request class contains module name
441
+            if (strpos($language, '/') !== false){
442
+                $path = explode('/', $language);
443
+                if (isset($path[0]) && in_array($path[0], Module::getModuleList())){
444
+                    $module = $path[0];
445
+                    $language = 'lang_' . $path[1] . '.php';
446
+                    $file = $path[0] . DS .$language;
447
+                }
448
+            }
449
+            if (! $module && !empty($obj->moduleName)){
450
+                $module = $obj->moduleName;
451
+            }
452
+            return array(
453
+                        'language' => $language,
454
+                        'module' => $module,
455
+                        'file' => $file
456
+                    );
457
+        }
458 458
 
459 459
 
460
-		/**
461
-		 * Get the module information for the config to load
462
-		 * @param  string $filename the filename of the configuration file,
463
-		 * @return array        the module information
464
-		 * array(
465
-		 * 	'module'=> 'module_name'
466
-		 * 	'filename' => 'filename'
467
-		 * )
468
-		 */
469
-		protected static function getModuleInfoForConfig($filename){
470
-			$module = null;
471
-			$obj = & get_instance();
472
-			//check if the request class contains module name
473
-			if (strpos($filename, '/') !== false){
474
-				$path = explode('/', $filename);
475
-				if (isset($path[0]) && in_array($path[0], Module::getModuleList())){
476
-					$module = $path[0];
477
-					$filename = $path[1] . '.php';
478
-				}
479
-			}
480
-			if (! $module && !empty($obj->moduleName)){
481
-				$module = $obj->moduleName;
482
-			}
483
-			return array(
484
-						'filename' => $filename,
485
-						'module' => $module
486
-					);
487
-		}
460
+        /**
461
+         * Get the module information for the config to load
462
+         * @param  string $filename the filename of the configuration file,
463
+         * @return array        the module information
464
+         * array(
465
+         * 	'module'=> 'module_name'
466
+         * 	'filename' => 'filename'
467
+         * )
468
+         */
469
+        protected static function getModuleInfoForConfig($filename){
470
+            $module = null;
471
+            $obj = & get_instance();
472
+            //check if the request class contains module name
473
+            if (strpos($filename, '/') !== false){
474
+                $path = explode('/', $filename);
475
+                if (isset($path[0]) && in_array($path[0], Module::getModuleList())){
476
+                    $module = $path[0];
477
+                    $filename = $path[1] . '.php';
478
+                }
479
+            }
480
+            if (! $module && !empty($obj->moduleName)){
481
+                $module = $obj->moduleName;
482
+            }
483
+            return array(
484
+                        'filename' => $filename,
485
+                        'module' => $module
486
+                    );
487
+        }
488 488
 
489
-		/**
490
-		 * Get the name of model or library instance if is null
491
-		 * @param  string $class the class name to determine the instance
492
-		 * @return string        the instance name
493
-		 */
494
-		protected static function getModelLibraryInstanceName($class){
495
-			//for module
496
-			$instance = null;
497
-			if (strpos($class, '/') !== false){
498
-				$path = explode('/', $class);
499
-				if (isset($path[1])){
500
-					$instance = strtolower($path[1]);
501
-				}
502
-			}
503
-			else{
504
-				$instance = strtolower($class);
505
-			}
506
-			return $instance;
507
-		}
489
+        /**
490
+         * Get the name of model or library instance if is null
491
+         * @param  string $class the class name to determine the instance
492
+         * @return string        the instance name
493
+         */
494
+        protected static function getModelLibraryInstanceName($class){
495
+            //for module
496
+            $instance = null;
497
+            if (strpos($class, '/') !== false){
498
+                $path = explode('/', $class);
499
+                if (isset($path[1])){
500
+                    $instance = strtolower($path[1]);
501
+                }
502
+            }
503
+            else{
504
+                $instance = strtolower($class);
505
+            }
506
+            return $instance;
507
+        }
508 508
 
509
-		/**
510
-		 * Get the library file path using the module information
511
-		 * @param  string $class the class name
512
-		 * @return string|null        the library file path otherwise null will be returned
513
-		 */
514
-		protected static function getLibraryPathUsingModuleInfo($class){
515
-			$logger = static::getLogger();
516
-			$libraryFilePath = null;
517
-			$logger->debug('Checking library [' . $class . '] from module list ...');
518
-			$moduleInfo = self::getModuleInfoForModelLibrary($class);
519
-			$module = $moduleInfo['module'];
520
-			$class  = $moduleInfo['class'];
521
-			$moduleLibraryPath = Module::findLibraryFullPath($class, $module);
522
-			if ($moduleLibraryPath){
523
-				$logger->info('Found library [' . $class . '] from module [' .$module. '], the file path is [' .$moduleLibraryPath. '] we will used it');
524
-				$libraryFilePath = $moduleLibraryPath;
525
-			}
526
-			else{
527
-				$logger->info('Cannot find library [' . $class . '] from modules using the default location');
528
-			}
529
-			return $libraryFilePath;
530
-		}
509
+        /**
510
+         * Get the library file path using the module information
511
+         * @param  string $class the class name
512
+         * @return string|null        the library file path otherwise null will be returned
513
+         */
514
+        protected static function getLibraryPathUsingModuleInfo($class){
515
+            $logger = static::getLogger();
516
+            $libraryFilePath = null;
517
+            $logger->debug('Checking library [' . $class . '] from module list ...');
518
+            $moduleInfo = self::getModuleInfoForModelLibrary($class);
519
+            $module = $moduleInfo['module'];
520
+            $class  = $moduleInfo['class'];
521
+            $moduleLibraryPath = Module::findLibraryFullPath($class, $module);
522
+            if ($moduleLibraryPath){
523
+                $logger->info('Found library [' . $class . '] from module [' .$module. '], the file path is [' .$moduleLibraryPath. '] we will used it');
524
+                $libraryFilePath = $moduleLibraryPath;
525
+            }
526
+            else{
527
+                $logger->info('Cannot find library [' . $class . '] from modules using the default location');
528
+            }
529
+            return $libraryFilePath;
530
+        }
531 531
 
532
-		/**
533
-		 * Load the library 
534
-		 * @param  string $libraryFilePath the file path of the library to load
535
-		 * @param  string $class           the class name
536
-		 * @param  string $instance        the instance
537
-		 * @param  array  $params          the parameter to use
538
-		 * @return void
539
-		 */
540
-		protected static function loadLibrary($libraryFilePath, $class, $instance, $params = array()){
541
-			if ($libraryFilePath){
542
-				$logger = static::getLogger();
543
-				require_once $libraryFilePath;
544
-				if (class_exists($class)){
545
-					$c = $params ? new $class($params) : new $class();
546
-					$obj = & get_instance();
547
-					$obj->{$instance} = $c;
548
-					static::$loaded[$instance] = $class;
549
-					$logger->info('Library [' . $class . '] --> ' . $libraryFilePath . ' loaded successfully.');
550
-				}
551
-				else{
552
-					show_error('The file '.$libraryFilePath.' exists but does not contain the class '.$class);
553
-				}
554
-			}
555
-			else{
556
-				show_error('Unable to find library class [' . $class . ']');
557
-			}
558
-		}
532
+        /**
533
+         * Load the library 
534
+         * @param  string $libraryFilePath the file path of the library to load
535
+         * @param  string $class           the class name
536
+         * @param  string $instance        the instance
537
+         * @param  array  $params          the parameter to use
538
+         * @return void
539
+         */
540
+        protected static function loadLibrary($libraryFilePath, $class, $instance, $params = array()){
541
+            if ($libraryFilePath){
542
+                $logger = static::getLogger();
543
+                require_once $libraryFilePath;
544
+                if (class_exists($class)){
545
+                    $c = $params ? new $class($params) : new $class();
546
+                    $obj = & get_instance();
547
+                    $obj->{$instance} = $c;
548
+                    static::$loaded[$instance] = $class;
549
+                    $logger->info('Library [' . $class . '] --> ' . $libraryFilePath . ' loaded successfully.');
550
+                }
551
+                else{
552
+                    show_error('The file '.$libraryFilePath.' exists but does not contain the class '.$class);
553
+                }
554
+            }
555
+            else{
556
+                show_error('Unable to find library class [' . $class . ']');
557
+            }
558
+        }
559 559
 
560
-		/**
561
-		 * Load the language 
562
-		 * @param  string $languageFilePath the file path of the language to load
563
-		 * @param  string $language           the language name
564
-		 * @return void
565
-		 */
566
-		protected static function loadLanguage($languageFilePath, $language){
567
-			if ($languageFilePath){
568
-				$logger = static::getLogger();
569
-				$lang = array();
570
-				require_once $languageFilePath;
571
-				if (! empty($lang) && is_array($lang)){
572
-					$logger->info('Language file  [' .$languageFilePath. '] contains the valid languages keys add them to language list');
573
-					//Note: may be here the class 'Lang' not yet loaded
574
-					$langObj =& class_loader('Lang', 'classes');
575
-					$langObj->addLangMessages($lang);
576
-					//free the memory
577
-					unset($lang);
578
-				}
579
-				static::$loaded['lang_' . $language] = $languageFilePath;
580
-				$logger->info('Language [' . $language . '] --> ' . $languageFilePath . ' loaded successfully.');
581
-			}
582
-			else{
583
-				show_error('Unable to find language [' . $language . ']');
584
-			}
585
-		}
560
+        /**
561
+         * Load the language 
562
+         * @param  string $languageFilePath the file path of the language to load
563
+         * @param  string $language           the language name
564
+         * @return void
565
+         */
566
+        protected static function loadLanguage($languageFilePath, $language){
567
+            if ($languageFilePath){
568
+                $logger = static::getLogger();
569
+                $lang = array();
570
+                require_once $languageFilePath;
571
+                if (! empty($lang) && is_array($lang)){
572
+                    $logger->info('Language file  [' .$languageFilePath. '] contains the valid languages keys add them to language list');
573
+                    //Note: may be here the class 'Lang' not yet loaded
574
+                    $langObj =& class_loader('Lang', 'classes');
575
+                    $langObj->addLangMessages($lang);
576
+                    //free the memory
577
+                    unset($lang);
578
+                }
579
+                static::$loaded['lang_' . $language] = $languageFilePath;
580
+                $logger->info('Language [' . $language . '] --> ' . $languageFilePath . ' loaded successfully.');
581
+            }
582
+            else{
583
+                show_error('Unable to find language [' . $language . ']');
584
+            }
585
+        }
586 586
 
587 587
 
588 588
 
589 589
 
590
-		/**
591
-		 * Get all the autoload using the configuration file
592
-		 * @return array
593
-		 */
594
-		private function getResourcesFromAutoloadConfig(){
595
-			$autoloads = array();
596
-			$autoloads['config']    = array();
597
-			$autoloads['languages'] = array();
598
-			$autoloads['libraries'] = array();
599
-			$autoloads['models']    = array();
600
-			$autoloads['functions'] = array();
601
-			//loading of the resources from autoload configuration file
602
-			if (file_exists(CONFIG_PATH . 'autoload.php')){
603
-				$autoload = array();
604
-				require_once CONFIG_PATH . 'autoload.php';
605
-				if (! empty($autoload) && is_array($autoload)){
606
-					$autoloads = array_merge($autoloads, $autoload);
607
-					unset($autoload);
608
-				}
609
-			}
610
-			//loading autoload configuration for modules
611
-			$modulesAutoloads = Module::getModulesAutoloadConfig();
612
-			if (! empty($modulesAutoloads) && is_array($modulesAutoloads)){
613
-				$autoloads = array_merge_recursive($autoloads, $modulesAutoloads);
614
-			}
615
-			return $autoloads;
616
-		}
590
+        /**
591
+         * Get all the autoload using the configuration file
592
+         * @return array
593
+         */
594
+        private function getResourcesFromAutoloadConfig(){
595
+            $autoloads = array();
596
+            $autoloads['config']    = array();
597
+            $autoloads['languages'] = array();
598
+            $autoloads['libraries'] = array();
599
+            $autoloads['models']    = array();
600
+            $autoloads['functions'] = array();
601
+            //loading of the resources from autoload configuration file
602
+            if (file_exists(CONFIG_PATH . 'autoload.php')){
603
+                $autoload = array();
604
+                require_once CONFIG_PATH . 'autoload.php';
605
+                if (! empty($autoload) && is_array($autoload)){
606
+                    $autoloads = array_merge($autoloads, $autoload);
607
+                    unset($autoload);
608
+                }
609
+            }
610
+            //loading autoload configuration for modules
611
+            $modulesAutoloads = Module::getModulesAutoloadConfig();
612
+            if (! empty($modulesAutoloads) && is_array($modulesAutoloads)){
613
+                $autoloads = array_merge_recursive($autoloads, $modulesAutoloads);
614
+            }
615
+            return $autoloads;
616
+        }
617 617
 
618
-		/**
619
-		 * Load the autoload configuration
620
-		 * @return void
621
-		 */
622
-		private function loadResourcesFromAutoloadConfig(){
623
-			$autoloads = array();
624
-			$autoloads['config']    = array();
625
-			$autoloads['languages'] = array();
626
-			$autoloads['libraries'] = array();
627
-			$autoloads['models']    = array();
628
-			$autoloads['functions'] = array();
618
+        /**
619
+         * Load the autoload configuration
620
+         * @return void
621
+         */
622
+        private function loadResourcesFromAutoloadConfig(){
623
+            $autoloads = array();
624
+            $autoloads['config']    = array();
625
+            $autoloads['languages'] = array();
626
+            $autoloads['libraries'] = array();
627
+            $autoloads['models']    = array();
628
+            $autoloads['functions'] = array();
629 629
 
630
-			$list = $this->getResourcesFromAutoloadConfig();
631
-			$autoloads = array_merge($autoloads, $list);
630
+            $list = $this->getResourcesFromAutoloadConfig();
631
+            $autoloads = array_merge($autoloads, $list);
632 632
 			
633
-			//config autoload
634
-			$this->loadAutoloadResourcesArray('config', $autoloads['config']);
633
+            //config autoload
634
+            $this->loadAutoloadResourcesArray('config', $autoloads['config']);
635 635
 			
636
-			//languages autoload
637
-			$this->loadAutoloadResourcesArray('lang', $autoloads['languages']);
636
+            //languages autoload
637
+            $this->loadAutoloadResourcesArray('lang', $autoloads['languages']);
638 638
 			
639
-			//libraries autoload
640
-			$this->loadAutoloadResourcesArray('library', $autoloads['libraries']);
639
+            //libraries autoload
640
+            $this->loadAutoloadResourcesArray('library', $autoloads['libraries']);
641 641
 
642
-			//models autoload
643
-			$this->loadAutoloadResourcesArray('model', $autoloads['models']);
642
+            //models autoload
643
+            $this->loadAutoloadResourcesArray('model', $autoloads['models']);
644 644
 			
645
-			//functions autoload
646
-			$this->loadAutoloadResourcesArray('functions', $autoloads['functions']);
647
-		}
645
+            //functions autoload
646
+            $this->loadAutoloadResourcesArray('functions', $autoloads['functions']);
647
+        }
648 648
 
649
-		/**
650
-		 * Load the resources autoload array
651
-		 * @param  string $method    this object method name to call
652
-		 * @param  array  $resources the resource to load
653
-		 * @return void            
654
-		 */
655
-		private function loadAutoloadResourcesArray($method, array $resources){
656
-			foreach ($resources as $name) {
657
-				$this->{$method}($name);
658
-			}
659
-		}
660
-	}
649
+        /**
650
+         * Load the resources autoload array
651
+         * @param  string $method    this object method name to call
652
+         * @param  array  $resources the resource to load
653
+         * @return void            
654
+         */
655
+        private function loadAutoloadResourcesArray($method, array $resources){
656
+            foreach ($resources as $name) {
657
+                $this->{$method}($name);
658
+            }
659
+        }
660
+    }
Please login to merge, or discard this patch.
core/classes/Log.php 1 patch
Indentation   +266 added lines, -266 removed lines patch added patch discarded remove patch
@@ -1,297 +1,297 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') || exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
2
+    defined('ROOT_PATH') || exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26 26
 
27
-	class Log{
27
+    class Log{
28 28
 		
29
-		/**
30
-		 * The defined constante for Log level
31
-		 */
32
-		const NONE = 99999999;
33
-		const FATAL = 500;
34
-		const ERROR = 400;
35
-		const WARNING = 300;
36
-		const INFO = 200;
37
-		const DEBUG = 100;
38
-		const ALL = -99999999;
29
+        /**
30
+         * The defined constante for Log level
31
+         */
32
+        const NONE = 99999999;
33
+        const FATAL = 500;
34
+        const ERROR = 400;
35
+        const WARNING = 300;
36
+        const INFO = 200;
37
+        const DEBUG = 100;
38
+        const ALL = -99999999;
39 39
 
40
-		/**
41
-		 * The logger name
42
-		 * @var string
43
-		 */
44
-		private $logger = 'ROOT_LOGGER';
40
+        /**
41
+         * The logger name
42
+         * @var string
43
+         */
44
+        private $logger = 'ROOT_LOGGER';
45 45
 		
46
-		/**
47
-		 * List of valid log level to be checked for the configuration
48
-		 * @var array
49
-		 */
50
-		private static $validConfigLevel = array('off', 'none', 'fatal', 'error', 'warning', 'warn', 'info', 'debug', 'all');
46
+        /**
47
+         * List of valid log level to be checked for the configuration
48
+         * @var array
49
+         */
50
+        private static $validConfigLevel = array('off', 'none', 'fatal', 'error', 'warning', 'warn', 'info', 'debug', 'all');
51 51
 
52
-		/**
53
-		 * Create new Log instance
54
-		 */
55
-		public function __construct(){
56
-		}
52
+        /**
53
+         * Create new Log instance
54
+         */
55
+        public function __construct(){
56
+        }
57 57
 
58
-		/**
59
-		 * Set the logger to identify each message in the log
60
-		 * @param string $logger the logger name
61
-		 */
62
-		public  function setLogger($logger){
63
-			$this->logger = $logger;
64
-		}
58
+        /**
59
+         * Set the logger to identify each message in the log
60
+         * @param string $logger the logger name
61
+         */
62
+        public  function setLogger($logger){
63
+            $this->logger = $logger;
64
+        }
65 65
 
66
-		/**
67
-		 * Save the fatal message in the log
68
-		 * @see Log::writeLog for more detail
69
-		 * @param  string $message the log message to save
70
-		 */
71
-		public function fatal($message){
72
-			$this->writeLog($message, self::FATAL);
73
-		} 
66
+        /**
67
+         * Save the fatal message in the log
68
+         * @see Log::writeLog for more detail
69
+         * @param  string $message the log message to save
70
+         */
71
+        public function fatal($message){
72
+            $this->writeLog($message, self::FATAL);
73
+        } 
74 74
 		
75
-		/**
76
-		 * Save the error message in the log
77
-		 * @see Log::writeLog for more detail
78
-		 * @param  string $message the log message to save
79
-		 */
80
-		public function error($message){
81
-			$this->writeLog($message, self::ERROR);
82
-		} 
75
+        /**
76
+         * Save the error message in the log
77
+         * @see Log::writeLog for more detail
78
+         * @param  string $message the log message to save
79
+         */
80
+        public function error($message){
81
+            $this->writeLog($message, self::ERROR);
82
+        } 
83 83
 
84
-		/**
85
-		 * Save the warning message in the log
86
-		 * @see Log::writeLog for more detail
87
-		 * @param  string $message the log message to save
88
-		 */
89
-		public function warning($message){
90
-			$this->writeLog($message, self::WARNING);
91
-		} 
84
+        /**
85
+         * Save the warning message in the log
86
+         * @see Log::writeLog for more detail
87
+         * @param  string $message the log message to save
88
+         */
89
+        public function warning($message){
90
+            $this->writeLog($message, self::WARNING);
91
+        } 
92 92
 		
93
-		/**
94
-		 * Save the info message in the log
95
-		 * @see Log::writeLog for more detail
96
-		 * @param  string $message the log message to save
97
-		 */
98
-		public function info($message){
99
-			$this->writeLog($message, self::INFO);
100
-		} 
93
+        /**
94
+         * Save the info message in the log
95
+         * @see Log::writeLog for more detail
96
+         * @param  string $message the log message to save
97
+         */
98
+        public function info($message){
99
+            $this->writeLog($message, self::INFO);
100
+        } 
101 101
 		
102
-		/**
103
-		 * Save the debug message in the log
104
-		 * @see Log::writeLog for more detail
105
-		 * @param  string $message the log message to save
106
-		 */
107
-		public function debug($message){
108
-			$this->writeLog($message, self::DEBUG);
109
-		} 
102
+        /**
103
+         * Save the debug message in the log
104
+         * @see Log::writeLog for more detail
105
+         * @param  string $message the log message to save
106
+         */
107
+        public function debug($message){
108
+            $this->writeLog($message, self::DEBUG);
109
+        } 
110 110
 		
111 111
 		
112
-		/**
113
-		 * Save the log message
114
-		 * @param  string $message the log message to be saved
115
-		 * @param  integer|string $level   the log level in integer or string format, if is string will convert into integer
116
-		 * to allow check the log level threshold.
117
-		 */
118
-		public function writeLog($message, $level = self::INFO){
119
-			$configLogLevel = get_config('log_level');
120
-			if(! $configLogLevel){
121
-				//so means no need log just stop here
122
-				return;
123
-			}
124
-			//check config log level
125
-			if(! self::isValidConfigLevel($configLogLevel)){
126
-				//NOTE: here need put the show_error() "logging" to false to prevent loop
127
-				show_error('Invalid config log level [' . $configLogLevel . '], the value must be one of the following: ' . implode(', ', array_map('strtoupper', self::$validConfigLevel)), $title = 'Log Config Error', $logging = false);	
128
-			}
112
+        /**
113
+         * Save the log message
114
+         * @param  string $message the log message to be saved
115
+         * @param  integer|string $level   the log level in integer or string format, if is string will convert into integer
116
+         * to allow check the log level threshold.
117
+         */
118
+        public function writeLog($message, $level = self::INFO){
119
+            $configLogLevel = get_config('log_level');
120
+            if(! $configLogLevel){
121
+                //so means no need log just stop here
122
+                return;
123
+            }
124
+            //check config log level
125
+            if(! self::isValidConfigLevel($configLogLevel)){
126
+                //NOTE: here need put the show_error() "logging" to false to prevent loop
127
+                show_error('Invalid config log level [' . $configLogLevel . '], the value must be one of the following: ' . implode(', ', array_map('strtoupper', self::$validConfigLevel)), $title = 'Log Config Error', $logging = false);	
128
+            }
129 129
 			
130
-			//check if config log_logger_name and current log can save log data
131
-			if(! $this->canSaveLogDataForLogger()){
132
-				return;
133
-			}
130
+            //check if config log_logger_name and current log can save log data
131
+            if(! $this->canSaveLogDataForLogger()){
132
+                return;
133
+            }
134 134
 			
135
-			//if $level is not an integer
136
-			if(! is_numeric($level)){
137
-				$level = self::getLevelValue($level);
138
-			}
135
+            //if $level is not an integer
136
+            if(! is_numeric($level)){
137
+                $level = self::getLevelValue($level);
138
+            }
139 139
 			
140
-			//check if can logging regarding the log level config
141
-			$configLevel = self::getLevelValue($configLogLevel);
142
-			if($configLevel > $level){
143
-				//can't log
144
-				return;
145
-			}
146
-			//check log file and directory
147
-			$path = $this->checkAndSetLogFileDirectory();
148
-			//save the log data
149
-			$this->saveLogData($path, $level, $message);
150
-		}	
140
+            //check if can logging regarding the log level config
141
+            $configLevel = self::getLevelValue($configLogLevel);
142
+            if($configLevel > $level){
143
+                //can't log
144
+                return;
145
+            }
146
+            //check log file and directory
147
+            $path = $this->checkAndSetLogFileDirectory();
148
+            //save the log data
149
+            $this->saveLogData($path, $level, $message);
150
+        }	
151 151
 
152
-		/**
153
-		 * Save the log data into file
154
-		 * @param  string $path    the path of the log file
155
-		 * @param  integer|string $level   the log level in integer or string format, if is string will convert into integer
156
-		 * @param  string $message the log message to save
157
-		 * @return void
158
-		 */
159
-		protected function saveLogData($path, $level, $message){
160
-			//may be at this time helper user_agent not yet included
161
-			require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
152
+        /**
153
+         * Save the log data into file
154
+         * @param  string $path    the path of the log file
155
+         * @param  integer|string $level   the log level in integer or string format, if is string will convert into integer
156
+         * @param  string $message the log message to save
157
+         * @return void
158
+         */
159
+        protected function saveLogData($path, $level, $message){
160
+            //may be at this time helper user_agent not yet included
161
+            require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
162 162
 			
163
-			///////////////////// date //////////////
164
-			$timestampWithMicro = microtime(true);
165
-			$microtime = sprintf('%06d', ($timestampWithMicro - floor($timestampWithMicro)) * 1000000);
166
-			$dateTime = new DateTime(date('Y-m-d H:i:s.' . $microtime, $timestampWithMicro));
167
-			$logDate = $dateTime->format('Y-m-d H:i:s.u'); 
168
-			//ip
169
-			$ip = get_ip();
163
+            ///////////////////// date //////////////
164
+            $timestampWithMicro = microtime(true);
165
+            $microtime = sprintf('%06d', ($timestampWithMicro - floor($timestampWithMicro)) * 1000000);
166
+            $dateTime = new DateTime(date('Y-m-d H:i:s.' . $microtime, $timestampWithMicro));
167
+            $logDate = $dateTime->format('Y-m-d H:i:s.u'); 
168
+            //ip
169
+            $ip = get_ip();
170 170
 			
171
-			//if $level is not an integer
172
-			if(! is_numeric($level)){
173
-				$level = self::getLevelValue($level);
174
-			}
171
+            //if $level is not an integer
172
+            if(! is_numeric($level)){
173
+                $level = self::getLevelValue($level);
174
+            }
175 175
 
176
-			//level name
177
-			$levelName = self::getLevelName($level);
176
+            //level name
177
+            $levelName = self::getLevelName($level);
178 178
 			
179
-			//debug info
180
-			$dtrace = debug_backtrace();
181
-			$fileInfo = $dtrace[0]['file'] == __FILE__ ? $dtrace[1] : $dtrace[0];
179
+            //debug info
180
+            $dtrace = debug_backtrace();
181
+            $fileInfo = $dtrace[0]['file'] == __FILE__ ? $dtrace[1] : $dtrace[0];
182 182
 			
183
-			$str = $logDate . ' [' . str_pad($levelName, 7 /*warning len*/) . '] ' . ' [' . str_pad($ip, 15) . '] ' . $this->logger . ' : ' . $message . ' ' . '[' . $fileInfo['file'] . '::' . $fileInfo['line'] . ']' . "\n";
184
-			$fp = fopen($path, 'a+');
185
-			if(is_resource($fp)){
186
-				flock($fp, LOCK_EX); // exclusive lock, will get released when the file is closed
187
-				fwrite($fp, $str);
188
-				fclose($fp);
189
-			}
190
-		}	
183
+            $str = $logDate . ' [' . str_pad($levelName, 7 /*warning len*/) . '] ' . ' [' . str_pad($ip, 15) . '] ' . $this->logger . ' : ' . $message . ' ' . '[' . $fileInfo['file'] . '::' . $fileInfo['line'] . ']' . "\n";
184
+            $fp = fopen($path, 'a+');
185
+            if(is_resource($fp)){
186
+                flock($fp, LOCK_EX); // exclusive lock, will get released when the file is closed
187
+                fwrite($fp, $str);
188
+                fclose($fp);
189
+            }
190
+        }	
191 191
 
192
-		/**
193
-		 * Check if the current logger can save log data regarding the configuration
194
-		 * of logger filter
195
-		 * @return boolean
196
-		 */
197
-		protected function canSaveLogDataForLogger(){
198
-			if(! empty($this->logger)){
199
-				$configLoggersName = get_config('log_logger_name', array());
200
-				if (!empty($configLoggersName)) {
201
-					//for best comparaison put all string to lowercase
202
-					$configLoggersName = array_map('strtolower', $configLoggersName);
203
-					if(! in_array(strtolower($this->logger), $configLoggersName)){
204
-						return false;
205
-					}
206
-				}
207
-			}
208
-			return true;
209
-		}
192
+        /**
193
+         * Check if the current logger can save log data regarding the configuration
194
+         * of logger filter
195
+         * @return boolean
196
+         */
197
+        protected function canSaveLogDataForLogger(){
198
+            if(! empty($this->logger)){
199
+                $configLoggersName = get_config('log_logger_name', array());
200
+                if (!empty($configLoggersName)) {
201
+                    //for best comparaison put all string to lowercase
202
+                    $configLoggersName = array_map('strtolower', $configLoggersName);
203
+                    if(! in_array(strtolower($this->logger), $configLoggersName)){
204
+                        return false;
205
+                    }
206
+                }
207
+            }
208
+            return true;
209
+        }
210 210
 
211
-		/**
212
-		 * Check the file and directory 
213
-		 * @return string the log file path
214
-		 */
215
-		protected function checkAndSetLogFileDirectory(){
216
-			$logSavePath = get_config('log_save_path');
217
-			if(! $logSavePath){
218
-				$logSavePath = LOGS_PATH;
219
-			}
211
+        /**
212
+         * Check the file and directory 
213
+         * @return string the log file path
214
+         */
215
+        protected function checkAndSetLogFileDirectory(){
216
+            $logSavePath = get_config('log_save_path');
217
+            if(! $logSavePath){
218
+                $logSavePath = LOGS_PATH;
219
+            }
220 220
 			
221
-			if(! is_dir($logSavePath) || !is_writable($logSavePath)){
222
-				//NOTE: here need put the show_error() "logging" to false to prevent loop
223
-				show_error('Error : the log dir does not exists or is not writable', $title = 'Log directory error', $logging = false);
224
-			}
221
+            if(! is_dir($logSavePath) || !is_writable($logSavePath)){
222
+                //NOTE: here need put the show_error() "logging" to false to prevent loop
223
+                show_error('Error : the log dir does not exists or is not writable', $title = 'Log directory error', $logging = false);
224
+            }
225 225
 			
226
-			$path = $logSavePath . 'logs-' . date('Y-m-d') . '.log';
227
-			if(! file_exists($path)){
228
-				touch($path);
229
-			}
230
-			return $path;
231
-		}
226
+            $path = $logSavePath . 'logs-' . date('Y-m-d') . '.log';
227
+            if(! file_exists($path)){
228
+                touch($path);
229
+            }
230
+            return $path;
231
+        }
232 232
 		
233
-		/**
234
-		 * Check if the given log level is valid
235
-		 *
236
-		 * @param  string  $level the log level
237
-		 *
238
-		 * @return boolean        true if the given log level is valid, false if not
239
-		 */
240
-		protected static function isValidConfigLevel($level){
241
-			$level = strtolower($level);
242
-			return in_array($level, self::$validConfigLevel);
243
-		}
233
+        /**
234
+         * Check if the given log level is valid
235
+         *
236
+         * @param  string  $level the log level
237
+         *
238
+         * @return boolean        true if the given log level is valid, false if not
239
+         */
240
+        protected static function isValidConfigLevel($level){
241
+            $level = strtolower($level);
242
+            return in_array($level, self::$validConfigLevel);
243
+        }
244 244
 
245
-		/**
246
-		 * Get the log level number for the given level string
247
-		 * @param  string $level the log level in string format
248
-		 * 
249
-		 * @return int        the log level in integer format using the predefined constants
250
-		 */
251
-		protected static function getLevelValue($level){
252
-			$level = strtolower($level);
253
-			$levelMaps = array(
254
-				'fatal'   => self::FATAL,
255
-				'error'   => self::ERROR,
256
-				'warning' => self::WARNING,
257
-				'warn'    => self::WARNING,
258
-				'info'    => self::INFO,
259
-				'debug'   => self::DEBUG,
260
-				'all'     => self::ALL
261
-			);
262
-			//the default value is NONE, so means no need test for NONE
263
-			$value = self::NONE;
264
-			foreach ($levelMaps as $k => $v) {
265
-				if($level == $k){
266
-					$value = $v;
267
-					break;
268
-				}
269
-			}
270
-			return $value;
271
-		}
245
+        /**
246
+         * Get the log level number for the given level string
247
+         * @param  string $level the log level in string format
248
+         * 
249
+         * @return int        the log level in integer format using the predefined constants
250
+         */
251
+        protected static function getLevelValue($level){
252
+            $level = strtolower($level);
253
+            $levelMaps = array(
254
+                'fatal'   => self::FATAL,
255
+                'error'   => self::ERROR,
256
+                'warning' => self::WARNING,
257
+                'warn'    => self::WARNING,
258
+                'info'    => self::INFO,
259
+                'debug'   => self::DEBUG,
260
+                'all'     => self::ALL
261
+            );
262
+            //the default value is NONE, so means no need test for NONE
263
+            $value = self::NONE;
264
+            foreach ($levelMaps as $k => $v) {
265
+                if($level == $k){
266
+                    $value = $v;
267
+                    break;
268
+                }
269
+            }
270
+            return $value;
271
+        }
272 272
 
273
-		/**
274
-		 * Get the log level string for the given log level integer
275
-		 * @param  integer $level the log level in integer format
276
-		 * @return string        the log level in string format
277
-		 */
278
-		protected static function getLevelName($level){
279
-			$levelMaps = array(
280
-				self::FATAL   => 'FATAL',
281
-				self::ERROR   => 'ERROR',
282
-				self::WARNING => 'WARNING',
283
-				self::INFO    => 'INFO',
284
-				self::DEBUG   => 'DEBUG'
285
-			);
286
-			$value = '';
287
-			foreach ($levelMaps as $k => $v) {
288
-				if($level == $k){
289
-					$value = $v;
290
-					break;
291
-				}
292
-			}
293
-			//no need for ALL
294
-			return $value;
295
-		}
273
+        /**
274
+         * Get the log level string for the given log level integer
275
+         * @param  integer $level the log level in integer format
276
+         * @return string        the log level in string format
277
+         */
278
+        protected static function getLevelName($level){
279
+            $levelMaps = array(
280
+                self::FATAL   => 'FATAL',
281
+                self::ERROR   => 'ERROR',
282
+                self::WARNING => 'WARNING',
283
+                self::INFO    => 'INFO',
284
+                self::DEBUG   => 'DEBUG'
285
+            );
286
+            $value = '';
287
+            foreach ($levelMaps as $k => $v) {
288
+                if($level == $k){
289
+                    $value = $v;
290
+                    break;
291
+                }
292
+            }
293
+            //no need for ALL
294
+            return $value;
295
+        }
296 296
 
297
-	}
297
+    }
Please login to merge, or discard this patch.