Andrew's Web Libraries (AWL)
AWLUtilities.php
1<?php
13if ( !function_exists('dbg_error_log') ) {
29 function dbg_error_log() {
30 global $c, $session;
31 $args = func_get_args();
32 $type = "DBG";
33 if (func_num_args() > 1) {
34 $component = array_shift($args);
35 } else {
36 $component = 'UNKNOWN';
37 }
38 if ( substr( $component, 0, 3) == "LOG" ) {
39 // Special escape case for stuff that always gets logged.
40 $type = 'LOG';
41 $component = substr($component,4);
42 }
43 else if ( $component == "ERROR" ) {
44 $type = "***";
45 }
46 else if ( isset($c->dbg["ALL"]) ) {
47 $type = "ALL";
48 }
49 else if ( !isset($c->dbg[strtolower($component)]) ) return;
50
51 /* ignore noisy components by setting $c->dbg['foo'] = 0; */
52 if ( isset($c->dbg[strtolower($component)]) && $c->dbg[strtolower($component)] === 0 ) return;
53
54 /* filter by remote IP or logged-in user */
55 if ( isset($c->dbg_filter["remoteIP"]) && !in_array($_SERVER['REMOTE_ADDR'], $c->dbg_filter["remoteIP"]) ) return;
56 if ( isset($c->dbg_filter["authenticatedUser"]) ) {
57 if ( !isset($session->username) ) return;
58 if ( !in_array($session->username, $c->dbg_filter["authenticatedUser"]) ) return;
59 }
60
61 if ( count($args) >= 2 ) {
62 $format = array_shift($args);
63 @error_log( $c->sysabbr.": $type: $component:". vsprintf( $format, $args ) );
64 }
65 else {
66 @error_log( $c->sysabbr.": $type: $component:" . $args[0]);
67 }
68 }
69}
70
71
72if ( !function_exists('fatal') ) {
73 function fatal() {
74 global $c;
75 $args = func_get_args();
76 $argc = func_num_args();
77 if ( 2 <= $argc ) {
78 $format = array_shift($args);
79 }
80 else {
81 $format = "%s";
82 }
83 @error_log( $c->sysabbr.": FATAL: $component:". vsprintf( $format, $args ) );
84
85 @error_log( "================= Stack Trace ===================" );
86
87 $trace = array_reverse(debug_backtrace());
88 array_pop($trace);
89 foreach( $trace AS $k => $v ) {
90 @error_log( sprintf(" ===> %s[%d] calls %s%s%s()",
91 $v['file'],
92 $v['line'],
93 (isset($v['class'])?$v['class']:''),
94 (isset($v['type'])?$v['type']:''),
95 (isset($v['function'])?$v['function']:'')
96 ));
97 }
98 echo "Fatal Error";
99 exit();
100 }
101}
102
103
104if ( !function_exists('trace_bug') ) {
108 function trace_bug() {
109 global $c;
110 $args = func_get_args();
111 $argc = func_num_args();
112 if ( 2 <= $argc ) {
113 $format = array_shift($args);
114 }
115 else {
116 $format = "%s";
117 }
118 @error_log( $c->sysabbr.": BUG: $component:". vsprintf( $format, $args ) );
119
120 @error_log( "================= Stack Trace ===================" );
121
122 $trace = array_reverse(debug_backtrace());
123 array_pop($trace);
124 foreach( $trace AS $k => $v ) {
125 @error_log( sprintf(" ===> %s[%d] calls %s%s%s()",
126 $v['file'],
127 $v['line'],
128 (isset($v['class'])?$v['class']:''),
129 (isset($v['type'])?$v['type']:''),
130 (isset($v['function'])?$v['function']:'')
131 ));
132 }
133 }
134}
135
136
137if ( !function_exists('apache_request_headers') ) {
142 eval('
143 function apache_request_headers() {
144 foreach($_SERVER as $key=>$value) {
145 if (substr($key,0,5)=="HTTP_") {
146 $key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
147 $out[$key]=$value;
148 }
149 }
150 return $out;
151 }
152 ');
153}
154
155
156
157if ( !function_exists('dbg_log_array') ) {
166 function dbg_log_array( $component, $name, $arr, $recursive = false ) {
167 if ( !isset($arr) || (gettype($arr) != 'array' && gettype($arr) != 'object') ) {
168 dbg_error_log( $component, "%s: array is not set, or is not an array!", $name);
169 return;
170 }
171 foreach ($arr as $key => $value) {
172 dbg_error_log( $component, "%s: >>%s<< = >>%s<<", $name, $key,
173 (gettype($value) == 'array' || gettype($value) == 'object' ? gettype($value) : $value) );
174 if ( $recursive && (gettype($value) == 'array' || (gettype($value) == 'object' && "$key" != 'self' && "$key" != 'parent') ) ) {
175 dbg_log_array( $component, "$name"."[$key]", $value, $recursive );
176 }
177 }
178 }
179}
180
181
182
183if ( !function_exists("session_simple_md5") ) {
190 function session_simple_md5( $instr ) {
191 global $c;
192 if ( isset($c->dbg['password']) ) dbg_error_log( "Login", "Making plain MD5: instr=$instr, md5($instr)=".md5($instr) );
193 return ( '*MD5*'. md5($instr) );
194 }
195}
196
197
198
199if ( !function_exists("session_salted_md5") ) {
209 function session_salted_md5( $instr, $salt = "" ) {
210 if ( $salt == "" ) $salt = substr( md5(rand(100000,999999)), 2, 8);
211 global $c;
212 if ( isset($c->dbg['password']) ) dbg_error_log( "Login", "Making salted MD5: salt=$salt, instr=$instr, md5($salt$instr)=".md5($salt . $instr) );
213 return ( sprintf("*%s*%s", $salt, md5($salt . $instr) ) );
214 }
215}
216
217
218
219if ( !function_exists("session_salted_sha1") ) {
233 function session_salted_sha1( $instr, $salt = "" ) {
234 if ( $salt == "" ) $salt = substr( str_replace('*','',base64_encode(sha1(rand(100000,9999999),true))), 2, 9);
235 global $c;
236 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) );
237 return ( sprintf("*%s*{SSHA}%s", $salt, base64_encode(sha1($instr.$salt, true) . $salt ) ) );
238 }
239}
240
241
242if ( !function_exists("session_validate_password") ) {
243
250 function session_validate_password( $they_sent, $we_have ) {
251 global $c;
252 if ( preg_match('/^\*\*.+$/', $we_have ) ) {
253 // The "forced" style of "**plaintext" to allow easier admin setting
254 return ( "**$they_sent" == $we_have );
255 }
256
257 if ( isset($c->wp_includes) && substring($we_have,0,1) == '$' ) {
258 // Include Wordpress password handling, if it's in the path.
259 @require_once($c->wp_includes .'/class-phpass.php');
260
261 if ( class_exists('PasswordHash') ) {
262 $wp_hasher = new PasswordHash(8, true);
263 return $wp_hasher->CheckPassword($password, $hash);
264 }
265 }
266
267 if ( preg_match('/^\*(.+)\*{[A-Z]+}.+$/', $we_have, $regs ) ) {
268 if ( function_exists("session_salted_sha1") ) {
269 // A nicely salted sha1sum like "*<salt>*{SSHA}<salted_sha1>"
270 $salt = $regs[1];
271 $sha1_sent = session_salted_sha1( $they_sent, $salt ) ;
272 return ( $sha1_sent == $we_have );
273 }
274 else {
275 dbg_error_log( "ERROR", "Password is salted SHA-1 but you are using PHP4!" );
276 echo <<<EOERRMSG
277<html>
278<head>
279<title>Salted SHA1 Password format not supported with PHP4</title>
280</head>
281<body>
282<h1>Salted SHA1 Password format not supported with PHP4</h1>
283<p>At some point you have used PHP5 to set the password for this user and now you are
284 using PHP4. You will need to assign a new password to this user using PHP4, or ensure
285 you use PHP5 everywhere (recommended).</p>
286<p>AWL has now switched to using salted SHA-1 passwords by preference in a format
287 compatible with OpenLDAP.</p>
288</body>
289</html>
290EOERRMSG;
291 exit;
292 }
293 }
294
295 if ( preg_match('/^\*MD5\*.+$/', $we_have, $regs ) ) {
296 // A crappy unsalted md5sum like "*MD5*<md5>"
297 $md5_sent = session_simple_md5( $they_sent ) ;
298 return ( $md5_sent == $we_have );
299 }
300 else if ( preg_match('/^\*(.+)\*.+$/', $we_have, $regs ) ) {
301 // A nicely salted md5sum like "*<salt>*<salted_md5>"
302 $salt = $regs[1];
303 $md5_sent = session_salted_md5( $they_sent, $salt ) ;
304 return ( $md5_sent == $we_have );
305 }
306
307 // Anything else is bad
308 return false;
309
310 }
311}
312
313
314
315if ( !function_exists("replace_uri_params") ) {
323 function replace_uri_params( $uri, $replacements ) {
324 $replaced = $uri;
325 foreach( $replacements AS $param => $new_value ) {
326 $rxp = preg_replace( '/([\[\]])/', '\\\\$1', $param ); // Some parameters may be arrays.
327 $regex = "/([&?])($rxp)=([^&]+)/";
328 dbg_error_log("core", "Looking for [%s] to replace with [%s] regex is %s and searching [%s]", $param, $new_value, $regex, $replaced );
329 if ( preg_match( $regex, $replaced ) )
330 $replaced = preg_replace( $regex, "\$1$param=$new_value", $replaced);
331 else
332 $replaced .= "&$param=$new_value";
333 }
334 if ( ! preg_match( '/\?/', $replaced ) ) {
335 $replaced = preg_replace("/&(.+)$/", "?\$1", $replaced);
336 }
337 $replaced = str_replace("&amp;", "--AmPeRsAnD--", $replaced);
338 $replaced = str_replace("&", "&amp;", $replaced);
339 $replaced = str_replace("--AmPeRsAnD--", "&amp;", $replaced);
340 dbg_error_log("core", "URI <<$uri>> morphed to <<$replaced>>");
341 return $replaced;
342 }
343}
344
345
346if ( !function_exists("uuid") ) {
376 function uuid() {
377
378 // The field names refer to RFC 4122 section 4.1.2
379
380 return sprintf('%04x%04x-%04x-%03x4-%04x-%04x%04x%04x',
381 mt_rand(0, 65535), mt_rand(0, 65535), // 32 bits for "time_low"
382 mt_rand(0, 65535), // 16 bits for "time_mid"
383 mt_rand(0, 4095), // 12 bits before the 0100 of (version) 4 for "time_hi_and_version"
384 bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
385 // 8 bits, the last two of which (positions 6 and 7) are 01, for "clk_seq_hi_res"
386 // (hence, the 2nd hex digit after the 3rd hyphen can only be 1, 5, 9 or d)
387 // 8 bits for "clk_seq_low"
388 mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535) // 48 bits for "node"
389 );
390 }
391}
392
393if ( !function_exists("translate") ) {
394 require("Translation.php");
395}
396
397 if ( !function_exists("clone") && version_compare(phpversion(), '5.0') < 0) {
403 eval( 'function clone($object) { return $object; }' );
404}
405
406if ( !function_exists("quoted_printable_encode") ) {
412 function quoted_printable_encode($string) {
413 return preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n", str_replace("%","=",str_replace("%20"," ",rawurlencode($string))));
414 }
415}
416
417
418if ( !function_exists("check_by_regex") ) {
424 function check_by_regex( $val, $regex ) {
425 if ( is_null($val) ) return null;
426 switch( $regex ) {
427 case 'int': $regex = '#^\d+$#'; break;
428 }
429 if ( is_array($val) ) {
430 foreach( $val AS $k => $v ) {
431 $val[$k] = check_by_regex($v,$regex);
432 }
433 }
434 else if ( ! is_object($val) ) {
435 if ( preg_match( $regex, $val, $matches) ) {
436 $val = $matches[0];
437 }
438 else {
439 $val = '';
440 }
441 }
442 return $val;
443 }
444}
445
446
447if ( !function_exists("param_to_global") ) {
458 function param_to_global( ) {
459 $args = func_get_args();
460
461 $varname = array_shift($args);
462 $GLOBALS[$varname] = null;
463
464 $match_regex = null;
465 $argc = func_num_args();
466 if ( $argc > 1 ) {
467 $match_regex = array_shift($args);
468 }
469
470 $args[] = $varname;
471 foreach( $args AS $k => $name ) {
472 if ( isset($_POST[$name]) ) {
473 $result = $_POST[$name];
474 break;
475 }
476 else if ( isset($_GET[$name]) ) {
477 $result = $_GET[$name];
478 break;
479 }
480 }
481 if ( !isset($result) ) return null;
482
483 if ( isset($match_regex) ) {
484 $result = check_by_regex( $result, $match_regex );
485 }
486
487 $GLOBALS[$varname] = $result;
488 return $result;
489 }
490}
491
492
493if ( !function_exists("awl_get_fields") ) {
497 $_AWL_field_cache = array();
498
504 function awl_get_fields( $tablename ) {
505 global $_AWL_field_cache;
506
507 if ( !isset($_AWL_field_cache[$tablename]) ) {
508 dbg_error_log( "core", ":awl_get_fields: Loading fields for table '$tablename'" );
509 $qry = new AwlQuery();
510 $db = $qry->GetConnection();
511 $qry->SetSQL($db->GetFields($tablename));
512 $qry->Exec("core");
513 $fields = array();
514 while( $row = $qry->Fetch() ) {
515 $fields[$row->fieldname] = $row->typename . ($row->precision >= 0 ? sprintf('(%d)',$row->precision) : '');
516 }
517 $_AWL_field_cache[$tablename] = $fields;
518 }
519 return $_AWL_field_cache[$tablename];
520 }
521}
522
523
524if ( !function_exists("force_utf8") ) {
525 function define_byte_mappings() {
526 global $byte_map, $nibble_good_chars;
527
528 # Needed for using Grant McLean's byte mappings code
529 $ascii_char = '[\x00-\x7F]';
530 $cont_byte = '[\x80-\xBF]';
531
532 $utf8_2 = '[\xC0-\xDF]' . $cont_byte;
533 $utf8_3 = '[\xE0-\xEF]' . $cont_byte . '{2}';
534 $utf8_4 = '[\xF0-\xF7]' . $cont_byte . '{3}';
535 $utf8_5 = '[\xF8-\xFB]' . $cont_byte . '{4}';
536
537 $nibble_good_chars = "/^($ascii_char+|$utf8_2|$utf8_3|$utf8_4|$utf8_5)(.*)$/s";
538
539 # From http://unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT
540 $byte_map = array(
541 "\x80" => "\xE2\x82\xAC", # EURO SIGN
542 "\x82" => "\xE2\x80\x9A", # SINGLE LOW-9 QUOTATION MARK
543 "\x83" => "\xC6\x92", # LATIN SMALL LETTER F WITH HOOK
544 "\x84" => "\xE2\x80\x9E", # DOUBLE LOW-9 QUOTATION MARK
545 "\x85" => "\xE2\x80\xA6", # HORIZONTAL ELLIPSIS
546 "\x86" => "\xE2\x80\xA0", # DAGGER
547 "\x87" => "\xE2\x80\xA1", # DOUBLE DAGGER
548 "\x88" => "\xCB\x86", # MODIFIER LETTER CIRCUMFLEX ACCENT
549 "\x89" => "\xE2\x80\xB0", # PER MILLE SIGN
550 "\x8A" => "\xC5\xA0", # LATIN CAPITAL LETTER S WITH CARON
551 "\x8B" => "\xE2\x80\xB9", # SINGLE LEFT-POINTING ANGLE QUOTATION MARK
552 "\x8C" => "\xC5\x92", # LATIN CAPITAL LIGATURE OE
553 "\x8E" => "\xC5\xBD", # LATIN CAPITAL LETTER Z WITH CARON
554 "\x91" => "\xE2\x80\x98", # LEFT SINGLE QUOTATION MARK
555 "\x92" => "\xE2\x80\x99", # RIGHT SINGLE QUOTATION MARK
556 "\x93" => "\xE2\x80\x9C", # LEFT DOUBLE QUOTATION MARK
557 "\x94" => "\xE2\x80\x9D", # RIGHT DOUBLE QUOTATION MARK
558 "\x95" => "\xE2\x80\xA2", # BULLET
559 "\x96" => "\xE2\x80\x93", # EN DASH
560 "\x97" => "\xE2\x80\x94", # EM DASH
561 "\x98" => "\xCB\x9C", # SMALL TILDE
562 "\x99" => "\xE2\x84\xA2", # TRADE MARK SIGN
563 "\x9A" => "\xC5\xA1", # LATIN SMALL LETTER S WITH CARON
564 "\x9B" => "\xE2\x80\xBA", # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
565 "\x9C" => "\xC5\x93", # LATIN SMALL LIGATURE OE
566 "\x9E" => "\xC5\xBE", # LATIN SMALL LETTER Z WITH CARON
567 "\x9F" => "\xC5\xB8", # LATIN CAPITAL LETTER Y WITH DIAERESIS
568 );
569
570 for( $i=160; $i < 256; $i++ ) {
571 $ch = chr($i);
572 $byte_map[$ch] = iconv('ISO-8859-1', 'UTF-8', $ch);
573 }
574 }
575 define_byte_mappings();
576
577 function force_utf8( $input ) {
578 global $byte_map, $nibble_good_chars;
579
580 $output = '';
581 $char = '';
582 $rest = '';
583 while( $input != '' ) {
584 if ( preg_match( $nibble_good_chars, $input, $matches ) ) {
585 $output .= $matches[1];
586 $rest = $matches[2];
587 }
588 else {
589 preg_match( '/^(.)(.*)$/s', $input, $matches );
590 $char = $matches[1];
591 $rest = $matches[2];
592 if ( isset($byte_map[$char]) ) {
593 $output .= $byte_map[$char];
594 }
595 else {
596 # Must be valid UTF8 already
597 $output .= $char;
598 }
599 }
600 $input = $rest;
601 }
602 return $output;
603 }
604
605}
606
607
608$timezone_identifiers_list_cache = timezone_identifiers_list();
609$timezone_identifiers_list_cache = isset($timezone_identifiers_list_cache) ? $timezone_identifiers_list_cache : [];
610
614function olson_from_tzstring( $tzstring ) {
615 global $c, $timezone_identifiers_list_cache;
616
617 if ( in_array($tzstring,$timezone_identifiers_list_cache) ) return $tzstring;
618 if ( preg_match( '{((Antarctica|America|Africa|Atlantic|Asia|Australia|Indian|Europe|Pacific)/(([^/]+)/)?[^/]+)$}', $tzstring, $matches ) ) {
619// dbg_error_log( 'INFO', 'Found timezone "%s" from string "%s"', $matches[1], $tzstring );
620 return $matches[1];
621 }
622 switch( $tzstring ) {
623 case 'New Zealand Standard Time': case 'New Zealand Daylight Time':
624 return 'Pacific/Auckland';
625 break;
626 case 'Central Standard Time': case 'Central Daylight Time': case 'US/Central':
627 return 'America/Chicago';
628 break;
629 case 'Eastern Standard Time': case 'Eastern Daylight Time': case 'US/Eastern':
630 case '(UTC-05:00) Eastern Time (US & Canada)':
631 return 'America/New_York';
632 break;
633 case 'Pacific Standard Time': case 'Pacific Daylight Time': case 'US/Pacific':
634 return 'America/Los_Angeles';
635 break;
636 case 'Mountain Standard Time': case 'Mountain Daylight Time': case 'US/Mountain': case 'Mountain Time':
637 return 'America/Denver';
638 // The US 'Mountain Time' can in fact be America/(Denver|Boise|Phoenix|Shiprock) which
639 // all vary to some extent due to differing DST rules.
640 break;
641 case '(GMT-07.00) Arizona':
642 return 'America/Phoenix';
643 break;
644 default:
645 if ( isset($c->timezone_translations) && is_array($c->timezone_translations)
646 && !empty($c->timezone_translations[$tzstring]) )
647 return $c->timezone_translations[$tzstring];
648 }
649 return null;
650}
651
652if ( !function_exists("deprecated") ) {
653 function deprecated( $method ) {
654 global $c;
655 if ( isset($c->dbg['ALL']) || isset($c->dbg['deprecated']) ) {
656 $stack = debug_backtrace();
657 array_shift($stack);
658 if ( preg_match( '{/inc/iCalendar.php$}', $stack[0]['file'] ) && $stack[0]['line'] > __LINE__ ) return;
659 @error_log( sprintf( $c->sysabbr.':DEPRECATED: Call to deprecated method "%s"', $method));
660 foreach( $stack AS $k => $v ) {
661 @error_log( sprintf( $c->sysabbr.': ==> called from line %4d of %s', $v['line'], $v['file']));
662 }
663 }
664 }
665}
666
667
668if ( !function_exists("gzdecode") ) {
669 function gzdecode( $instring ) {
670 global $c;
671 if ( !isset($c->use_pipe_gunzip) || $c->use_pipe_gunzip ) {
672 $descriptorspec = array(
673 0 => array("pipe", "r"), // stdin is a pipe that the child will read from
674 1 => array("pipe", "w"), // stdout is a pipe that the child will write to
675 2 => array("file", "/dev/null", "a") // stderr is discarded
676 );
677 $process = proc_open('gunzip',$descriptorspec, $pipes);
678 if ( is_resource($process) ) {
679 fwrite($pipes[0],$instring);
680 fclose($pipes[0]);
681
682 $outstring = stream_get_contents($pipes[1]);
683 fclose($pipes[1]);
684
685 proc_close($process);
686 return $outstring;
687 }
688 return '';
689 }
690 else {
691 $g=tempnam('./','gz');
692 file_put_contents($g,$instring);
693 ob_start();
694 readgzfile($g);
695 $d=ob_get_clean();
696 unlink($g);
697 return $d;
698 }
699 }
700}
701
705function awl_version() {
706 global $c;
707$c->awl_library_version = 0.64;
708 return $c->awl_library_version;
709}