1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 2 3 // ------------------------------------------------------------------------ 4 5 /** 6 * Common Functions 7 */ 8 9 /** 10 * 爲何還要定義這些全局函數呢?好比說,下面有不少函數,如get_config()、config_item()這兩個方法不是應該由 11 * core/Config.php這個組件去作麼?那個load_class()不該該由core/Loader.php去作麼? 把這些函數定義出來貌似 12 * 感受架構變得不那麼優雅,有點多餘。 13 * 實際上是出於這樣一種狀況: 14 * 好比說,若是一切和配置有關的動做都由Config組件來完成,一切加載的動做都由Loader來完成, 15 * 試想一下,若是我要加載Config組件,那麼,必須得經過Loader來加載,因此Loader必須比Config要更早實例化, 16 * 可是若是Loader實例化的時候須要一些和Loader有關的配置信息才能實例化呢?那就必須經過Config來爲它取得配置信息。 17 * 這裏就出現了雞和雞蛋的問題。。 18 * 我以前寫本身的框架也糾結過這樣的問題,後來參考了YII框架,發現它裏面其實都有一樣的問題,它裏面有個Exception的組件, 19 * 可是在加載這個Exception組件以前,在加載其它組件的時候,若是出錯了,那誰來處理異常和錯誤信息呢?答案就是先定義一些公共的函數。 20 * 因此這些公共函數就很好地解決了這個問題,這也是爲何Common.php要很早被引入。 21 * 22 */ 23 24 25 // ------------------------------------------------------------------------ 26 27 /** 28 * Determines if the current version of PHP is greater then the supplied value 29 */ 30 if ( ! function_exists('is_php')) 31 { 32 //判斷當前php版本是否是$version以上的。調用version_compare()這個函數。 33 function is_php($version = '5.0.0') 34 { 35 static $_is_php; 36 $version = (string)$version; 37 38 if ( ! isset($_is_php[$version])) 39 { 40 //PHP_VERION可以得到當前php版本。 41 $_is_php[$version] = (version_compare(PHP_VERSION, $version) < 0) ? FALSE : TRUE; 42 } 43 44 return $_is_php[$version]; 45 } 46 } 47 48 // ------------------------------------------------------------------------ 49 50 /** 51 * Tests for file writability 52 */ 53 if ( ! function_exists('is_really_writable')) 54 { 55 //該函數和php官方手冊上面寫的差很少,兼容linux/Unix和windows系統: 56 //http://www.php.net/manual/en/function.is-writable.php 57 function is_really_writable($file) 58 { 59 60 //DIRECTORY_SEPARATOR是系統的目錄分割符。利用它的值能夠知道當前是否是linux系統。 61 if (DIRECTORY_SEPARATOR == '/' AND @ini_get("safe_mode") == FALSE) 62 { 63 //若是是linux系統的話,那麼能夠直接調用此方法來判斷文件是否可寫。 64 return is_writable($file); 65 } 66 67 //若是是windows系統,則嘗試寫入一個文件來判斷。 68 69 if (is_dir($file)) 70 { 71 //若是是目錄,則建立一個隨機命名的文件。 72 $file = rtrim($file, '/').'/'.md5(mt_rand(1,100).mt_rand(1,100)); 73 74 //若是文件不能建立,則返回不可寫。 75 if (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE) 76 { 77 return FALSE; 78 } 79 80 fclose($fp); 81 //刪除剛纔的文件。 82 @chmod($file, DIR_WRITE_MODE); 83 @unlink($file); 84 return TRUE; 85 } 86 elseif ( ! is_file($file) OR ($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE) 87 { 88 //若是是一個文件,而經過寫入方式打不開,則返回不可寫。 89 return FALSE; 90 } 91 92 fclose($fp); 93 return TRUE; 94 } 95 } 96 97 // ------------------------------------------------------------------------ 98 99 /** 100 * Class registry 101 */ 102 if ( ! function_exists('load_class')) 103 { 104 //加載類。默認是加載libraries裏面的,若是要加載核心組件,$directory就爲'core' 105 function &load_class($class, $directory = 'libraries', $prefix = 'CI_') 106 { 107 static $_classes = array();//用一個靜態數組,保存已經加載過的類的實例,防止屢次實例消耗資源,實現單例化。 108 109 // Does the class exist? If so, we're done... 110 if (isset($_classes[$class])) 111 { 112 return $_classes[$class];//若是已經保存在這裏,就返回它。 113 } 114 115 $name = FALSE; 116 117 //這裏,若是應用目錄下有和系統目錄下相同的類的話,優先引入應用目錄,也就是你本身定義的。 118 foreach (array(APPPATH, BASEPATH) as $path) 119 { 120 if (file_exists($path.$directory.'/'.$class.'.php')) 121 { 122 $name = $prefix.$class; 123 124 if (class_exists($name) === FALSE) 125 { 126 require($path.$directory.'/'.$class.'.php'); 127 } 128 129 break; 130 } 131 } 132 133 //這裏就用到的前綴擴展,若是在應用目錄相應的目錄下,有本身寫的一些對CI庫的擴展,那麼咱們加載的是它,而不是 134 //原來的。由於咱們寫的擴展是繼承了CI原來的。 135 //因此能夠看出,即便是CI的核心組件(core/下面的)咱們均可覺得之進行擴展。 136 if (file_exists(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php')) 137 { 138 $name = config_item('subclass_prefix').$class; 139 140 if (class_exists($name) === FALSE) 141 { 142 require(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php'); 143 } 144 } 145 146 // Did we find the class? 147 if ($name === FALSE) 148 { 149 //這裏用的是exit();來提示錯誤,而不是用show_error();這是由於這個load_class的錯誤有可能 150 //在加載Exception組件以前發。 151 exit('Unable to locate the specified class: '.$class.'.php'); 152 } 153 154 // Keep track of what we just loaded 155 //這個函數只是用來記錄已經被加載過的類的類名而已。 156 is_loaded($class); 157 158 $_classes[$class] = new $name(); 159 return $_classes[$class]; 160 } 161 } 162 163 // -------------------------------------------------------------------- 164 165 /** 166 * Keeps track of which libraries have been loaded. This function is 167 * called by the load_class() function above 168 */ 169 if ( ! function_exists('is_loaded')) 170 { 171 //記錄有哪些類是已經被加載的。 172 function is_loaded($class = '') 173 { 174 static $_is_loaded = array(); 175 176 if ($class != '') 177 { 178 $_is_loaded[strtolower($class)] = $class; 179 } 180 181 return $_is_loaded; 182 } 183 } 184 185 // ------------------------------------------------------------------------ 186 187 /** 188 * Loads the main config.php file 189 */ 190 if ( ! function_exists('get_config')) 191 { 192 //這個是讀取配置信息的函數,在Config類被實例化以前,由它暫負責。 193 //而在Config類被實例化以前,咱們須要讀取的配置信息,其實僅僅是config.php這個主配置文件的。因此這個方法是不能讀出 194 //config/下其它配置文件的信息的。 195 //這個$replace參數,是提供一個臨時替換配置信息的機會,僅一次,由於執行一次後,配置信息都會保存在靜態變量$_config中,不能 196 //改變。 197 function &get_config($replace = array()) 198 { 199 static $_config; 200 201 if (isset($_config)) 202 { 203 return $_config[0]; 204 } 205 206 // Is the config file in the environment folder? 207 if ( ! defined('ENVIRONMENT') OR ! file_exists($file_path = APPPATH.'config/'.ENVIRONMENT.'/config.php')) 208 { 209 $file_path = APPPATH.'config/config.php'; 210 } 211 212 // Fetch the config file 213 if ( ! file_exists($file_path)) 214 { 215 exit('The configuration file does not exist.'); 216 } 217 218 require($file_path); 219 220 // Does the $config array exist in the file? 221 if ( ! isset($config) OR ! is_array($config)) 222 { 223 exit('Your config file does not appear to be formatted correctly.'); 224 } 225 226 // Are any values being dynamically replaced? 227 if (count($replace) > 0) 228 { 229 foreach ($replace as $key => $val) 230 { 231 if (isset($config[$key])) 232 { 233 $config[$key] = $val; 234 } 235 } 236 } 237 238 return $_config[0] =& $config; 239 } 240 } 241 242 // ------------------------------------------------------------------------ 243 244 /** 245 * Returns the specified config item 246 */ 247 if ( ! function_exists('config_item')) 248 { 249 //取得配置數組中某個元素。 250 function config_item($item) 251 { 252 static $_config_item = array(); 253 254 if ( ! isset($_config_item[$item])) 255 { 256 $config =& get_config(); 257 258 if ( ! isset($config[$item])) 259 { 260 return FALSE; 261 } 262 $_config_item[$item] = $config[$item]; 263 } 264 265 return $_config_item[$item]; 266 } 267 } 268 269 // ------------------------------------------------------------------------ 270 271 /** 272 * Error Handler 273 */ 274 275 //這裏的show_error和下面的show_404以及 _exception_handler這三個錯誤的處理,實質都是由Exception組件完成的。 276 //詳見core/Exception.php. 277 if ( ! function_exists('show_error')) 278 { 279 280 function show_error($message, $status_code = 500, $heading = 'An Error Was Encountered') 281 { 282 $_error =& load_class('Exceptions', 'core'); 283 echo $_error->show_error($heading, $message, 'error_general', $status_code); 284 exit; 285 } 286 } 287 288 // ------------------------------------------------------------------------ 289 290 /** 291 * 404 Page Handler 292 */ 293 if ( ! function_exists('show_404')) 294 { 295 296 function show_404($page = '', $log_error = TRUE) 297 { 298 $_error =& load_class('Exceptions', 'core'); 299 $_error->show_404($page, $log_error); 300 exit; 301 } 302 } 303 304 // ------------------------------------------------------------------------ 305 306 /** 307 * Error Logging Interface 308 */ 309 if ( ! function_exists('log_message')) 310 { 311 function log_message($level = 'error', $message, $php_error = FALSE) 312 { 313 static $_log; 314 315 if (config_item('log_threshold') == 0) 316 { 317 return; 318 } 319 320 $_log =& load_class('Log'); 321 $_log->write_log($level, $message, $php_error); 322 } 323 } 324 325 // ------------------------------------------------------------------------ 326 327 /** 328 * Set HTTP Status Header 329 */ 330 if ( ! function_exists('set_status_header')) 331 { 332 function set_status_header($code = 200, $text = '') 333 { 334 //此函數構造一個響應頭。$stati爲響應碼與其響應說明。 335 $stati = array( 336 200 => 'OK', 337 201 => 'Created', 338 202 => 'Accepted', 339 203 => 'Non-Authoritative Information', 340 204 => 'No Content', 341 205 => 'Reset Content', 342 206 => 'Partial Content', 343 344 300 => 'Multiple Choices', 345 301 => 'Moved Permanently', 346 302 => 'Found', 347 304 => 'Not Modified', 348 305 => 'Use Proxy', 349 307 => 'Temporary Redirect', 350 351 400 => 'Bad Request', 352 401 => 'Unauthorized', 353 403 => 'Forbidden', 354 404 => 'Not Found', 355 405 => 'Method Not Allowed', 356 406 => 'Not Acceptable', 357 407 => 'Proxy Authentication Required', 358 408 => 'Request Timeout', 359 409 => 'Conflict', 360 410 => 'Gone', 361 411 => 'Length Required', 362 412 => 'Precondition Failed', 363 413 => 'Request Entity Too Large', 364 414 => 'Request-URI Too Long', 365 415 => 'Unsupported Media Type', 366 416 => 'Requested Range Not Satisfiable', 367 417 => 'Expectation Failed', 368 369 500 => 'Internal Server Error', 370 501 => 'Not Implemented', 371 502 => 'Bad Gateway', 372 503 => 'Service Unavailable', 373 504 => 'Gateway Timeout', 374 505 => 'HTTP Version Not Supported' 375 ); 376 377 //若是調用此函數自己出錯,則發出一個錯誤。 378 if ($code == '' OR ! is_numeric($code)) 379 { 380 show_error('Status codes must be numeric', 500); 381 } 382 383 if (isset($stati[$code]) AND $text == '') 384 { 385 $text = $stati[$code]; 386 } 387 388 //若是$text爲空,通常是由於調用此函數時,給的響應碼不正確同時又沒有寫出響應報文信息。 389 if ($text == '') 390 { 391 show_error('No status text available. Please check your status code number or supply your own message text.', 500); 392 } 393 394 //取得當前協議。 395 $server_protocol = (isset($_SERVER['SERVER_PROTOCOL'])) ? $_SERVER['SERVER_PROTOCOL'] : FALSE; 396 397 //php_sapi_name()方法能夠得到PHP與服務器之間的接口類型, 398 //下面是以cgi類型和以服務器模塊形式類型的不一樣發出響應的方式。 399 if (substr(php_sapi_name(), 0, 3) == 'cgi') 400 { 401 header("Status: {$code} {$text}", TRUE); 402 } 403 elseif ($server_protocol == 'HTTP/1.1' OR $server_protocol == 'HTTP/1.0') 404 { 405 header($server_protocol." {$code} {$text}", TRUE, $code); 406 } 407 else 408 { 409 header("HTTP/1.1 {$code} {$text}", TRUE, $code); 410 } 411 } 412 } 413 414 // -------------------------------------------------------------------- 415 416 /** 417 * Exception Handler 418 */ 419 if ( ! function_exists('_exception_handler')) 420 { 421 //在CodeIgniter.php中執行set_error_handler('_exception_handler');後,之後一切非致命(非fatal)錯誤信息都由它處理。 422 //觸發錯誤的時候,會產生幾個參數,錯誤級別(號),錯誤信息,錯誤文件,錯誤行。 423 function _exception_handler($severity, $message, $filepath, $line) 424 { 425 /** 426 * 有關錯誤等級的內容可看:http://blog.163.com/wu_guoqing/blog/static/19653701820127269312682/ 427 * E_STRICT對於大多數狀況來講都是沒多大做用的錯誤提示,這裏CI把它屏蔽掉,若是實在要查看,能夠查看日誌文件。 428 */ 429 if ($severity == E_STRICT) 430 { 431 return; 432 } 433 434 //真正起到錯誤處理的是Exception組件。 435 $_error =& load_class('Exceptions', 'core'); 436 437 /* 438 * 注意下面的符號是&而不是&&,php的錯誤等級的值都是有規律的,例如1,2,4,8...(1,10,100,1000)等等,實際上,php是經過位運算來實現的, 439 * 使得錯誤控制更精準。(相似linux的權限控制,rwx) 440 * 在設置error_reporting()的時候,可經過E_XX|E_YY|E_ZZ的形式來設置,而判斷的時候則經過E_XX&error_repoorting()來判斷 441 * E_XX有沒有設置。例如1,10,100,1000相或|,則值爲1111,則之後1,10,100,1000中任意一個與1111相&,值都爲它自己。 442 * 而E_ALL能夠看到是除E_STRICT以外其它等級的「或(|)運算」。我的理解,之因此E_ALL的值是不一樣版本有所不一樣的,是 443 * 由於有時候會加入新的錯誤級別,從而致使這個E_ALL的值也不同。 444 */ 445 if (($severity & error_reporting()) == $severity) 446 { 447 //若是符合則交給Exception組件的show_php_error();進行處理。 448 $_error->show_php_error($severity, $message, $filepath, $line); 449 } 450 451 //下面兩行只是根據配置文件判斷要不要log錯誤信息而已。 452 453 if (config_item('log_threshold') == 0) 454 { 455 return; 456 } 457 458 $_error->log_exception($severity, $message, $filepath, $line); 459 } 460 } 461 462 // -------------------------------------------------------------------- 463 464 /** 465 * Remove Invisible Characters 466 */ 467 if ( ! function_exists('remove_invisible_characters')) 468 { 469 function remove_invisible_characters($str, $url_encoded = TRUE) 470 { 471 $non_displayables = array(); 472 473 // every control character except newline (dec 10) 474 // carriage return (dec 13), and horizontal tab (dec 09) 475 476 if ($url_encoded) 477 { 478 $non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15 479 $non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31 480 } 481 482 $non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S'; // 00-08, 11, 12, 14-31, 127 483 484 do 485 { 486 $str = preg_replace($non_displayables, '', $str, -1, $count); 487 } 488 while ($count); 489 490 return $str; 491 } 492 } 493 494 // ------------------------------------------------------------------------ 495 496 /** 497 * Returns HTML escaped variable 498 */ 499 if ( ! function_exists('html_escape')) 500 { 501 function html_escape($var) 502 { 503 if (is_array($var)) 504 { 505 return array_map('html_escape', $var); 506 } 507 else 508 { 509 return htmlspecialchars($var, ENT_QUOTES, config_item('charset')); 510 } 511 } 512 }