Passed
Push — 1.0.0-dev ( 024223...5d8234 )
by nguereza
02:46
created

set_session_config()   C

Complexity

Conditions 12
Paths 41

Size

Total Lines 62
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 45
nc 41
nop 0
dl 0
loc 62
rs 6.9666
c 1
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 MIT License (MIT)
9
     *
10
     * Copyright (c) 2017 TNH Framework
11
     *
12
     * Permission is hereby granted, free of charge, to any person obtaining a copy
13
     * of this software and associated documentation files (the "Software"), to deal
14
     * in the Software without restriction, including without limitation the rights
15
     * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
     * copies of the Software, and to permit persons to whom the Software is
17
     * furnished to do so, subject to the following conditions:
18
     *
19
     * The above copyright notice and this permission notice shall be included in all
20
     * copies or substantial portions of the Software.
21
     *
22
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
     * SOFTWARE.
29
     */
30
31
    /**
32
     *  @file common.php
33
     *  
34
     *  Contains most of the commons functions used by the system
35
     *  
36
     *  @package	core
37
     *  @author	TNH Framework team
38
     *  @copyright	Copyright (c) 2017
39
     *  @license	http://opensource.org/licenses/MIT	MIT License
40
     *  @link	http://www.iacademy.cf
41
     *  @version 1.0.0
42
     *  @filesource
43
     */
44
	
45
46
    /**
47
     * This function is the class loader helper is used if the library "Loader" not yet loaded
48
     * he load the class once
49
     * @param  string $class  the class name to be loaded
50
     * @param  string $dir    the directory where to find the class
51
     * @param  mixed $params the parameter to pass as argument to the constructor of the class
52
     * @codeCoverageIgnore
53
     * 
54
     * @return object         the instance of the loaded class
55
     */
56
    function & class_loader($class, $dir = 'libraries', $params = null){
57
        //put the first letter of class to upper case 
58
        $class = ucfirst($class);
59
        static $classes = array();
60
        if (isset($classes[$class]) /*hack for duplicate log Logger name*/ && $class != 'Log') {
61
            return $classes[$class];
62
        }
63
        $found = false;
64
        foreach (array(APPS_PATH, CORE_PATH) as $path) {
65
            $file = $path . $dir . DS . $class . '.php';
66
            if (file_exists($file)) {
67
                if (class_exists($class, false) === false) {
68
                    require_once $file;
69
                }
70
                //already found
71
                $found = true;
72
                break;
73
            }
74
        }
75
        if (!$found) {
76
            //can't use show_error() at this time because some dependencies not yet loaded
77
            set_http_status_header(503);
78
            echo 'Cannot find the class [' . $class . ']';
79
            die();
80
        }
81
		
82
        /*
83
		   TODO use the best method to get the Log instance
84
		 */
85
        if ($class == 'Log') {
86
            //can't use the instruction like "return new Log()" 
87
            //because we need return the reference instance of the loaded class.
88
            $log = new Log();
89
            return $log;
90
        }
91
        //track of loaded classes
92
        class_loaded($class);
93
		
94
        //record the class instance
95
        $classes[$class] = isset($params) ? new $class($params) : new $class();
96
		
97
        return $classes[$class];
98
    }
99
100
    /**
101
     * This function is the helper to record the loaded classes
102
     * @param  string $class the loaded class name
103
     * @codeCoverageIgnore
104
     * 
105
     * @return array        the list of the loaded classes
106
     */
107
    function & class_loaded($class = null){
108
        static $list = array();
109
        if ($class !== null) {
110
            $list[strtolower($class)] = $class;
111
        }
112
        return $list;
113
    }
114
115
    /**
116
     * This function is used to load the configurations in the case the "Config" library not yet loaded
117
     * @param  array  $overwrite_values if need overwrite the existing configuration
118
     * @codeCoverageIgnore
119
     * 
120
     * @return array                   the configurations values
121
     */
122
    function & load_configurations(array $overwrite_values = array()){
123
        static $config;
124
        if (empty($config)) {
125
            $file = CONFIG_PATH . 'config.php';
126
            $found = false;
127
            if (file_exists($file)) {
128
                require_once $file;
129
                $found = true;
130
            }
131
            if (!$found) {
132
                set_http_status_header(503);
133
                echo 'Unable to find the configuration file [' . $file . ']';
134
                die();
135
            }
136
        }
137
        foreach ($overwrite_values as $key => $value) {
138
            $config[$key] = $value;
139
        }
140
        return $config;
141
    }
142
143
    /**
144
     * This function is the helper to get the config value in case the "Config" library not yet loaded
145
     * @param  string $key     the config item to get the vale
146
     * @param  mixed $default the default value to return if can't find the config item in the configuration
147
     * @test
148
     * 
149
     * @return mixed          the config value
150
     */
151
    function get_config($key, $default = null) {
152
        static $cfg;
153
        if (empty($cfg)) {
154
            $cfg[0] = & load_configurations();
155
            if(! is_array($cfg[0])){
156
                $cfg[0] = array();
157
            }
158
        }
159
        return array_key_exists($key, $cfg[0]) ? $cfg[0][$key] : $default;
160
    }
161
162
    /**
163
     * This function is a helper to logging message
164
     * @param  string $level   the log level "ERROR", "DEBUG", "INFO", etc.
165
     * @param  string $message the log message to be saved
166
     * @param  string $logger  the logger to use if is set
167
     * 
168
     * @codeCoverageIgnore
169
     */
170
    function save_to_log($level, $message, $logger = null) {
171
        $log = & class_loader('Log', 'classes');
172
        if ($logger) {
173
            $log->setLogger($logger);
174
        }
175
        $log->writeLog($message, $level);
176
    }
177
178
    /**
179
     * Set the HTTP status header
180
     * @param integer $code the HTTP status code
181
     * @param string  $text the HTTP status text
182
     * 
183
     * @codeCoverageIgnore
184
     */
185
    function set_http_status_header($code = 200, $text = null) {
186
        if (empty($text)) {
187
            $http_status = array(
188
                                100 => 'Continue',
189
                                101 => 'Switching Protocols',
190
                                200 => 'OK',
191
                                201 => 'Created',
192
                                202 => 'Accepted',
193
                                203 => 'Non-Authoritative Information',
194
                                204 => 'No Content',
195
                                205 => 'Reset Content',
196
                                206 => 'Partial Content',
197
                                300 => 'Multiple Choices',
198
                                301 => 'Moved Permanently',
199
                                302 => 'Found',
200
                                303 => 'See Other',
201
                                304 => 'Not Modified',
202
                                305 => 'Use Proxy',
203
                                307 => 'Temporary Redirect',
204
                                400 => 'Bad Request',
205
                                401 => 'Unauthorized',
206
                                402 => 'Payment Required',
207
                                403 => 'Forbidden',
208
                                404 => 'Not Found',
209
                                405 => 'Method Not Allowed',
210
                                406 => 'Not Acceptable',
211
                                407 => 'Proxy Authentication Required',
212
                                408 => 'Request Timeout',
213
                                409 => 'Conflict',
214
                                410 => 'Gone',
215
                                411 => 'Length Required',
216
                                412 => 'Precondition Failed',
217
                                413 => 'Request Entity Too Large',
218
                                414 => 'Request-URI Too Long',
219
                                415 => 'Unsupported Media Type',
220
                                416 => 'Requested Range Not Satisfiable',
221
                                417 => 'Expectation Failed',
222
                                418 => 'I\'m a teapot',
223
                                500 => 'Internal Server Error',
224
                                501 => 'Not Implemented',
225
                                502 => 'Bad Gateway',
226
                                503 => 'Service Unavailable',
227
                                504 => 'Gateway Timeout',
228
                                505 => 'HTTP Version Not Supported',
229
                            );
230
            if (isset($http_status[$code])) {
231
                $text = $http_status[$code];
232
            } else {
233
                show_error('No HTTP status text found for your code please check it.');
234
            }
235
        }
236
		
237
        if (strpos(php_sapi_name(), 'cgi') === 0) {
238
            header('Status: ' . $code . ' ' . $text, TRUE);
239
        } else {
240
            $globals = & class_loader('GlobalVar', 'classes');
241
            $proto = 'HTTP/1.1';
242
            if ($globals->server('SERVER_PROTOCOL')) {
243
                $proto = $globals->server('SERVER_PROTOCOL');
244
            }
245
            header($proto . ' ' . $code . ' ' . $text, TRUE, $code);
246
        }
247
    }
248
249
    /**
250
     *  This function displays an error message to the user and ends the execution of the script.
251
     *  
252
     *  @param string $msg the message to display
253
     *  @param string $title the message title: "error", "info", "warning", etc.
254
     *  @param boolean $logging either to save error in log
255
     *  
256
     *  @codeCoverageIgnore
257
     */
258
    function show_error($msg, $title = 'error', $logging = true) {
259
        $title = strtoupper($title);
260
        $data = array();
261
        $data['error'] = $msg;
262
        $data['title'] = $title;
263
        if ($logging) {
264
            save_to_log('error', '[' . $title . '] ' . strip_tags($msg), 'GLOBAL::ERROR');
265
        }
266
        $response = & class_loader('Response', 'classes');
267
        //remove other content set to prevent duplicate view
268
        $response->setFinalPageContent(null);
269
        $response->render('errors', $data);
270
        $response->sendError();
271
        die();
272
    }
273
274
       /**
275
     *  Function defined for handling PHP exception error message, 
276
     *  it displays an error message using the function "show_error"
277
     *  
278
     *  @param object $ex instance of the "Exception" class or a derived class
279
     *  @codeCoverageIgnore
280
     *  
281
     *  @return boolean
282
     */
283
    function fw_exception_handler($ex) {
284
        if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))) {
285
            show_error('An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception #' . $ex->getCode());
286
        } else {
287
            save_to_log('error', 'An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception');
288
        }
289
        return true;
290
    }
291
    
292
    /**
293
     *  Function defined for PHP error message handling
294
     *              
295
     *  @param int $errno the type of error for example: E_USER_ERROR, E_USER_WARNING, etc.
296
     *  @param string $errstr the error message
297
     *  @param string $errfile the file where the error occurred
298
     *  @param int $errline the line number where the error occurred
299
     *  @codeCoverageIgnore
300
     *  
301
     *  @return boolean 
302
     */
303
    function fw_error_handler($errno, $errstr, $errfile, $errline) {
304
        $isError = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $errno) === $errno);
305
        if ($isError) {
306
            set_http_status_header(500);
307
        }
308
        if (!(error_reporting() & $errno)) {
309
            save_to_log('error', 'An error is occurred in the file ' . $errfile . ' at line ' . $errline . ' raison : ' . $errstr, 'PHP ERROR');
310
            return;
311
        }
312
        if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))) {
313
            $errorType = 'error';
314
            switch ($errno) {
315
                case E_USER_WARNING:
316
                    $errorType = 'warning';
317
                    break;
318
                case E_USER_NOTICE:
319
                    $errorType = 'notice';
320
                    break;
321
            }
322
            show_error('An error is occurred in the file <b>' . $errfile . '</b> at line <b>' . $errline . '</b> raison : ' . $errstr, 'PHP ' . $errorType);
323
        }
324
        if ($isError) {
325
            die();
326
        }
327
        return true;
328
    }
329
330
    /**
331
     * This function is used to run in shutdown situation of the script
332
     * @codeCoverageIgnore
333
     */
334
    function fw_shudown_handler() {
335
        $lastError = error_get_last();
336
        if (isset($lastError) &&
337
            ($lastError['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING))) {
338
            fw_error_handler($lastError['type'], $lastError['message'], $lastError['file'], $lastError['line']);
339
        }
340
    }
341
342
    /**
343
     *  Check whether the protocol used is "https" or not
344
     *  That is, the web server is configured to use a secure connection.
345
     *  @codeCoverageIgnore
346
     *  
347
     *  @return boolean true if the web server uses the https protocol, false if not.
348
     */
349
    function is_https() {
350
        /*
351
		* some servers pass the "HTTPS" parameter in the server variable,
352
		* if is the case, check if the value is "on", "true", "1".
353
		*/
354
        $globals = & class_loader('GlobalVar', 'classes');
355
        if ($globals->server('HTTPS') && strtolower($globals->server('HTTPS')) !== 'off') {
356
            return true;
357
        }
358
        if ($globals->server('HTTP_X_FORWARDED_PROTO') && $globals->server('HTTP_X_FORWARDED_PROTO') === 'https') {
359
            return true;
360
        }
361
        if ($globals->server('HTTP_FRONT_END_HTTPS') && strtolower($globals->server('HTTP_FRONT_END_HTTPS')) !== 'off') {
362
            return true;
363
        }
364
        return false;
365
    }
366
	
367
    /**
368
     *  This function is used to check the URL format of the given string argument. 
369
     *  The address is valid if the protocol is http, https, ftp, etc.
370
     *
371
     *  @param string $url the URL address to check
372
     *  @test
373
     *  
374
     *  @return boolean true if is a valid URL address or false.
375
     */
376
    function is_url($url) {
377
        return preg_match('/^(http|https|ftp):\/\/(.*)/', $url) == 1;
378
    }
379
	
380
    /**
381
     *  Function defined to load controller
382
     *  
383
     *  @param string $controllerClass the controller class name to be loaded
384
     *  @codeCoverageIgnore
385
     */
386
    function autoload_controller($controllerClass) {
387
        if (file_exists($path = APPS_CONTROLLER_PATH . $controllerClass . '.php')) {
388
            require_once $path;
389
        }
390
    }
391
392
    /**
393
     *  Convert array attributes to string
394
     *
395
     *  This function converts an associative array into HTML attributes.
396
     *  For example :
397
     *  $a = array('name' => 'Foo', 'type' => 'text'); => produces the following string:
398
     *  name = "Foo" type = "text"
399
     *
400
     *  @param array $attributes associative array to convert to a string attribute.
401
     *   
402
     *  @return string string of the HTML attribute.
403
     */
404
    function attributes_to_string(array $attributes) {
405
        $str = ' ';
406
        //we check that the array passed as an argument is not empty.
407
        if (!empty($attributes)) {
408
            foreach ($attributes as $key => $value) {
409
                $key = trim(htmlspecialchars($key));
410
                $value = trim(htmlspecialchars($value));
411
                /*
412
				* To predict the case where the string to convert contains the character "
413
				* we check if this is the case we add a slash to solve this problem.
414
				* For example:
415
				* 	$attr = array('placeholder' => 'I am a "puple"')
416
				* 	$str = attributes_to_string($attr); => placeholder = "I am a \"puple\""
417
				 */
418
                if ($value && strpos('"', $value) !== false) {
419
                    $value = addslashes($value);
420
                }
421
                $str .= $key . ' = "' . $value . '" ';
422
            }
423
        }
424
        //remove the space after using rtrim()
425
        return rtrim($str);
426
    }
427
428
429
    /**
430
     * Function to stringfy PHP variable, useful in debug situation
431
     *
432
     * @param mixed $var the variable to stringfy
433
     * @codeCoverageIgnore
434
     *
435
     * @return string the stringfy value
436
     */
437
    function stringfy_vars($var) {
438
        return print_r($var, true);
439
    }
440
441
    /**
442
     * Clean the user input
443
     * @param  mixed $str the value to clean
444
     * @test
445
     * 
446
     * @return mixed   the sanitize value
447
     */
448
    function clean_input($str) {
449
        if (is_array($str)) {
450
            $str = array_map('clean_input', $str);
451
        } else if (is_object($str)) {
452
            $obj = $str;
453
            foreach ($str as $var => $value) {
454
                $obj->$var = clean_input($value);
455
            }
456
            $str = $obj;
457
        } else {
458
            $str = htmlspecialchars(strip_tags($str), ENT_QUOTES, 'UTF-8');
459
        }
460
        return $str;
461
    }
462
	
463
    /**
464
     * This function is used to hidden some part of the given string. Helpful if you need hide some confidential 
465
     * Information like credit card number, password, etc.
466
     *
467
     * @param  string $str the string you want to hide some part
468
     * @param  int $startCount the length of non hidden for the beginning char
469
     * @param  int $endCount the length of non hidden for the ending char
470
     * @param  string $hiddenChar the char used to hide the given string
471
     * @test
472
     * 
473
     * @return string the string with the hidden part.
474
     */
475
    function string_hidden($str, $startCount = 0, $endCount = 0, $hiddenChar = '*') {
476
        //get the string length
477
        $len = strlen($str);
478
        //if str is empty
479
        if ($len <= 0) {
480
            return str_repeat($hiddenChar, 6);
481
        }
482
        //if the length is less than startCount and endCount
483
        //or the startCount and endCount length is 0
484
        //or startCount is negative or endCount is negative
485
        //return the full string hidden
486
		
487
        if ((($startCount + $endCount) > $len) || ($startCount == 0 && $endCount == 0) || ($startCount < 0 || $endCount < 0)) {
488
            return str_repeat($hiddenChar, $len);
489
        }
490
        //the start non hidden string
491
        $startNonHiddenStr = substr($str, 0, $startCount);
492
        //the end non hidden string
493
        $endNonHiddenStr = null;
494
        if ($endCount > 0) {
495
            $endNonHiddenStr = substr($str, - $endCount);
496
        }
497
        //the hidden string
498
        $hiddenStr = str_repeat($hiddenChar, $len - ($startCount + $endCount));
499
		
500
        return $startNonHiddenStr . $hiddenStr . $endNonHiddenStr;
501
    }
502
	
503
    /**
504
     * This function is very useful, it allows to use the shared instance of 
505
     * the super controller in of all parts of your application.
506
     * 
507
     * NOTE: this function always returns the reference of the super instance.
508
     * For example :
509
     * $obj = & get_instance();
510
     * 
511
     * @codeCoverageIgnore
512
     *  
513
     * @return object the instance of the "Controller" class
514
     */
515
    function & get_instance(){
516
        return Controller::getInstance();
517
    }
518