Overview

Packages

  • awl
    • AuthPlugin
    • AwlDatabase
    • Browser
    • classEditor
    • DataEntry
    • DataUpdate
    • EMail
    • iCalendar
    • MenuSet
    • PgQuery
    • Session
    • Translation
    • User
    • Utilities
    • Validation
    • vCalendar
    • vComponent
    • XMLDocument
    • XMLElement
  • None
  • PHP

Functions

  • awl_get_fields
  • awl_version
  • check_by_regex
  • dbg_error_log
  • dbg_log_array
  • define_byte_mappings
  • deprecated
  • fatal
  • force_utf8
  • gzdecode
  • olson_from_tzstring
  • param_to_global
  • quoted_printable_encode
  • replace_uri_params
  • session_salted_md5
  • session_salted_sha1
  • session_simple_md5
  • session_validate_password
  • trace_bug
  • uuid
  • Overview
  • Package
  • Function
  • Tree
  • Deprecated
  • Todo
  1: <?php
  2: /**
  3: * Utility functions of a general nature which are used by
  4: * most AWL library classes.
  5: *
  6: * @package   awl
  7: * @subpackage   Utilities
  8: * @author    Andrew McMillan <andrew@mcmillan.net.nz>
  9: * @copyright Catalyst IT Ltd, Morphoss Ltd <http://www.morphoss.com/>
 10: * @license   http://www.gnu.org/licenses/lgpl-3.0.txt  GNU LGPL version 3 or later
 11: */
 12: 
 13: if ( !function_exists('dbg_error_log') ) {
 14:   /**
 15:   * Writes a debug message into the error log using printf syntax.  If the first
 16:   * parameter is "ERROR" then the message will _always_ be logged.
 17:   * Otherwise, the first parameter is a "component" name, and will only be logged
 18:   * if $c->dbg["component"] is set to some non-null value.
 19:   *
 20:   * If you want to see every log message then $c->dbg["ALL"] can be set, and
 21:   * then individual components can be set to zero to selectively ignore them.
 22:   * Additionally, log messages can be filtered by remote IP or username by populating
 23:   * the $c->dbg_filter["remoteIP"][] and $c->dbg_filter["authenticatedUser"][] arrays.
 24:   *
 25:   * @var string $component The component to identify itself, or "ERROR", or "LOG:component"
 26:   * @var string $format A format string for the log message
 27:   * @var [string $parameter ...] Parameters for the format string.
 28:   */
 29:   function dbg_error_log() {
 30:     global $c, $session;
 31:     $args = func_get_args();
 32:     $type = "DBG";
 33:     $component = array_shift($args);
 34:     if ( substr( $component, 0, 3) == "LOG" ) {
 35:       // Special escape case for stuff that always gets logged.
 36:       $type = 'LOG';
 37:       $component = substr($component,4);
 38:     }
 39:     else if ( $component == "ERROR" ) {
 40:       $type = "***";
 41:     }
 42:     else if ( isset($c->dbg["ALL"]) ) {
 43:       $type = "ALL";
 44:     }
 45:     else if ( !isset($c->dbg[strtolower($component)]) ) return;
 46: 
 47:     /* ignore noisy components by setting $c->dbg['foo'] = 0; */
 48:     if ( isset($c->dbg[strtolower($component)]) && $c->dbg[strtolower($component)] === 0 ) return;
 49: 
 50:     /* filter by remote IP or logged-in user */
 51:     if ( isset($c->dbg_filter["remoteIP"]) && !in_array($_SERVER['REMOTE_ADDR'], $c->dbg_filter["remoteIP"]) ) return;
 52:     if ( isset($c->dbg_filter["authenticatedUser"]) ) {
 53:         if ( !isset($session->username) ) return;
 54:         if ( !in_array($session->username, $c->dbg_filter["authenticatedUser"]) ) return;
 55:     }
 56: 
 57:     $argc = func_num_args();
 58:     if ( 2 <= $argc ) {
 59:       $format = array_shift($args);
 60:     }
 61:     else {
 62:       $format = "%s";
 63:     }
 64:     @error_log( $c->sysabbr.": $type: $component:". vsprintf( $format, $args ) );
 65:   }
 66: }
 67: 
 68: 
 69: if ( !function_exists('fatal') ) {
 70:   function fatal() {
 71:     global $c;
 72:     $args = func_get_args();
 73:     $argc = func_num_args();
 74:     if ( 2 <= $argc ) {
 75:       $format = array_shift($args);
 76:     }
 77:     else {
 78:       $format = "%s";
 79:     }
 80:     @error_log( $c->sysabbr.": FATAL: $component:". vsprintf( $format, $args ) );
 81: 
 82:     @error_log( "================= Stack Trace ===================" );
 83: 
 84:     $trace = array_reverse(debug_backtrace());
 85:     array_pop($trace);
 86:     foreach( $trace AS $k => $v ) {
 87:       @error_log( sprintf(" ===>  %s[%d] calls %s%s%s()",
 88:                     $v['file'],
 89:                     $v['line'],
 90:                     (isset($v['class'])?$v['class']:''),
 91:                     (isset($v['type'])?$v['type']:''),
 92:                     (isset($v['function'])?$v['function']:'')
 93:       ));
 94:     }
 95:     echo "Fatal Error";
 96:     exit();
 97:   }
 98: }
 99: 
100: 
101: if ( !function_exists('trace_bug') ) {
102: /**
103: * Not as sever as a fatal() call, but we want to log and trace it
104: */
105:   function trace_bug() {
106:     global $c;
107:     $args = func_get_args();
108:     $argc = func_num_args();
109:     if ( 2 <= $argc ) {
110:       $format = array_shift($args);
111:     }
112:     else {
113:       $format = "%s";
114:     }
115:     @error_log( $c->sysabbr.": BUG: $component:". vsprintf( $format, $args ) );
116: 
117:     @error_log( "================= Stack Trace ===================" );
118: 
119:     $trace = array_reverse(debug_backtrace());
120:     array_pop($trace);
121:     foreach( $trace AS $k => $v ) {
122:       @error_log( sprintf(" ===>  %s[%d] calls %s%s%s()",
123:                     $v['file'],
124:                     $v['line'],
125:                     (isset($v['class'])?$v['class']:''),
126:                     (isset($v['type'])?$v['type']:''),
127:                     (isset($v['function'])?$v['function']:'')
128:       ));
129:     }
130:   }
131: }
132: 
133: 
134: if ( !function_exists('apache_request_headers') ) {
135:   /**
136:   * Compatibility so we can use the apache function name and still work with CGI
137:   * @package awl
138:   */
139:   eval('
140:     function apache_request_headers() {
141:         foreach($_SERVER as $key=>$value) {
142:             if (substr($key,0,5)=="HTTP_") {
143:                 $key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
144:                 $out[$key]=$value;
145:             }
146:         }
147:         return $out;
148:     }
149:   ');
150: }
151: 
152: 
153: 
154: if ( !function_exists('dbg_log_array') ) {
155:   /**
156:   * Function to dump an array to the error log, possibly recursively
157:   *
158:   * @var string $component Which component should this log message identify itself from
159:   * @var string $name What name should this array dump identify itself as
160:   * @var array $arr The array to be dumped.
161:   * @var boolean $recursive Should the dump recurse into arrays/objects in the array
162:   */
163:   function dbg_log_array( $component, $name, $arr, $recursive = false ) {
164:     if ( !isset($arr) || (gettype($arr) != 'array' && gettype($arr) != 'object') ) {
165:       dbg_error_log( $component, "%s: array is not set, or is not an array!", $name);
166:       return;
167:     }
168:     foreach ($arr as $key => $value) {
169:       dbg_error_log( $component, "%s: >>%s<< = >>%s<<", $name, $key,
170:                       (gettype($value) == 'array' || gettype($value) == 'object' ? gettype($value) : $value) );
171:       if ( $recursive && (gettype($value) == 'array' || (gettype($value) == 'object' && "$key" != 'self' && "$key" != 'parent') ) ) {
172:         dbg_log_array( $component, "$name"."[$key]", $value, $recursive );
173:       }
174:     }
175:   }
176: }
177: 
178: 
179: 
180: if ( !function_exists("session_simple_md5") ) {
181:   /**
182:   * Make a plain MD5 hash of a string, identifying the type of hash it is
183:   *
184:   * @param string $instr The string to be salted and MD5'd
185:   * @return string The *MD5* and the MD5 of the string
186:   */
187:   function session_simple_md5( $instr ) {
188:     global $c;
189:     if ( isset($c->dbg['password']) ) dbg_error_log( "Login", "Making plain MD5: instr=$instr, md5($instr)=".md5($instr) );
190:     return ( '*MD5*'. md5($instr) );
191:   }
192: }
193: 
194: 
195: 
196: if ( !function_exists("session_salted_md5") ) {
197:   /**
198:   * Make a salted MD5 string, given a string and (possibly) a salt.
199:   *
200:   * If no salt is supplied we will generate a random one.
201:   *
202:   * @param string $instr The string to be salted and MD5'd
203:   * @param string $salt Some salt to sprinkle into the string to be MD5'd so we don't get the same PW always hashing to the same value.
204:   * @return string The salt, a * and the MD5 of the salted string, as in SALT*SALTEDHASH
205:   */
206:   function session_salted_md5( $instr, $salt = "" ) {
207:     if ( $salt == "" ) $salt = substr( md5(rand(100000,999999)), 2, 8);
208:     global $c;
209:     if ( isset($c->dbg['password']) ) dbg_error_log( "Login", "Making salted MD5: salt=$salt, instr=$instr, md5($salt$instr)=".md5($salt . $instr) );
210:     return ( sprintf("*%s*%s", $salt, md5($salt . $instr) ) );
211:   }
212: }
213: 
214: 
215: 
216: if ( !function_exists("session_salted_sha1") ) {
217:   /**
218:   * Make a salted SHA1 string, given a string and (possibly) a salt.  PHP5 only (although it
219:   * could be made to work on PHP4 (@see http://www.openldap.org/faq/data/cache/347.html). The
220:   * algorithm used here is compatible with OpenLDAP so passwords generated through this function
221:   * should be able to be migrated to OpenLDAP by using the part following the second '*', i.e.
222:   * the '{SSHA}....' part.
223:   *
224:   * If no salt is supplied we will generate a random one.
225:   *
226:   * @param string $instr The string to be salted and SHA1'd
227:   * @param string $salt Some salt to sprinkle into the string to be SHA1'd so we don't get the same PW always hashing to the same value.
228:   * @return string A *, the salt, a * and the SHA1 of the salted string, as in *SALT*SALTEDHASH
229:   */
230:   function session_salted_sha1( $instr, $salt = "" ) {
231:     if ( $salt == "" ) $salt = substr( str_replace('*','',base64_encode(sha1(rand(100000,9999999),true))), 2, 9);
232:     global $c;
233:     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) );
234:     return ( sprintf("*%s*{SSHA}%s", $salt, base64_encode(sha1($instr.$salt, true) . $salt ) ) );
235:   }
236: }
237: 
238: 
239: if ( !function_exists("session_validate_password") ) {
240: 
241:   /**
242:   * Checks what a user entered against the actual password on their account.
243:   * @param string $they_sent What the user entered.
244:   * @param string $we_have What we have in the database as their password.  Which may (or may not) be a salted MD5.
245:   * @return boolean Whether or not the users attempt matches what is already on file.
246:   */
247:   function session_validate_password( $they_sent, $we_have ) {
248:     global $c;
249:     if ( preg_match('/^\*\*.+$/', $we_have ) ) {
250:       //  The "forced" style of "**plaintext" to allow easier admin setting
251:       return ( "**$they_sent" == $we_have );
252:     }
253: 
254:     if ( isset($c->wp_includes) && substring($we_have,0,1) == '$' ) {
255:       // Include Wordpress password handling, if it's in the path.
256:       @require_once($c->wp_includes .'/class-phpass.php');
257: 
258:       if ( class_exists('PasswordHash') ) {
259:         $wp_hasher = new PasswordHash(8, true);
260:         return $wp_hasher->CheckPassword($password, $hash);
261:       }
262:     }
263: 
264:     if ( preg_match('/^\*(.+)\*{[A-Z]+}.+$/', $we_have, $regs ) ) {
265:       if ( function_exists("session_salted_sha1") ) {
266:         // A nicely salted sha1sum like "*<salt>*{SSHA}<salted_sha1>"
267:         $salt = $regs[1];
268:         $sha1_sent = session_salted_sha1( $they_sent, $salt ) ;
269:         return ( $sha1_sent == $we_have );
270:       }
271:       else {
272:         dbg_error_log( "ERROR", "Password is salted SHA-1 but you are using PHP4!" );
273:         echo <<<EOERRMSG
274: <html>
275: <head>
276: <title>Salted SHA1 Password format not supported with PHP4</title>
277: </head>
278: <body>
279: <h1>Salted SHA1 Password format not supported with PHP4</h1>
280: <p>At some point you have used PHP5 to set the password for this user and now you are
281:    using PHP4.  You will need to assign a new password to this user using PHP4, or ensure
282:    you use PHP5 everywhere (recommended).</p>
283: <p>AWL has now switched to using salted SHA-1 passwords by preference in a format
284:    compatible with OpenLDAP.</p>
285: </body>
286: </html>
287: EOERRMSG;
288:         exit;
289:       }
290:     }
291: 
292:     if ( preg_match('/^\*MD5\*.+$/', $we_have, $regs ) ) {
293:       // A crappy unsalted md5sum like "*MD5*<md5>"
294:       $md5_sent = session_simple_md5( $they_sent ) ;
295:       return ( $md5_sent == $we_have );
296:     }
297:     else if ( preg_match('/^\*(.+)\*.+$/', $we_have, $regs ) ) {
298:       // A nicely salted md5sum like "*<salt>*<salted_md5>"
299:       $salt = $regs[1];
300:       $md5_sent = session_salted_md5( $they_sent, $salt ) ;
301:       return ( $md5_sent == $we_have );
302:     }
303: 
304:     // Anything else is bad
305:     return false;
306: 
307:   }
308: }
309: 
310: 
311: 
312: if ( !function_exists("replace_uri_params") ) {
313:   /**
314:   * Given a URL (presumably the current one) and a parameter, replace the value of parameter,
315:   * extending the URL as necessary if the parameter is not already there.
316:   * @param string $uri The URI we will be replacing parameters in.
317:   * @param array $replacements An array of replacement pairs array( "replace_this" => "with this" )
318:   * @return string The URI with the replacements done.
319:   */
320:   function replace_uri_params( $uri, $replacements ) {
321:     $replaced = $uri;
322:     foreach( $replacements AS $param => $new_value ) {
323:       $rxp = preg_replace( '/([\[\]])/', '\\\\$1', $param );  // Some parameters may be arrays.
324:       $regex = "/([&?])($rxp)=([^&]+)/";
325:       dbg_error_log("core", "Looking for [%s] to replace with [%s] regex is %s and searching [%s]", $param, $new_value, $regex, $replaced );
326:       if ( preg_match( $regex, $replaced ) )
327:         $replaced = preg_replace( $regex, "\$1$param=$new_value", $replaced);
328:       else
329:         $replaced .= "&$param=$new_value";
330:     }
331:     if ( ! preg_match( '/\?/', $replaced  ) ) {
332:       $replaced = preg_replace("/&(.+)$/", "?\$1", $replaced);
333:     }
334:     $replaced = str_replace("&amp;", "--AmPeRsAnD--", $replaced);
335:     $replaced = str_replace("&", "&amp;", $replaced);
336:     $replaced = str_replace("--AmPeRsAnD--", "&amp;", $replaced);
337:     dbg_error_log("core", "URI <<$uri>> morphed to <<$replaced>>");
338:     return $replaced;
339:   }
340: }
341: 
342: 
343: if ( !function_exists("uuid") ) {
344: /**
345:  * Generates a Universally Unique IDentifier, version 4.
346:  *
347:  * RFC 4122 (http://www.ietf.org/rfc/rfc4122.txt) defines a special type of Globally
348:  * Unique IDentifiers (GUID), as well as several methods for producing them. One
349:  * such method, described in section 4.4, is based on truly random or pseudo-random
350:  * number generators, and is therefore implementable in a language like PHP.
351:  *
352:  * We choose to produce pseudo-random numbers with the Mersenne Twister, and to always
353:  * limit single generated numbers to 16 bits (ie. the decimal value 65535). That is
354:  * because, even on 32-bit systems, PHP's RAND_MAX will often be the maximum *signed*
355:  * value, with only the equivalent of 31 significant bits. Producing two 16-bit random
356:  * numbers to make up a 32-bit one is less efficient, but guarantees that all 32 bits
357:  * are random.
358:  *
359:  * The algorithm for version 4 UUIDs (ie. those based on random number generators)
360:  * states that all 128 bits separated into the various fields (32 bits, 16 bits, 16 bits,
361:  * 8 bits and 8 bits, 48 bits) should be random, except : (a) the version number should
362:  * be the last 4 bits in the 3rd field, and (b) bits 6 and 7 of the 4th field should
363:  * be 01. We try to conform to that definition as efficiently as possible, generating
364:  * smaller values where possible, and minimizing the number of base conversions.
365:  *
366:  * @copyright  Copyright (c) CFD Labs, 2006. This function may be used freely for
367:  *              any purpose ; it is distributed without any form of warranty whatsoever.
368:  * @author      David Holmes <dholmes@cfdsoftware.net>
369:  *
370:  * @return  string  A UUID, made up of 32 hex digits and 4 hyphens.
371:  */
372: 
373:   function uuid() {
374: 
375:     // The field names refer to RFC 4122 section 4.1.2
376: 
377:     return sprintf('%04x%04x-%04x-%03x4-%04x-%04x%04x%04x',
378:         mt_rand(0, 65535), mt_rand(0, 65535), // 32 bits for "time_low"
379:         mt_rand(0, 65535), // 16 bits for "time_mid"
380:         mt_rand(0, 4095),  // 12 bits before the 0100 of (version) 4 for "time_hi_and_version"
381:         bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
382:             // 8 bits, the last two of which (positions 6 and 7) are 01, for "clk_seq_hi_res"
383:             // (hence, the 2nd hex digit after the 3rd hyphen can only be 1, 5, 9 or d)
384:             // 8 bits for "clk_seq_low"
385:         mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535) // 48 bits for "node"
386:     );
387:   }
388: }
389: 
390: if ( !function_exists("translate") ) {
391:   require("Translation.php");
392: }
393: 
394:  if ( !function_exists("clone") && version_compare(phpversion(), '5.0') < 0) {
395:   /**
396:   * PHP5 screws with the assignment operator changing so that $a = $b means that
397:   * $a becomes a reference to $b.  There is a clone() that we can use in PHP5, so
398:   * we have to emulate that for PHP4.  Bleargh.
399:   */
400:   eval( 'function clone($object) { return $object; }' );
401: }
402: 
403: if ( !function_exists("quoted_printable_encode") ) {
404:   /**
405:   * Process a string to fit the requirements of RFC2045 section 6.7.  Note that
406:   * this works, but replaces more characters than the minimum set. For readability
407:   * the spaces aren't encoded as =20 though.
408:   */
409:   function quoted_printable_encode($string) {
410:     return preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n", str_replace("%","=",str_replace("%20"," ",rawurlencode($string))));
411:   }
412: }
413: 
414: 
415: if ( !function_exists("check_by_regex") ) {
416:   /**
417:   * Verify a value is OK by testing a regex against it.  If it is an array apply it to
418:   * each element in the array recursively.  If it is an object we don't mess
419:   * with it.
420:   */
421:   function check_by_regex( $val, $regex ) {
422:     if ( is_null($val) ) return null;
423:     switch( $regex ) {
424:       case 'int':     $regex = '#^\d+$#';     break;
425:     }
426:     if ( is_array($val) ) {
427:       foreach( $val AS $k => $v ) {
428:         $val[$k] = check_by_regex($v,$regex);
429:       }
430:     }
431:     else if ( ! is_object($val) ) {
432:       if ( preg_match( $regex, $val, $matches) ) {
433:         $val = $matches[0];
434:       }
435:       else {
436:         $val = '';
437:       }
438:     }
439:     return $val;
440:   }
441: }
442: 
443: 
444: if ( !function_exists("param_to_global") ) {
445:   /**
446:   * Convert a parameter to a global.  We first look in _POST and then in _GET,
447:   * and if they passed in a bunch of valid characters, we will make sure the
448:   * incoming is cleaned to only match that set.
449:   *
450:   * @param string $varname The name of the global variable to put the answer in
451:   * @param string $match_regex The part of the parameter matching this regex will be returned
452:   * @param string $alias1  An alias for the name that we should look for first.
453:   * @param    "    ...     More aliases, in the order which they should be examined.  $varname will be appended to the end.
454:   */
455:   function param_to_global( ) {
456:     $args = func_get_args();
457: 
458:     $varname = array_shift($args);
459:     $GLOBALS[$varname] = null;
460: 
461:     $match_regex = null;
462:     $argc = func_num_args();
463:     if ( $argc > 1 ) {
464:       $match_regex = array_shift($args);
465:     }
466: 
467:     $args[] = $varname;
468:     foreach( $args AS $k => $name ) {
469:       if ( isset($_POST[$name]) ) {
470:         $result = $_POST[$name];
471:         break;
472:       }
473:       else if ( isset($_GET[$name]) ) {
474:         $result = $_GET[$name];
475:         break;
476:       }
477:     }
478:     if ( !isset($result) ) return null;
479: 
480:     if ( isset($match_regex) ) {
481:       $result = check_by_regex( $result, $match_regex );
482:     }
483: 
484:     $GLOBALS[$varname] = $result;
485:     return $result;
486:   }
487: }
488: 
489: 
490: if ( !function_exists("awl_get_fields") ) {
491:   /**
492:   * @var array $_AWL_field_cache is a cache of the field names for a table
493:   */
494:   $_AWL_field_cache = array();
495: 
496:   /**
497:   * Get the names of the fields for a particular table
498:   * @param string $tablename The name of the table.
499:   * @return array of string The public fields in the table.
500:   */
501:   function awl_get_fields( $tablename ) {
502:     global $_AWL_field_cache;
503: 
504:     if ( !isset($_AWL_field_cache[$tablename]) ) {
505:       dbg_error_log( "core", ":awl_get_fields: Loading fields for table '$tablename'" );
506:       $qry = new AwlQuery();
507:       $db = $qry->GetConnection();
508:       $qry->SetSQL($db->GetFields($tablename));
509:       $qry->Exec("core");
510:       $fields = array();
511:       while( $row = $qry->Fetch() ) {
512:         $fields[$row->fieldname] = $row->typename . ($row->precision >= 0 ? sprintf('(%d)',$row->precision) : '');
513:       }
514:       $_AWL_field_cache[$tablename] = $fields;
515:     }
516:     return $_AWL_field_cache[$tablename];
517:   }
518: }
519: 
520: 
521: if ( !function_exists("force_utf8") ) {
522:   function define_byte_mappings() {
523:     global $byte_map, $nibble_good_chars;
524: 
525:     # Needed for using Grant McLean's byte mappings code
526:     $ascii_char = '[\x00-\x7F]';
527:     $cont_byte  = '[\x80-\xBF]';
528: 
529:     $utf8_2     = '[\xC0-\xDF]' . $cont_byte;
530:     $utf8_3     = '[\xE0-\xEF]' . $cont_byte . '{2}';
531:     $utf8_4     = '[\xF0-\xF7]' . $cont_byte . '{3}';
532:     $utf8_5     = '[\xF8-\xFB]' . $cont_byte . '{4}';
533: 
534:     $nibble_good_chars = "/^($ascii_char+|$utf8_2|$utf8_3|$utf8_4|$utf8_5)(.*)$/s";
535: 
536:     # From http://unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT
537:     $byte_map = array(
538:         "\x80" => "\xE2\x82\xAC",  # EURO SIGN
539:         "\x82" => "\xE2\x80\x9A",  # SINGLE LOW-9 QUOTATION MARK
540:         "\x83" => "\xC6\x92",      # LATIN SMALL LETTER F WITH HOOK
541:         "\x84" => "\xE2\x80\x9E",  # DOUBLE LOW-9 QUOTATION MARK
542:         "\x85" => "\xE2\x80\xA6",  # HORIZONTAL ELLIPSIS
543:         "\x86" => "\xE2\x80\xA0",  # DAGGER
544:         "\x87" => "\xE2\x80\xA1",  # DOUBLE DAGGER
545:         "\x88" => "\xCB\x86",      # MODIFIER LETTER CIRCUMFLEX ACCENT
546:         "\x89" => "\xE2\x80\xB0",  # PER MILLE SIGN
547:         "\x8A" => "\xC5\xA0",      # LATIN CAPITAL LETTER S WITH CARON
548:         "\x8B" => "\xE2\x80\xB9",  # SINGLE LEFT-POINTING ANGLE QUOTATION MARK
549:         "\x8C" => "\xC5\x92",      # LATIN CAPITAL LIGATURE OE
550:         "\x8E" => "\xC5\xBD",      # LATIN CAPITAL LETTER Z WITH CARON
551:         "\x91" => "\xE2\x80\x98",  # LEFT SINGLE QUOTATION MARK
552:         "\x92" => "\xE2\x80\x99",  # RIGHT SINGLE QUOTATION MARK
553:         "\x93" => "\xE2\x80\x9C",  # LEFT DOUBLE QUOTATION MARK
554:         "\x94" => "\xE2\x80\x9D",  # RIGHT DOUBLE QUOTATION MARK
555:         "\x95" => "\xE2\x80\xA2",  # BULLET
556:         "\x96" => "\xE2\x80\x93",  # EN DASH
557:         "\x97" => "\xE2\x80\x94",  # EM DASH
558:         "\x98" => "\xCB\x9C",      # SMALL TILDE
559:         "\x99" => "\xE2\x84\xA2",  # TRADE MARK SIGN
560:         "\x9A" => "\xC5\xA1",      # LATIN SMALL LETTER S WITH CARON
561:         "\x9B" => "\xE2\x80\xBA",  # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
562:         "\x9C" => "\xC5\x93",      # LATIN SMALL LIGATURE OE
563:         "\x9E" => "\xC5\xBE",      # LATIN SMALL LETTER Z WITH CARON
564:         "\x9F" => "\xC5\xB8",      # LATIN CAPITAL LETTER Y WITH DIAERESIS
565:     );
566: 
567:     for( $i=160; $i < 256; $i++ ) {
568:       $ch = chr($i);
569:       $byte_map[$ch] = iconv('ISO-8859-1', 'UTF-8', $ch);
570:     }
571:   }
572:   define_byte_mappings();
573: 
574:   function force_utf8( $input ) {
575:     global $byte_map, $nibble_good_chars;
576: 
577:     $output = '';
578:     $char   = '';
579:     $rest   = '';
580:     while( $input != '' ) {
581:       if ( preg_match( $nibble_good_chars, $input, $matches ) ) {
582:         $output .= $matches[1];
583:         $rest = $matches[2];
584:       }
585:       else {
586:         preg_match( '/^(.)(.*)$/s', $input, $matches );
587:         $char = $matches[1];
588:         $rest = $matches[2];
589:         if ( isset($byte_map[$char]) ) {
590:           $output .= $byte_map[$char];
591:         }
592:         else {
593:           # Must be valid UTF8 already
594:           $output .= $char;
595:         }
596:       }
597:       $input = $rest;
598:     }
599:     return $output;
600:   }
601: 
602: }
603: 
604: 
605: /**
606: * Try and extract something like "Pacific/Auckland" or "America/Indiana/Indianapolis" if possible.
607: */
608: function olson_from_tzstring( $tzstring ) {
609:   global $c;
610: 
611:   if ( function_exists('timezone_identifiers_list') && in_array($tzstring,timezone_identifiers_list()) ) return $tzstring;
612:   if ( preg_match( '{((Antarctica|America|Africa|Atlantic|Asia|Australia|Indian|Europe|Pacific)/(([^/]+)/)?[^/]+)$}', $tzstring, $matches ) ) {
613: //    dbg_error_log( 'INFO', 'Found timezone "%s" from string "%s"', $matches[1], $tzstring );
614:     return $matches[1];
615:   }
616:   switch( $tzstring ) {
617:     case 'New Zealand Standard Time': case 'New Zealand Daylight Time':
618:          return 'Pacific/Auckland';
619:          break;
620:     case 'Central Standard Time':     case 'Central Daylight Time':     case 'US/Central':
621:          return 'America/Chicago';
622:          break;
623:     case 'Eastern Standard Time':     case 'Eastern Daylight Time':     case 'US/Eastern':
624:     case '(UTC-05:00) Eastern Time (US & Canada)':
625:          return 'America/New_York';
626:          break;
627:     case 'Pacific Standard Time':     case 'Pacific Daylight Time':     case 'US/Pacific':
628:          return 'America/Los_Angeles';
629:          break;
630:     case 'Mountain Standard Time':    case 'Mountain Daylight Time':    case 'US/Mountain':    case 'Mountain Time':
631:          return 'America/Denver';
632:          // The US 'Mountain Time' can in fact be America/(Denver|Boise|Phoenix|Shiprock) which
633:          // all vary to some extent due to differing DST rules.
634:          break;
635:     case '(GMT-07.00) Arizona':
636:          return 'America/Phoenix';
637:          break;
638:     default:
639:          if ( isset($c->timezone_translations) && is_array($c->timezone_translations)
640:                       && !empty($c->timezone_translations[$tzstring]) )
641:            return $c->timezone_translations[$tzstring];
642:   }
643:   return null;
644: }
645: 
646: if ( !function_exists("deprecated") ) {
647:   function deprecated( $method ) {
648:     global $c;
649:     if ( isset($c->dbg['ALL']) || isset($c->dbg['deprecated']) ) {
650:       $stack = debug_backtrace();
651:       array_shift($stack);
652:       if ( preg_match( '{/inc/iCalendar.php$}', $stack[0]['file'] ) && $stack[0]['line'] > __LINE__ ) return;
653:       @error_log( sprintf( $c->sysabbr.':DEPRECATED: Call to deprecated method "%s"', $method));
654:       foreach( $stack AS $k => $v ) {
655:         @error_log( sprintf( $c->sysabbr.':  ==>  called from line %4d of %s', $v['line'], $v['file']));
656:       }
657:     }
658:   }
659: }
660: 
661: 
662: if ( !function_exists("gzdecode") ) {
663:   function gzdecode( $instring ) {
664:     global $c;
665:     if ( !isset($c->use_pipe_gunzip) || $c->use_pipe_gunzip ) {
666:       $descriptorspec = array(
667:          0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
668:          1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
669:          2 => array("file", "/dev/null", "a") // stderr is discarded
670:       );
671:       $process = proc_open('gunzip',$descriptorspec, $pipes);
672:       if ( is_resource($process) ) {
673:         fwrite($pipes[0],$instring);
674:         fclose($pipes[0]);
675: 
676:         $outstring = stream_get_contents($pipes[1]);
677:         fclose($pipes[1]);
678: 
679:         proc_close($process);
680:         return $outstring;
681:       }
682:       return '';
683:     }
684:     else {
685:       $g=tempnam('./','gz');
686:       file_put_contents($g,$instring);
687:       ob_start();
688:       readgzfile($g);
689:       $d=ob_get_clean();
690:       unlink($g);
691:       return $d;
692:     }
693:   }
694: }
695: 
696: /**
697:  * Return the AWL version
698:  */
699: function awl_version() {
700:   global $c;
701: $c->awl_library_version = 0.57;
702:   return $c->awl_library_version;
703: }
704: 
AWL API documentation generated by ApiGen 2.8.0