Andrew's Web Libraries (AWL)
Loading...
Searching...
No Matches
AWLUtilities.php
1<?php
12
13if ( !function_exists('dbg_error_log') ) {
29 function dbg_error_log() {
30 global $c, $session;
31 $args = func_get_args();
32 $type = "DBG";
33
34 if (func_num_args() > 1) {
35 $component = array_shift($args);
36 } else {
37 $component = 'UNKNOWN';
38 }
39
40 if ( substr( $component, 0, 3) == "LOG" ) {
41 // Special escape case for stuff that always gets logged.
42 $type = 'LOG';
43 $component = substr($component,4);
44 }
45 else if ( $component == "ERROR" ) {
46 $type = "***";
47 }
48 else if ( isset($c->dbg["ALL"]) ) {
49 $type = "ALL";
50 }
51 else if ( !isset($c->dbg[strtolower($component)]) ) return;
52
53 /* ignore noisy components by setting $c->dbg['foo'] = 0; */
54 if ( isset($c->dbg[strtolower($component)]) && $c->dbg[strtolower($component)] === 0 ) return;
55
56 /* filter by remote IP or logged-in user */
57 if ( isset($c->dbg_filter["remoteIP"]) && !in_array($_SERVER['REMOTE_ADDR'], $c->dbg_filter["remoteIP"]) ) return;
58
59 if ( isset($c->dbg_filter["authenticatedUser"]) ) {
60 if ( !isset($session->username) ) return;
61 if ( !in_array($session->username, $c->dbg_filter["authenticatedUser"]) ) return;
62 }
63
64 # The component isn't always set, if it is then we add a bit of space.
65 if ($component != '') {
66 $component .= ":";
67 }
68
69 if ( count($args) >= 2 ) {
70 $format = array_shift($args);
71 @error_log( sprintf("%s%s: %s: %s%s", $c->sysabbr, request_id_str(),
72 $type, $component, vsprintf($format, $args) ));
73 }
74 else {
75 @error_log( sprintf("%s%s: %s: %s%s", $c->sysabbr, request_id_str(),
76 $type, $component, $args[0] ));
77 }
78 }
79}
80
81
82if ( !function_exists('fatal') ) {
83 function fatal() {
84 global $c;
85 $args = func_get_args();
86 $argc = func_num_args();
87 $request_id_str = request_id_str();
88
89 if ( 2 <= $argc ) {
90 $format = array_shift($args);
91 }
92 else {
93 $format = "%s";
94 }
95
96 @error_log( sprintf("%s%s: FATAL: %s: %s", $c->sysabbr, $request_id_str,
97 $component, vsprintf($format, $args) ));
98
99 @error_log( $request_id_str . "================= Stack Trace ===================" );
100
101 $trace = array_reverse(debug_backtrace());
102 array_pop($trace);
103 foreach( $trace AS $k => $v ) {
104 @error_log( sprintf("%s ===> %s[%d] calls %s%s%s()",
105 $request_id_str,
106 $v['file'],
107 $v['line'],
108 (isset($v['class']) ? $v['class'] : ''),
109 (isset($v['type']) ? $v['type'] : ''),
110 (isset($v['function']) ? $v['function'] : '')
111 ));
112 }
113 echo "Fatal Error";
114 exit();
115 }
116}
117
118
119if ( !function_exists('trace_bug') ) {
123 function trace_bug() {
124 global $c;
125 $args = func_get_args();
126 $argc = func_num_args();
127 $request_id_str = request_id_str();
128
129 if ( 2 <= $argc ) {
130 $format = array_shift($args);
131 }
132 else {
133 $format = "%s";
134 }
135
136 @error_log( $c->sysabbr . $request_id_str . ": BUG: $component:". vsprintf( $format, $args ) );
137
138 @error_log( $request_id_str . "================= Stack Trace ===================" );
139
140 $trace = array_reverse(debug_backtrace());
141 array_pop($trace);
142 foreach( $trace AS $k => $v ) {
143 @error_log( $request_id_str . sprintf(" ===> %s[%d] calls %s%s%s()",
144 $v['file'],
145 $v['line'],
146 (isset($v['class'])?$v['class']:''),
147 (isset($v['type'])?$v['type']:''),
148 (isset($v['function'])?$v['function']:'')
149 ));
150 }
151 }
152}
153
154
155if ( !function_exists('apache_request_headers') ) {
160 eval('
161 function apache_request_headers() {
162 foreach($_SERVER as $key=>$value) {
163 if (substr($key,0,5)=="HTTP_") {
164 $key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
165 $out[$key]=$value;
166 }
167 }
168 return $out;
169 }
170 ');
171}
172
173
174
175if ( !function_exists('dbg_log_array') ) {
184 function dbg_log_array( $component, $name, $arr, $recursive = false ) {
185 if ( !isset($arr) || (gettype($arr) != 'array' && gettype($arr) != 'object') ) {
186 dbg_error_log( $component, "%s: array is not set, or is not an array!", $name);
187 return;
188 }
189 foreach ($arr as $key => $value) {
190 dbg_error_log( $component, "%s: >>%s<< = >>%s<<", $name, $key,
191 (gettype($value) == 'array' || gettype($value) == 'object' ? gettype($value) : $value) );
192 if ( $recursive && (gettype($value) == 'array' || (gettype($value) == 'object' && "$key" != 'self' && "$key" != 'parent') ) ) {
193 dbg_log_array( $component, "$name"."[$key]", $value, $recursive );
194 }
195 }
196 }
197}
198
199
200
201if ( !function_exists("session_simple_md5") ) {
208 function session_simple_md5( $instr ) {
209 global $c;
210 if ( isset($c->dbg['password']) ) dbg_error_log( "Login", "Making plain MD5: instr=$instr, md5($instr)=".md5($instr) );
211 return ( '*MD5*'. md5($instr) );
212 }
213}
214
215
216
217if ( !function_exists("session_salted_md5") ) {
227 function session_salted_md5( $instr, $salt = "" ) {
228 if ( $salt == "" ) $salt = substr( md5(rand(100000,999999)), 2, 8);
229 global $c;
230 if ( isset($c->dbg['password']) ) dbg_error_log( "Login", "Making salted MD5: salt=$salt, instr=$instr, md5($salt$instr)=".md5($salt . $instr) );
231 return ( sprintf("*%s*%s", $salt, md5($salt . $instr) ) );
232 }
233}
234
235
236
237if ( !function_exists("session_salted_sha1") ) {
251 function session_salted_sha1( $instr, $salt = "" ) {
252 if ( $salt == "" ) $salt = substr( str_replace('*','',base64_encode(sha1(rand(100000,9999999),true))), 2, 9);
253 global $c;
254 if ( isset($c->dbg['password']) ) dbg_error_log( "Login", "Making salted SHA1: salt=$salt, instr=$instr, encoded($instr$salt)=".base64_encode(sha1($instr . $salt, true).$salt) );
255 return ( sprintf("*%s*{SSHA}%s", $salt, base64_encode(sha1($instr.$salt, true) . $salt ) ) );
256 }
257}
258
259
260if ( !function_exists("session_validate_password") ) {
261
268 function session_validate_password( $they_sent, $we_have ) {
269 global $c;
270 if ( preg_match('/^\*\*.+$/', $we_have ) ) {
271 // The "forced" style of "**plaintext" to allow easier admin setting
272 return ( "**$they_sent" == $we_have );
273 }
274
275 if ( isset($c->wp_includes) && substring($we_have,0,1) == '$' ) {
276 // Include Wordpress password handling, if it's in the path.
277 @require_once($c->wp_includes .'/class-phpass.php');
278
279 if ( class_exists('PasswordHash') ) {
280 $wp_hasher = new PasswordHash(8, true);
281 return $wp_hasher->CheckPassword($password, $hash);
282 }
283 }
284
285 if ( preg_match('/^\*(.+)\*{[A-Z]+}.+$/', $we_have, $regs ) ) {
286 if ( function_exists("session_salted_sha1") ) {
287 // A nicely salted sha1sum like "*<salt>*{SSHA}<salted_sha1>"
288 $salt = $regs[1];
289 $sha1_sent = session_salted_sha1( $they_sent, $salt ) ;
290 return ( $sha1_sent == $we_have );
291 }
292 else {
293 dbg_error_log( "ERROR", "Password is salted SHA-1 but you are using PHP4!" );
294 echo <<<EOERRMSG
295<html>
296<head>
297<title>Salted SHA1 Password format not supported with PHP4</title>
298</head>
299<body>
300<h1>Salted SHA1 Password format not supported with PHP4</h1>
301<p>At some point you have used PHP5 to set the password for this user and now you are
302 using PHP4. You will need to assign a new password to this user using PHP4, or ensure
303 you use PHP5 everywhere (recommended).</p>
304<p>AWL has now switched to using salted SHA-1 passwords by preference in a format
305 compatible with OpenLDAP.</p>
306</body>
307</html>
308EOERRMSG;
309 exit;
310 }
311 }
312
313 if ( preg_match('/^\*MD5\*.+$/', $we_have, $regs ) ) {
314 // A crappy unsalted md5sum like "*MD5*<md5>"
315 $md5_sent = session_simple_md5( $they_sent ) ;
316 return ( $md5_sent == $we_have );
317 }
318 else if ( preg_match('/^\*(.+)\*.+$/', $we_have, $regs ) ) {
319 // A nicely salted md5sum like "*<salt>*<salted_md5>"
320 $salt = $regs[1];
321 $md5_sent = session_salted_md5( $they_sent, $salt ) ;
322 return ( $md5_sent == $we_have );
323 }
324
325 // Anything else is bad
326 return false;
327
328 }
329}
330
331
332
333if ( !function_exists("replace_uri_params") ) {
341 function replace_uri_params( $uri, $replacements ) {
342 $replaced = $uri;
343 foreach( $replacements AS $param => $new_value ) {
344 $rxp = preg_replace( '/([\‍[\‍]])/', '\\\\$1', $param ); // Some parameters may be arrays.
345 $regex = "/([&?])($rxp)=([^&]+)/";
346 dbg_error_log("core", "Looking for [%s] to replace with [%s] regex is %s and searching [%s]", $param, $new_value, $regex, $replaced );
347 if ( preg_match( $regex, $replaced ) )
348 $replaced = preg_replace( $regex, "\$1$param=$new_value", $replaced);
349 else
350 $replaced .= "&$param=$new_value";
351 }
352 if ( ! preg_match( '/\?/', $replaced ) ) {
353 $replaced = preg_replace("/&(.+)$/", "?\$1", $replaced);
354 }
355 $replaced = str_replace("&amp;", "--AmPeRsAnD--", $replaced);
356 $replaced = str_replace("&", "&amp;", $replaced);
357 $replaced = str_replace("--AmPeRsAnD--", "&amp;", $replaced);
358 dbg_error_log("core", "URI <<$uri>> morphed to <<$replaced>>");
359 return $replaced;
360 }
361}
362
363
364if ( !function_exists("uuid") ) {
393
394 function uuid() {
395
396 // The field names refer to RFC 4122 section 4.1.2
397
398 return sprintf('%04x%04x-%04x-%03x4-%04x-%04x%04x%04x',
399 mt_rand(0, 65535), mt_rand(0, 65535), // 32 bits for "time_low"
400 mt_rand(0, 65535), // 16 bits for "time_mid"
401 mt_rand(0, 4095), // 12 bits before the 0100 of (version) 4 for "time_hi_and_version"
402 bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
403 // 8 bits, the last two of which (positions 6 and 7) are 01, for "clk_seq_hi_res"
404 // (hence, the 2nd hex digit after the 3rd hyphen can only be 1, 5, 9 or d)
405 // 8 bits for "clk_seq_low"
406 mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535) // 48 bits for "node"
407 );
408 }
409}
410
411if ( !function_exists("translate") ) {
412 require("Translation.php");
413}
414
415 if ( !function_exists("clone") && version_compare(phpversion(), '5.0') < 0) {
421 eval( 'function clone($object) { return $object; }' );
422}
423
424if ( !function_exists("quoted_printable_encode") ) {
430 function quoted_printable_encode($string) {
431 return preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n", str_replace("%","=",str_replace("%20"," ",rawurlencode($string))));
432 }
433}
434
435
436if ( !function_exists("check_by_regex") ) {
442 function check_by_regex( $val, $regex ) {
443 if ( is_null($val) ) return null;
444 switch( $regex ) {
445 case 'int': $regex = '#^\d+$#'; break;
446 }
447 if ( is_array($val) ) {
448 foreach( $val AS $k => $v ) {
449 $val[$k] = check_by_regex($v,$regex);
450 }
451 }
452 else if ( ! is_object($val) ) {
453 if ( preg_match( $regex, $val, $matches) ) {
454 $val = $matches[0];
455 }
456 else {
457 $val = '';
458 }
459 }
460 return $val;
461 }
462}
463
464
465if ( !function_exists("param_to_global") ) {
476 function param_to_global( ) {
477 $args = func_get_args();
478
479 $varname = array_shift($args);
480 $GLOBALS[$varname] = null;
481
482 $match_regex = null;
483 $argc = func_num_args();
484 if ( $argc > 1 ) {
485 $match_regex = array_shift($args);
486 }
487
488 $args[] = $varname;
489 foreach( $args AS $k => $name ) {
490 if ( isset($_POST[$name]) ) {
491 $result = $_POST[$name];
492 break;
493 }
494 else if ( isset($_GET[$name]) ) {
495 $result = $_GET[$name];
496 break;
497 }
498 }
499 if ( !isset($result) ) return null;
500
501 if ( isset($match_regex) ) {
502 $result = check_by_regex( $result, $match_regex );
503 }
504
505 $GLOBALS[$varname] = $result;
506 return $result;
507 }
508}
509
510
511if ( !function_exists("awl_get_fields") ) {
515 $_AWL_field_cache = array();
516
522 function awl_get_fields( $tablename ) {
523 global $_AWL_field_cache;
524
525 if ( !isset($_AWL_field_cache[$tablename]) ) {
526 dbg_error_log( "core", ":awl_get_fields: Loading fields for table '$tablename'" );
527 $qry = new AwlQuery();
528 $db = $qry->GetConnection();
529 $qry->SetSQL($db->GetFields($tablename));
530 $qry->Exec("core");
531 $fields = array();
532 while( $row = $qry->Fetch() ) {
533 $fields[$row->fieldname] = $row->typename . ($row->precision >= 0 ? sprintf('(%d)',$row->precision) : '');
534 }
535 $_AWL_field_cache[$tablename] = $fields;
536 }
537 return $_AWL_field_cache[$tablename];
538 }
539}
540
541
542if ( !function_exists("force_utf8") ) {
543 function define_byte_mappings() {
544 global $byte_map, $nibble_good_chars;
545
546 # Needed for using Grant McLean's byte mappings code
547 $ascii_char = '[\x00-\x7F]';
548 $cont_byte = '[\x80-\xBF]';
549
550 $utf8_2 = '[\xC0-\xDF]' . $cont_byte;
551 $utf8_3 = '[\xE0-\xEF]' . $cont_byte . '{2}';
552 $utf8_4 = '[\xF0-\xF7]' . $cont_byte . '{3}';
553 $utf8_5 = '[\xF8-\xFB]' . $cont_byte . '{4}';
554
555 $nibble_good_chars = "/^($ascii_char+|$utf8_2|$utf8_3|$utf8_4|$utf8_5)(.*)$/s";
556
557 # From http://unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT
558 $byte_map = array(
559 "\x80" => "\xE2\x82\xAC", # EURO SIGN
560 "\x82" => "\xE2\x80\x9A", # SINGLE LOW-9 QUOTATION MARK
561 "\x83" => "\xC6\x92", # LATIN SMALL LETTER F WITH HOOK
562 "\x84" => "\xE2\x80\x9E", # DOUBLE LOW-9 QUOTATION MARK
563 "\x85" => "\xE2\x80\xA6", # HORIZONTAL ELLIPSIS
564 "\x86" => "\xE2\x80\xA0", # DAGGER
565 "\x87" => "\xE2\x80\xA1", # DOUBLE DAGGER
566 "\x88" => "\xCB\x86", # MODIFIER LETTER CIRCUMFLEX ACCENT
567 "\x89" => "\xE2\x80\xB0", # PER MILLE SIGN
568 "\x8A" => "\xC5\xA0", # LATIN CAPITAL LETTER S WITH CARON
569 "\x8B" => "\xE2\x80\xB9", # SINGLE LEFT-POINTING ANGLE QUOTATION MARK
570 "\x8C" => "\xC5\x92", # LATIN CAPITAL LIGATURE OE
571 "\x8E" => "\xC5\xBD", # LATIN CAPITAL LETTER Z WITH CARON
572 "\x91" => "\xE2\x80\x98", # LEFT SINGLE QUOTATION MARK
573 "\x92" => "\xE2\x80\x99", # RIGHT SINGLE QUOTATION MARK
574 "\x93" => "\xE2\x80\x9C", # LEFT DOUBLE QUOTATION MARK
575 "\x94" => "\xE2\x80\x9D", # RIGHT DOUBLE QUOTATION MARK
576 "\x95" => "\xE2\x80\xA2", # BULLET
577 "\x96" => "\xE2\x80\x93", # EN DASH
578 "\x97" => "\xE2\x80\x94", # EM DASH
579 "\x98" => "\xCB\x9C", # SMALL TILDE
580 "\x99" => "\xE2\x84\xA2", # TRADE MARK SIGN
581 "\x9A" => "\xC5\xA1", # LATIN SMALL LETTER S WITH CARON
582 "\x9B" => "\xE2\x80\xBA", # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
583 "\x9C" => "\xC5\x93", # LATIN SMALL LIGATURE OE
584 "\x9E" => "\xC5\xBE", # LATIN SMALL LETTER Z WITH CARON
585 "\x9F" => "\xC5\xB8", # LATIN CAPITAL LETTER Y WITH DIAERESIS
586 );
587
588 for( $i=160; $i < 256; $i++ ) {
589 $ch = chr($i);
590 $byte_map[$ch] = iconv('ISO-8859-1', 'UTF-8', $ch);
591 }
592 }
593 define_byte_mappings();
594
595 function force_utf8( $input ) {
596 global $byte_map, $nibble_good_chars;
597
598 $output = '';
599 $char = '';
600 $rest = '';
601 while( $input != '' ) {
602 if ( preg_match( $nibble_good_chars, $input, $matches ) ) {
603 $output .= $matches[1];
604 $rest = $matches[2];
605 }
606 else {
607 preg_match( '/^(.)(.*)$/s', $input, $matches );
608 $char = $matches[1];
609 $rest = $matches[2];
610 if ( isset($byte_map[$char]) ) {
611 $output .= $byte_map[$char];
612 }
613 else {
614 # Must be valid UTF8 already
615 $output .= $char;
616 }
617 }
618 $input = $rest;
619 }
620 return $output;
621 }
622
623}
624
625
626$timezone_identifiers_list_cache = timezone_identifiers_list() ?: [];
627
631function olson_from_tzstring( $tzstring ) {
632 global $c, $timezone_identifiers_list_cache;
633
634 if ( !isset($timezone_identifiers_list_cache) ) {
635 $timezone_identifiers_list_cache = timezone_identifiers_list() ?: [];
636 }
637 if ( in_array($tzstring,$timezone_identifiers_list_cache) ) return $tzstring;
638
639 if ( preg_match( '{((Antarctica|America|Africa|Atlantic|Asia|Australia|Indian|Europe|Pacific)/(([^/]+)/)?[^/]+)$}', $tzstring, $matches ) ) {
640// dbg_error_log( 'INFO', 'Found timezone "%s" from string "%s"', $matches[1], $tzstring );
641 return $matches[1];
642 }
643 switch( $tzstring ) {
644 case 'New Zealand Standard Time': case 'New Zealand Daylight Time':
645 return 'Pacific/Auckland';
646 break;
647 case 'Central Standard Time': case 'Central Daylight Time': case 'US/Central':
648 return 'America/Chicago';
649 break;
650 case 'Eastern Standard Time': case 'Eastern Daylight Time': case 'US/Eastern':
651 case '(UTC-05:00) Eastern Time (US & Canada)':
652 return 'America/New_York';
653 break;
654 case 'Pacific Standard Time': case 'Pacific Daylight Time': case 'US/Pacific':
655 return 'America/Los_Angeles';
656 break;
657 case 'Mountain Standard Time': case 'Mountain Daylight Time': case 'US/Mountain': case 'Mountain Time':
658 return 'America/Denver';
659 // The US 'Mountain Time' can in fact be America/(Denver|Boise|Phoenix|Shiprock) which
660 // all vary to some extent due to differing DST rules.
661 break;
662 case '(GMT-07.00) Arizona':
663 return 'America/Phoenix';
664 break;
665 default:
666 if ( isset($c->timezone_translations) && is_array($c->timezone_translations)
667 && !empty($c->timezone_translations[$tzstring]) )
668 return $c->timezone_translations[$tzstring];
669 }
670 return null;
671}
672
673if ( !function_exists("deprecated") ) {
674 function deprecated( $method ) {
675 global $c;
676 $request_id_str = request_id_str();
677
678 if ( isset($c->dbg['ALL']) || isset($c->dbg['deprecated']) ) {
679 $stack = debug_backtrace();
680 array_shift($stack);
681
682 if ( preg_match( '{/inc/iCalendar.php$}', $stack[0]['file'] ) && $stack[0]['line'] > __LINE__ ) return;
683 @error_log( sprintf( '%s%s: DEPRECATED: Call to deprecated method "%s"',
684 $c->sysabbr, $request_id_str, $method));
685 foreach( $stack AS $k => $v ) {
686 @error_log( sprintf( '%s%s: ==> called from line %4d of %s',
687 $c->sysabbr, $request_id_str, $v['line'], $v['file']));
688 }
689 }
690 }
691}
692
693
694if ( !function_exists("gzdecode") ) {
695 function gzdecode( $instring ) {
696 global $c;
697 if ( !isset($c->use_pipe_gunzip) || $c->use_pipe_gunzip ) {
698 $descriptorspec = array(
699 0 => array("pipe", "r"), // stdin is a pipe that the child will read from
700 1 => array("pipe", "w"), // stdout is a pipe that the child will write to
701 2 => array("file", "/dev/null", "a") // stderr is discarded
702 );
703 $process = proc_open('gunzip',$descriptorspec, $pipes);
704 if ( is_resource($process) ) {
705 fwrite($pipes[0],$instring);
706 fclose($pipes[0]);
707
708 $outstring = stream_get_contents($pipes[1]);
709 fclose($pipes[1]);
710
711 proc_close($process);
712 return $outstring;
713 }
714 return '';
715 }
716 else {
717 $g=tempnam('./','gz');
718 file_put_contents($g,$instring);
719 ob_start();
720 readgzfile($g);
721 $d=ob_get_clean();
722 unlink($g);
723 return $d;
724 }
725 }
726}
727
728if ( !function_exists("request_id") ) {
729 function request_id() {
730 global $c;
731
732 if (isset($c->request_id))
733 return $c->request_id;
734
735 if (isset($_SERVER['UNIQUE_ID'])) {
736 # Use what Apache2 has provided.
737 $c->request_id = $_SERVER['UNIQUE_ID'];
738
739 } else if (isset($_SERVER['REQUEST_ID'])) {
740 # Use what the web server (nginx only?) has provided.
741 $c->request_id = $_SERVER['REQUEST_ID'];
742
743 } else if (isset($_SERVER['REQUEST_METHOD'])) {
744 # Make up an ID that should do the job.
745 $c->request_id = hash('crc32b', (
746 $_SERVER['REMOTE_ADDR'] .
747 $_SERVER['REQUEST_TIME_FLOAT'] .
748 $_SERVER['REMOTE_PORT']
749 ));
750
751 } else {
752 # probably run from a CLI, don't need a request ID.
753 $c->request_id = '';
754 }
755
756 return $c->request_id;
757 }
758
759 function request_id_str() {
760 global $c;
761
762 $request_id_str = '';
763 $request_id = request_id();
764
765 if (isset($request_id) && $request_id != '') {
766 $request_id_str = ": " . $request_id;
767 }
768
769 return $request_id_str;
770 }
771}
772
776function awl_version() {
777 global $c;
778 $c->awl_library_version = 0.65;
779 return $c->awl_library_version;
780}