-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcommon.html
810 lines (652 loc) · 21 KB
/
common.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/shCore.css">
<link rel="stylesheet" href="css/shThemeDefault.css">
<script src="js/shCore.js"></script>
<script src="js/shBrushPhp.js"></script>
</head>
<body>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<div class='alert alert-success'>
我們開始分析Common.php。<br />
它包含了整個application常用到的一些全域函數。
</div>
<div class='alert alert-danger'>
注意這整份檔案的一個pattern:<br/>
它全都會用if ( ! function_exists('xxx'))來確認函數是否被定義過。<br/>
原作者群試圖進行防禦性編程。我認為沒必要、這是bad practice。<br/>
整個system的製作團隊自己要清楚哪些函數被定義過、又是在哪被定義。用這種防禦性編程是在逃避架構不清的問題。<br/>
況且,若是真已被定義過,卻是目的不同的定義,那整個system會crash或是很buggy。<br/>
再不然,根本不應該寫成全域函數,而應該以class封裝好,甚至是使用namespace<br/>
結果整個system都沒有namespace,這也是我們說CI過時了的一個原因。<br/>
這個pattern在helper內也有出現。
</div>
<pre class="brush: php">
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* Common Functions
*
* Loads the base classes and executes the request.
*
* @package CodeIgniter
* @subpackage codeigniter
* @category Common Functions
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/
*/
// ------------------------------------------------------------------------
/**
* Determines if the current version of PHP is greater then the supplied value
*
* Since there are a few places where we conditionally test for PHP > 5
* we'll set a static variable.
*
* @access public
* @param string
* @return bool TRUE if the current version is $version or higher
*/
if ( ! function_exists('is_php'))
{
function is_php($version = '5.0.0')
{
static $_is_php;
$version = (string)$version;
if ( ! isset($_is_php[$version]))
{
$_is_php[$version] = (version_compare(PHP_VERSION, $version) < 0) ? FALSE : TRUE;
}
return $_is_php[$version];
}
}
</pre>
<div class='alert alert-success'>
之後某些功能針對不同版本有不同寫法,為了方便比較,建立一個is_php全域函數。<br/>
注意此處用了 static 宣告靜態變數。這讓$_is_php陣列內的值能作為暫存,不用每次都去執行運算。<br/>
</div>
<div class='alert alert-danger'>
注意這邊有一個函數叫做version_compare。它不過就是字串比較而已。<br/>
我想這就是PHP的一個特色:什麼鬼函數都有。<br/>
有些人熱愛PHP提供了各種功能;有些人覺得這沒什麼品味。
</div>
<pre class="brush: php">
// ------------------------------------------------------------------------
/**
* Tests for file writability
*
* is_writable() returns TRUE on Windows servers when you really can't write to
* the file, based on the read-only attribute. is_writable() is also unreliable
* on Unix servers if safe_mode is on.
*
* @access private
* @return void
*/
if ( ! function_exists('is_really_writable'))
{
function is_really_writable($file)
{
// If we're on a Unix server with safe_mode off we call is_writable
if (DIRECTORY_SEPARATOR == '/' AND @ini_get("safe_mode") == FALSE)
{
return is_writable($file);
}
// For windows servers and safe_mode "on" installations we'll actually
// write a file then read it. Bah...
if (is_dir($file))
{
$file = rtrim($file, '/').'/'.md5(mt_rand(1,100).mt_rand(1,100));
if (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE)
{
return FALSE;
}
fclose($fp);
@chmod($file, DIR_WRITE_MODE);
@unlink($file);
return TRUE;
}
elseif ( ! is_file($file) OR ($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE)
{
return FALSE;
}
fclose($fp);
return TRUE;
}
}
</pre>
<div class='alert alert-success'>
php內建函數is_writable會根據一個檔案的權限判斷是否可寫入。<br/>
不幸的,若是php.ini定義了安全模式,is_writable判斷可寫入的未必真的可寫入。<br/>
這邊使用了DIRECTORY_SEPARATOR來判斷作業系統。<br/>
在Windows作業系統也有一些屬性要判斷,實作比較複雜:<br/>
若是資料夾,就試著在裡面建立一個檔案,建立了卻不能讀取就是不可寫入。
</div>
<div class='alert alert-danger'>
PHP不是包山包海,什麼功能都有提供嗎?怎麼這個深入確認的函數卻是要framework自己提供呀。
</div>
<pre class="brush: php">
// ------------------------------------------------------------------------
/**
* Class registry
*
* This function acts as a singleton. If the requested class does not
* exist it is instantiated and set to a static variable. If it has
* previously been instantiated the variable is returned.
*
* @access public
* @param string the class name being requested
* @param string the directory where the class should be found
* @param string the class name prefix
* @return object
*/
if ( ! function_exists('load_class'))
{
function &load_class($class, $directory = 'libraries', $prefix = 'CI_')
{
static $_classes = array();
// Does the class exist? If so, we're done...
if (isset($_classes[$class]))
{
return $_classes[$class];
}
$name = FALSE;
// Look for the class first in the local application/libraries folder
// then in the native system/libraries folder
foreach (array(APPPATH, BASEPATH) as $path)
{
if (file_exists($path.$directory.'/'.$class.'.php'))
{
$name = $prefix.$class;
if (class_exists($name) === FALSE)
{
require($path.$directory.'/'.$class.'.php');
}
break;
}
}
// Is the request a class extension? If so we load it too
if (file_exists(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php'))
{
$name = config_item('subclass_prefix').$class;
if (class_exists($name) === FALSE)
{
require(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php');
}
}
// Did we find the class?
if ($name === FALSE)
{
// Note: We use exit() rather then show_error() in order to avoid a
// self-referencing loop with the Excptions class
exit('Unable to locate the specified class: '.$class.'.php');
}
// Keep track of what we just loaded
is_loaded($class);
$_classes[$class] = new $name();
return $_classes[$class];
}
}
</pre>
<div class='alert alert-success'>
重頭戲來了,CI利用這個函數將幾乎所有核心類別載入。<br/>
也正是因為這個函數,你在其他地方幾乎看不到require或是include函數。<br/>
注意函數前面有一個&符號,表示pass by reference。<br/>
此處用了static靜態變數來做到儲存,並且會呼叫下面的is_load函數紀錄已經載入的類別。
</div>
<div class='alert alert-danger'>
用全域函數來逐步載入元件,然後紀錄在另一個全域函數的的靜態變數裡面?<br/>
我認為這真的超怪異,這應該寫成一個類別吧!<br/>
會寫成這樣,我認為是最一開始設計時沒有思考清楚系統該如何抽象化。
</div>
<div class='alert alert-danger'>
注意這邊自訂載入函數的一個重大代價:沒辦法在new一個物件時,傳入任何參數(看看倒數幾行的new相關程式碼)。<br/>
也就是PHP程式語言為了支援OOP所提供的類別construtor功能,被全面放棄了!
</div>
<pre class="brush: php">
// --------------------------------------------------------------------
/**
* Keeps track of which libraries have been loaded. This function is
* called by the load_class() function above
*
* @access public
* @return array
*/
if ( ! function_exists('is_loaded'))
{
function &is_loaded($class = '')
{
static $_is_loaded = array();
if ($class != '')
{
$_is_loaded[strtolower($class)] = $class;
}
return $_is_loaded;
}
}
</pre>
<div class='alert alert-success'>
這就是剛剛所說,利用靜態變數做紀錄的函數。
</div>
<div class='alert alert-danger'>
看到這邊,我個人感覺這像是一大串quick and dirty solution的組合。<br/>
繼續往下看,你會發現CI真的用了很多全域函數。<br/>
我認為這是procedural programming的一個徵兆:一堆到處用的全域函數。<br/>
這也是很多人批評CI一點也不OOP的一個地方。<br/>
我個人是覺得獨立function根本不應該有靜態變數。函數還有狀態真的很怪。
</div>
<pre class="brush: php">
// ------------------------------------------------------------------------
/**
* Loads the main config.php file
*
* This function lets us grab the config file even if the Config class
* hasn't been instantiated yet
*
* @access private
* @return array
*/
if ( ! function_exists('get_config'))
{
function &get_config($replace = array())
{
static $_config;
if (isset($_config))
{
return $_config[0];
}
// Is the config file in the environment folder?
if ( ! defined('ENVIRONMENT') OR ! file_exists($file_path = APPPATH.'config/'.ENVIRONMENT.'/config.php'))
{
$file_path = APPPATH.'config/config.php';
}
// Fetch the config file
if ( ! file_exists($file_path))
{
exit('The configuration file does not exist.');
}
require($file_path);
// Does the $config array exist in the file?
if ( ! isset($config) OR ! is_array($config))
{
exit('Your config file does not appear to be formatted correctly.');
}
// Are any values being dynamically replaced?
if (count($replace) > 0)
{
foreach ($replace as $key => $val)
{
if (isset($config[$key]))
{
$config[$key] = $val;
}
}
}
return $_config[0] =& $config;
}
}
</pre>
<div class='alert alert-success'>
</div>
<div class='alert alert-danger'>
</div>
<pre class="brush: php">
// ------------------------------------------------------------------------
/**
* Returns the specified config item
*
* @access public
* @return mixed
*/
if ( ! function_exists('config_item'))
{
function config_item($item)
{
static $_config_item = array();
if ( ! isset($_config_item[$item]))
{
$config =& get_config();
if ( ! isset($config[$item]))
{
return FALSE;
}
$_config_item[$item] = $config[$item];
}
return $_config_item[$item];
}
}
</pre>
<div class='alert alert-success'>
</div>
<div class='alert alert-danger'>
</div>
<pre class="brush: php">
// ------------------------------------------------------------------------
/**
* Error Handler
*
* This function lets us invoke the exception class and
* display errors using the standard error template located
* in application/errors/errors.php
* This function will send the error page directly to the
* browser and exit.
*
* @access public
* @return void
*/
if ( ! function_exists('show_error'))
{
function show_error($message, $status_code = 500, $heading = 'An Error Was Encountered')
{
$_error =& load_class('Exceptions', 'core');
echo $_error->show_error($heading, $message, 'error_general', $status_code);
exit;
}
}
</pre>
<div class='alert alert-success'>
用來顯示錯誤訊息的函數。有了它,在任何地方都可以利用show_error來顯示錯誤、debug也很方便。<br/>
少數我覺得全域函數幹得好的地方。
</div>
<div class='alert alert-danger'>
注意這個函數跟其他函數有相依性,囧。
</div>
<pre class="brush: php">
// ------------------------------------------------------------------------
/**
* 404 Page Handler
*
* This function is similar to the show_error() function above
* However, instead of the standard error template it displays
* 404 errors.
*
* @access public
* @return void
*/
if ( ! function_exists('show_404'))
{
function show_404($page = '', $log_error = TRUE)
{
$_error =& load_class('Exceptions', 'core');
$_error->show_404($page, $log_error);
exit;
}
}
</pre>
<div class='alert alert-success'>
跟show_error函數差不多。
</div>
<pre class="brush: php">
// ------------------------------------------------------------------------
/**
* Error Logging Interface
*
* We use this as a simple mechanism to access the logging
* class and send messages to be logged.
*
* @access public
* @return void
*/
if ( ! function_exists('log_message'))
{
function log_message($level = 'error', $message, $php_error = FALSE)
{
static $_log;
if (config_item('log_threshold') == 0)
{
return;
}
$_log =& load_class('Log');
$_log->write_log($level, $message, $php_error);
}
}
</pre>
<div class='alert alert-success'>
用來log訊息的函數。
</div>
<pre class="brush: php">
// ------------------------------------------------------------------------
/**
* Set HTTP Status Header
*
* @access public
* @param int the status code
* @param string
* @return void
*/
if ( ! function_exists('set_status_header'))
{
function set_status_header($code = 200, $text = '')
{
$stati = array(
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported'
);
if ($code == '' OR ! is_numeric($code))
{
show_error('Status codes must be numeric', 500);
}
if (isset($stati[$code]) AND $text == '')
{
$text = $stati[$code];
}
if ($text == '')
{
show_error('No status text available. Please check your status code number or supply your own message text.', 500);
}
$server_protocol = (isset($_SERVER['SERVER_PROTOCOL'])) ? $_SERVER['SERVER_PROTOCOL'] : FALSE;
if (substr(php_sapi_name(), 0, 3) == 'cgi')
{
header("Status: {$code} {$text}", TRUE);
}
elseif ($server_protocol == 'HTTP/1.1' OR $server_protocol == 'HTTP/1.0')
{
header($server_protocol." {$code} {$text}", TRUE, $code);
}
else
{
header("HTTP/1.1 {$code} {$text}", TRUE, $code);
}
}
}
</pre>
<div class='alert alert-success'>
</div>
<div class='alert alert-danger'>
</div>
<pre class="brush: php">
// --------------------------------------------------------------------
/**
* Exception Handler
*
* This is the custom exception handler that is declaired at the top
* of Codeigniter.php. The main reason we use this is to permit
* PHP errors to be logged in our own log files since the user may
* not have access to server logs. Since this function
* effectively intercepts PHP errors, however, we also need
* to display errors based on the current error_reporting level.
* We do that with the use of a PHP error template.
*
* @access private
* @return void
*/
if ( ! function_exists('_exception_handler'))
{
function _exception_handler($severity, $message, $filepath, $line)
{
// We don't bother with "strict" notices since they tend to fill up
// the log file with excess information that isn't normally very helpful.
// For example, if you are running PHP 5 and you use version 4 style
// class functions (without prefixes like "public", "private", etc.)
// you'll get notices telling you that these have been deprecated.
if ($severity == E_STRICT)
{
return;
}
$_error =& load_class('Exceptions', 'core');
// Should we display the error? We'll get the current error_reporting
// level and add its bits with the severity bits to find out.
if (($severity & error_reporting()) == $severity)
{
$_error->show_php_error($severity, $message, $filepath, $line);
}
// Should we log the error? No? We're done...
if (config_item('log_threshold') == 0)
{
return;
}
$_error->log_exception($severity, $message, $filepath, $line);
}
}
</pre>
<div class='alert alert-success'>
</div>
<div class='alert alert-danger'>
</div>
<pre class="brush: php">
// --------------------------------------------------------------------
/**
* Remove Invisible Characters
*
* This prevents sandwiching null characters
* between ascii characters, like Java\0script.
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('remove_invisible_characters'))
{
function remove_invisible_characters($str, $url_encoded = TRUE)
{
$non_displayables = array();
// every control character except newline (dec 10)
// carriage return (dec 13), and horizontal tab (dec 09)
if ($url_encoded)
{
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
}
$non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S'; // 00-08, 11, 12, 14-31, 127
do
{
$str = preg_replace($non_displayables, '', $str, -1, $count);
}
while ($count);
return $str;
}
}
</pre>
<div class='alert alert-success'>
</div>
<div class='alert alert-danger'>
</div>
<pre class="brush: php">
// ------------------------------------------------------------------------
/**
* Returns HTML escaped variable
*
* @access public
* @param mixed
* @return mixed
*/
if ( ! function_exists('html_escape'))
{
function html_escape($var)
{
if (is_array($var))
{
return array_map('html_escape', $var);
}
else
{
return htmlspecialchars($var, ENT_QUOTES, config_item('charset'));
}
}
}
/* End of file Common.php */
/* Location: ./system/core/Common.php */
</pre>
<div class='alert alert-success'>
用來強化PHP內建htmlspecialchars函數的函數。<br/>
可以轉換整個陣列內的字串。<br />
注意到array_map跟htmlspecialchars這兩個內建函數了嗎?PHP內建的函數可是包山包海。
</div>
<!-- Finally, to actually run the highlighter, you need to include this JS on your page -->
<script type="text/javascript">
SyntaxHighlighter.all()
</script>
</body>
<style>
body{
width: 960px;
margin: 0 auto;
background-color: #444;
}
.alert{
line-height: 2;
}
</style>
</html>