File: Util.php

package info (click to toggle)
horde3 3.1.3-4etch7
  • links: PTS
  • area: main
  • in suites: etch
  • size: 22,876 kB
  • ctags: 18,071
  • sloc: php: 75,151; xml: 2,979; sql: 1,069; makefile: 79; sh: 64
file content (866 lines) | stat: -rw-r--r-- 28,337 bytes parent folder | download | duplicates (2)
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
<?php

/**
 * Error code for a missing driver configuration.
 */
define('HORDE_ERROR_DRIVER_CONFIG_MISSING', 1);

/**
 * Error code for an incomplete driver configuration.
 */
define('HORDE_ERROR_DRIVER_CONFIG', 2);

/**
 * The Util:: class provides generally useful methods of different kinds.
 *
 * $Horde: framework/Util/Util.php,v 1.384.6.17 2006/05/05 16:02:12 jan Exp $
 *
 * Copyright 1999-2006 Chuck Hagenbuch <chuck@horde.org>
 * Copyright 1999-2006 Jon Parise <jon@horde.org>
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 *
 * @author  Chuck Hagenbuch <chuck@horde.org>
 * @author  Jon Parise <jon@horde.org>
 * @since   Horde 3.0
 * @package Horde_Util
 */
class Util {

    /**
     * Returns an object's clone.
     *
     * @param object &$obj  The object to clone.
     *
     * @return object  The cloned object.
     */
    function &cloneObject(&$obj)
    {
        /* Cloning does *not* currently work if using PHP 5.
         * This is a known PHP issue: http://bugs.php.net/bug.php?id=27268
         * Therefore, work around this issue by using the PHP 4
         * serialize/unserialize clone hack. */
        /*
        if (version_compare(zend_version(), '2', '>')) {
            return clone($obj);
        } else {
            $newObj = $obj;
            return $newObj;
        }
        */
        $ret = unserialize(serialize($obj));
        return $ret;
    }

    /**
     * Buffers the output from a function call, like readfile() or
     * highlight_string(), that prints the output directly, so that instead it
     * can be returned as a string and used.
     *
     * @param string $function  The function to run.
     * @param mixed $arg1       First argument to $function().
     * @param mixed $arg2       Second argument to $function().
     * @param mixed $arg...     ...
     * @param mixed $argN       Nth argument to $function().
     *
     * @return string  The output of the function.
     */
    function bufferOutput()
    {
        if (func_num_args() == 0) {
            return false;
        }
        $include = false;
        $args = func_get_args();
        $function = array_shift($args);
        if (is_array($function)) {
            if (!is_callable($function)) {
                return false;
            }
        } elseif (($function == 'include') ||
                  ($function == 'include_once') ||
                  ($function == 'require') ||
                  ($function == 'require_once')) {
            $include = true;
        } elseif (!function_exists($function)) {
            return false;
        }

        ob_start();
        if ($include) {
            $file = implode(',', $args);
            switch ($function) {
            case 'include':
                include $file;
                break;

            case 'include_once':
                include_once $file;
                break;

            case 'require':
                require $file;
                break;

            case 'require_once':
                require_once $file;
                break;
            }
        } else {
            call_user_func_array($function, $args);
        }
        $output = ob_get_contents();
        ob_end_clean();

        return $output;
    }

    /**
     * Checks to see if a value has been set by the script and not by GET,
     * POST, or cookie input. The value being checked MUST be in the global
     * scope.
     *
     * @param string $varname  The variable name to check.
     * @param mixed $default   Default value if the variable isn't present
     *                         or was specified by the user. Defaults to null.
     *                         @since Horde 3.1
     *
     * @return mixed  $default if the var is in user input or not present,
     *                the variable value otherwise.
     */
    function nonInputVar($varname, $default = null)
    {
        if (isset($_GET[$varname]) ||
            isset($_POST[$varname]) ||
            isset($_COOKIE[$varname])) {
            return $default;
        } else {
            return isset($GLOBALS[$varname]) ? $GLOBALS[$varname] : $default;
        }
    }

    /**
     * Adds a name=value pair to the end of an URL, taking care of whether
     * there are existing parameters and whether to use ?, & or &amp; as the
     * glue.  All data will be urlencoded.
     *
     * @param string $url       The URL to modify
     * @param mixed $parameter  Either the name=value pair to add
     *                          (DEPRECATED) -or-
     *                          the name value -or-
     *                          an array of name/value pairs.
     * @param string $value     If specified, the value part ($parameter is
     *                          then assumed to just be the parameter name).
     * @param boolean $encode   If true, and we don't have argument separators
     *                          yet, the argument separator gets encoded.
     *
     * @return string  The modified URL.
     */
    function addParameter($url, $parameter, $value = null, $encode = true)
    {
        static $translation_table;

        if (!isset($translation_table)) {
            $translation_table = array_flip(get_html_translation_table(HTML_ENTITIES));
        }
        if (empty($parameter)) {
            return $url;
        }

        /* Make sure to have an array. */
        if (!is_array($parameter)) {
            $add = array($parameter => $value);
        } else {
            $add = $parameter;
        }

        $arg = $encode ? '&amp;' : '&';
        if (($pos = strpos($url, '?')) === false) {
            $glue = '?';
        } else {
            /* Check if the argument separator has been already
             * htmlentities-ized in the URL. */
            $query = substr($url, $pos + 1);
            if (preg_match('/=.*?&amp;.*?=/', $query)) {
                $arg = '&amp;';
                $query = strtr($query, $translation_table);
            } elseif (preg_match('/=.*?&.*?=/', $query)) {
                $arg = '&';
            }
            $pairs = explode($arg, $query);
            $params = array();
            foreach ($pairs as $pair) {
                $pair = explode('=', $pair, 2);
                $params[$pair[0]] = count($pair) == 2 ? $pair[1] : '';
            }
            $glue = $arg;
        }

        $url_params = array();
        foreach ($add as $parameter => $value) {
            if (!isset($params[$parameter])) {
                if (is_array($value)) {
                    foreach ($value as $val) {
                        $url_params[] = urlencode($parameter) . '[]=' . urlencode($val);
                    }
                } else {
                    $url_params[] = urlencode($parameter) . '=' . urlencode($value);
                }
            }
        }

        if (count($url_params)) {
            return $url . $glue . implode($arg, $url_params);
        } else {
            return $url;
        }
    }

    /**
     * Removes name=value pairs from a URL.
     *
     * @param string $url    The URL to modify.
     * @param mixed $remove  Either a single parameter to remove or an array
     *                       of parameters to remove.
     *
     * @return string  The modified URL.
     */
    function removeParameter($url, $remove)
    {
        static $translation_table;

        if (!isset($translation_table)) {
            $translation_table = array_flip(get_html_translation_table(HTML_ENTITIES));
        }
        if (!is_array($remove)) {
            $remove = array($remove);
        }

        /* Return immediately if there are no parameters to remove. */
        if (($pos = strpos($url, '?')) === false) {
            return $url;
        }

        $entities = false;
        list($url, $query) = explode('?', $url, 2);

        /* Check if the argument separator has been already
         * htmlentities-ized in the URL. */
        if (preg_match('/=.*?&amp;.*?=/', $query)) {
            $entities = true;
            $query = strtr($query, $translation_table);
        }

        /* Get the list of parameters. */
        $pairs = explode('&', $query);
        $params = array();
        foreach ($pairs as $pair) {
            $pair = explode('=', $pair, 2);
            $params[$pair[0]] = count($pair) == 2 ? $pair[1] : '';
        }

        /* Remove the parameters. */
        foreach ($remove as $param) {
            unset($params[$param]);
        }

        if (!count($params)) {
            return $url;
        }

        /* Flatten arrays.
         * FIXME: should handle more than one array level somehow. */
        $add = array();
        foreach ($params as $key => $val) {
            if (is_array($val)) {
                foreach ($val as $v) {
                    $add[] = $key . '[]=' . $v;
                }
            } else {
                $add[] = $key . '=' . $val;
            }
        }

        $query = implode('&', $add);
        if ($entities) {
            $query = htmlentities($query);
        }

        return $url . '?' . $query;
    }

    /**
     * Returns a url with the 'nocache' parameter added, if the browser is
     * buggy and caches old URLs.
     *
     * @param string $url  The URL to modify.
     *
     * @return string  The requested URI.
     */
    function nocacheUrl($url)
    {
        static $rand_num;

        require_once 'Horde/Browser.php';
        $browser = &Browser::singleton();

        /* We may need to set a dummy parameter 'nocache' since some
         * browsers do not always honor the 'no-cache' header. */
        if ($browser->hasQuirk('cache_same_url')) {
            if (!isset($rand_num)) {
                $rand_num = base_convert(microtime(), 10, 36);
            }
            return Util::addParameter($url, 'nocache', $rand_num);
        } else {
            return $url;
        }
    }

    /**
     * Returns a hidden form input containing the session name and id.
     *
     * @param boolean $append_session  0 = only if needed, 1 = always.
     *
     * @return string  The hidden form input, if needed/requested.
     */
    function formInput($append_session = 0)
    {
        if ($append_session == 1 ||
            !isset($_COOKIE[session_name()])) {
            return '<input type="hidden" name="' . htmlspecialchars(session_name()) . '" value="' . htmlspecialchars(session_id()) . "\" />\n";
        } else {
            return '';
        }
    }

    /**
     * Prints a hidden form input containing the session name and id.
     *
     * @param boolean $append_session  0 = only if needed, 1 = always.
     */
    function pformInput($append_session = 0)
    {
        echo Util::formInput($append_session);
    }

    /**
     * If magic_quotes_gpc is in use, run stripslashes() on $var.
     *
     * @param string &$var  The string to un-quote, if necessary.
     *
     * @return string  $var, minus any magic quotes.
     */
    function dispelMagicQuotes(&$var)
    {
        static $magic_quotes;

        if (!isset($magic_quotes)) {
            $magic_quotes = get_magic_quotes_gpc();
        }

        if ($magic_quotes) {
            if (!is_array($var)) {
                $var = stripslashes($var);
            } else {
                array_walk($var, array('Util', 'dispelMagicQuotes'));
            }
        }

        return $var;
    }

    /**
     * Gets a form variable from GET or POST data, stripped of magic quotes if
     * necessary. If the variable is somehow set in both the GET data and the
     * POST data, the value from the POST data will be returned and the GET
     * value will be ignored.
     *
     * @param string $var      The name of the form variable to look for.
     * @param string $default  The value to return if the variable is not
     *                         there.
     *
     * @return string  The cleaned form variable, or $default.
     */
    function getFormData($var, $default = null)
    {
        return (($val = Util::getPost($var)) !== null)
            ? $val : Util::getGet($var, $default);
    }

    /**
     * Gets a form variable from GET data, stripped of magic quotes if
     * necessary. This function will NOT return a POST variable.
     *
     * @param string $var      The name of the form variable to look for.
     * @param string $default  The value to return if the variable is not
     *                         there.
     *
     * @return string  The cleaned form variable, or $default.
     */
    function getGet($var, $default = null)
    {
        return (isset($_GET[$var]))
            ? Util::dispelMagicQuotes($_GET[$var])
            : $default;
    }

    /**
     * Gets a form variable from POST data, stripped of magic quotes if
     * necessary. This function will NOT return a GET variable.
     *
     * @param string $var      The name of the form variable to look for.
     * @param string $default  The value to return if the variable is not
     *                         there.
     *
     * @return string  The cleaned form variable, or $default.
     */
    function getPost($var, $default = null)
    {
        return (isset($_POST[$var]))
            ? Util::dispelMagicQuotes($_POST[$var])
            : $default;
    }

    /**
     * Determines the location of the system temporary directory.
     *
     * @return string  A directory name which can be used for temp files.
     *                 Returns false if one could not be found.
     */
    function getTempDir()
    {
        /* First, try PHP's upload_tmp_dir directive. */
        $tmp = ini_get('upload_tmp_dir');

        /* Otherwise, try to determine the TMPDIR environment
         * variable. */
        if (empty($tmp)) {
            $tmp = getenv('TMPDIR');
        }

        /* If we still cannot determine a value, then cycle through a
         * list of preset possibilities. */
        $tmp_locations = array('/tmp', '/var/tmp', 'c:\WUTemp', 'c:\temp',
                               'c:\windows\temp', 'c:\winnt\temp');
        while (empty($tmp) && count($tmp_locations)) {
            $tmp_check = array_shift($tmp_locations);
            if (@is_dir($tmp_check)) {
                $tmp = $tmp_check;
            }
        }

        /* If it is still empty, we have failed, so return false;
         * otherwise return the directory determined. */
        return empty($tmp) ? false : $tmp;
    }

    /**
     * Creates a temporary filename for the lifetime of the script, and
     * (optionally) register it to be deleted at request shutdown.
     *
     * @param string $prefix   Prefix to make the temporary name more
     *                         recognizable.
     * @param boolean $delete  Delete the file at the end of the request?
     * @param string $dir      Directory to create the temporary file in.
     * @param boolean $secure  If deleting file, should we securely delete the
     *                         file?
     *
     * @return string   Returns the full path-name to the temporary file.
     *                  Returns false if a temp file could not be created.
     */
    function getTempFile($prefix = '', $delete = true, $dir = '', $secure = false)
    {
        if (empty($dir) || !is_dir($dir)) {
            $tmp_dir = Util::getTempDir();
        } else {
            $tmp_dir = $dir;
        }

        if (empty($tmp_dir)) {
            return false;
        }

        $tmp_file = tempnam($tmp_dir, $prefix);

        /* If the file was created, then register it for deletion and return */
        if (empty($tmp_file)) {
            return false;
        } else {
            if ($delete) {
                Util::deleteAtShutdown($tmp_file, true, $secure);
            }
            return $tmp_file;
        }
    }

    /**
     * Creates a temporary directory in the system's temporary directory.
     *
     * @param boolean $delete   Delete the temporary directory at the end of
     *                          the request?
     * @param string $temp_dir  Use this temporary directory as the directory
     *                          where the temporary directory will be created.
     *
     * @return string  The pathname to the new temporary directory.
     *                 Returns false if directory not created.
     */
    function createTempDir($delete = true, $temp_dir = null)
    {
        if (is_null($temp_dir)) {
            $temp_dir = Util::getTempDir();
        }

        if (empty($temp_dir)) {
            return false;
        }

        /* Get the first 8 characters of a random string to use as a temporary
           directory name. */
        do {
            $temp_dir .= '/' . substr(base_convert(mt_rand() . microtime(), 10, 36), 0, 8);
        } while (file_exists($temp_dir));

        $old_umask = umask(0000);
        if (!mkdir($temp_dir, 0700)) {
            $temp_dir = false;
        } elseif ($delete) {
            Util::deleteAtShutdown($temp_dir);
        }
        umask($old_umask);

        return $temp_dir;
    }

    /**
     * Returns the canonical path of the string.  Like PHP's built-in
     * realpath() except the directory need not exist on the local server.
     *
     * Algorithim loosely based on code from the Perl File::Spec::Unix module
     * (version 1.5).
     *
     * @since Horde 3.0.5
     *
     * @param string $path  A file path.
     *
     * @return string  The canonicalized file path.
     */
    function realPath($path)
    {
        /* Standardize on UNIX directory separators. */
        if (substr(PHP_OS, 0, 3) == 'WIN') {
            $path = str_replace('\\', '/', $path);
        }

        /* xx////xx -> xx/xx
         * xx/././xx -> xx/xx */
        $path = preg_replace(array("|/+|", "@(/\.)+(/|\Z(?!\n))@"), array('/', '/'), $path);

        /* ./xx -> xx */
        if ($path != './') {
            $path = preg_replace("|^(\./)+|", '', $path);
        }

        /* /../../xx -> xx */
        $path = preg_replace("|^/(\.\./?)+|", '/', $path);

        /* xx/ -> xx */
        if ($path != '/') {
            $path = preg_replace("|/\Z(?!\n)|", '', $path);
        }

        /* /xx/.. -> / */
        while (strpos($path, '/..') !== false) {
            $path = preg_replace("|/[^/]+/\.\.|", '', $path);
        }

        return empty($path) ? '/' : $path;
    }

    /**
     * Removes given elements at request shutdown.
     *
     * If called with a filename will delete that file at request shutdown; if
     * called with a directory will remove that directory and all files in that
     * directory at request shutdown.
     *
     * If called with no arguments, return all elements to be deleted (this
     * should only be done by Util::_deleteAtShutdown).
     *
     * The first time it is called, it initializes the array and registers
     * Util::_deleteAtShutdown() as a shutdown function - no need to do so
     * manually.
     *
     * The second parameter allows the unregistering of previously registered
     * elements.
     *
     * @param string $filename   The filename to be deleted at the end of the
     *                           request.
     * @param boolean $register  If true, then register the element for
     *                           deletion, otherwise, unregister it.
     * @param boolean $secure    If deleting file, should we securely delete
     *                           the file?
     */
    function deleteAtShutdown($filename = false, $register = true,
                              $secure = false)
    {
        static $dirs, $files, $securedel;

        /* Initialization of variables and shutdown functions. */
        if (is_null($dirs)) {
            $dirs = array();
            $files = array();
            $securedel = array();
            register_shutdown_function(array('Util', '_deleteAtShutdown'));
        }

        if ($filename) {
            if ($register) {
                if (@is_dir($filename)) {
                    $dirs[$filename] = true;
                } else {
                    $files[$filename] = true;
                }
                if ($secure) {
                    $securedel[$filename] = true;
                }
            } else {
                unset($dirs[$filename]);
                unset($files[$filename]);
                unset($securedel[$filename]);
            }
        } else {
            return array($dirs, $files, $securedel);
        }
    }

    /**
     * Deletes registered files at request shutdown.
     *
     * This function should never be called manually; it is registered as a
     * shutdown function by Util::deleteAtShutdown() and called automatically
     * at the end of the request. It will retrieve the list of folders and
     * files to delete from Util::deleteAtShutdown()'s static array, and then
     * iterate through, deleting folders recursively.
     *
     * Contains code from gpg_functions.php.
     * Copyright (c) 2002-2003 Braverock Ventures
     *
     * @access private
     */
    function _deleteAtShutdown()
    {
        $registered = Util::deleteAtShutdown();
        $dirs = $registered[0];
        $files = $registered[1];
        $secure = $registered[2];

        foreach ($files as $file => $val) {
            /* Delete files */
            if ($val && @file_exists($file)) {
                /* Should we securely delete the file by overwriting the
                   data with a random string? */
                if (isset($secure[$file])) {
                    $random_str = '';
                    for ($i = 0; $i < filesize($file); $i++) {
                        $random_str .= chr(mt_rand(0, 255));
                    }
                    $fp = fopen($file, 'r+');
                    fwrite($fp, $random_str);
                    fclose($fp);
                }
                @unlink($file);
            }
        }

        foreach ($dirs as $dir => $val) {
            /* Delete directories */
            if ($val && @file_exists($dir)) {
                /* Make sure directory is empty. */
                $dir_class = dir($dir);
                while (false !== ($entry = $dir_class->read())) {
                    if ($entry != '.' && $entry != '..') {
                        @unlink($dir . '/' . $entry);
                    }
                }
                $dir_class->close();
                @rmdir($dir);
            }
        }
    }

    /**
     * Outputs javascript code to close the current window.
     *
     * @param string $code  Any addtional javascript code to run before
     *                      closing the window.
     */
    function closeWindowJS($code = '')
    {
        echo '<script type="text/javascript">' . $code .
            'window.close();</script>';
    }

    /**
     * Caches the result of extension_loaded() calls.
     *
     * @access private
     *
     * @param string $ext  The extension name.
     *
     * @return boolean  Is the extension loaded?
     */
    function extensionExists($ext)
    {
        static $cache = array();

        if (!isset($cache[$ext])) {
            $cache[$ext] = extension_loaded($ext);
        }

        return $cache[$ext];
    }

    /**
     * Tries to load a PHP extension, behaving correctly for all operating
     * systems.
     *
     * @param string $ext  The extension to load.
     *
     * @return boolean  True if the extension is now loaded, false if not.
     *                  True can mean that the extension was already loaded,
     *                  OR was loaded dynamically.
     */
    function loadExtension($ext)
    {
        /* If $ext is already loaded, our work is done. */
        if (Util::extensionExists($ext)) {
            return true;
        }

        /* See if we can call dl() at all, by the current ini settings. */
        if ((ini_get('enable_dl') != 1) || (ini_get('safe_mode') == 1)) {
            return false;
        }

        if (substr(PHP_OS, 0, 3) == 'WIN') {
            $suffix = 'dll';
        } else {
            switch (PHP_OS) {
            case 'HP-UX':
                $suffix = 'sl';
                break;

            case 'AIX':
                $suffix = 'a';
                break;

            case 'OSX':
                $suffix = 'bundle';
                break;

            default:
                $suffix = 'so';
            }
        }

        return @dl($ext . '.' . $suffix) || @dl('php_' . $ext . '.' . $suffix);
    }

    /**
     * Checks if all necessary parameters for a driver's configuration are set
     * and returns a PEAR_Error if something is missing.
     *
     * @param array $params   The configuration array with all parameters.
     * @param array $fields   An array with mandatory parameter names for this
     *                        driver.
     * @param string $name    The clear text name of the driver. If not
     *                        specified, the application name will be used.
     * @param array $info     A hash containing detailed information about the
     *                        driver. Will be passed as the userInfo to the
     *                        PEAR_Error.
     */
    function assertDriverConfig($params, $fields, $name, $info = array())
    {
        $info = array_merge($info,
                            array('params' => $params,
                                  'fields' => $fields,
                                  'name' => $name));

        if (!is_array($params) || !count($params)) {
            require_once 'PEAR.php';
            return PEAR::throwError(sprintf(_("No configuration information specified for %s."), $name),
                                    HORDE_ERROR_DRIVER_CONFIG_MISSING,
                                    $info);
        }

        foreach ($fields as $field) {
            if (!isset($params[$field])) {
                require_once 'PEAR.php';
                return PEAR::throwError(sprintf(_("Required \"%s\" not specified in configuration."), $field, $name),
                                        HORDE_ERROR_DRIVER_CONFIG,
                                        $info);
            }
        }
    }

    /**
     * Returns a format string to be used by strftime().
     *
     * @param string $format  A format string as used by date().
     *
     * @return string  A format string as similar as possible to $format.
     */
    function date2strftime($format)
    {
        $dateSymbols = array('a', 'A', 'd', 'D', 'F', 'g', 'G', 'h', 'H', 'i', 'j', 'l', 'm', 'M', 'n', 'r', 's', 'T', 'w', 'W', 'y', 'Y', 'z', 'm/d/Y', 'M', "\n", 'g:i a', 'G:i', "\t", 'H:i:s', '%');
        $strftimeSymbols = array('%p', '%p', '%d', '%a', '%B', '%I', '%H', '%I', '%H', '%M', '%e', '%A', '%m', '%b', '%m', '%a, %e %b %Y %T %Z', '%S', '%Z', '%w', '%V', '%y', '%Y', '%j', '%D', '%h', '%n', '%r', '%R', '%t', '%T', '%%');

        $result = '';
        for ($pos = 0; $pos < strlen($format);) {
            for ($symbol = 0; $symbol < count($dateSymbols); $symbol++) {
                if (strpos($format, $dateSymbols[$symbol], $pos) === $pos) {
                    $result .= $strftimeSymbols[$symbol];
                    $pos += strlen($dateSymbols[$symbol]);
                    continue 2;
                }
            }
            $result .= substr($format, $pos, 1);
            $pos++;
        }

        return $result;
    }

    /**
     * Returns a format string to be used by date().
     *
     * @param string $format  A format string as used by strftime().
     *
     * @return string  A format string as similar as possible to $format.
     */
    function strftime2date($format)
    {
        $dateSymbols = array('a', 'A', 'd', 'D', 'F', 'g', 'G', 'h', 'H', 'i', 'j', 'l', 'm', 'M', 'n', 'r', 's', 'T', 'w', 'W', 'y', 'Y', 'z', 'm/d/Y', 'M', "\n", 'g:i a', 'G:i', "\t", 'H:i:s', '%');
        $strftimeSymbols = array('%p', '%p', '%d', '%a', '%B', '%I', '%H', '%I', '%H', '%M', '%e', '%A', '%m', '%b', '%m', '%a, %e %b %Y %T %Z', '%S', '%Z', '%w', '%V', '%y', '%Y', '%j', '%D', '%h', '%n', '%r', '%R', '%t', '%T', '%%');

        return str_replace($strftimeSymbols, $dateSymbols, $format);
    }

}

if (!function_exists('_')) {
    function _($string)
    {
        return $string;
    }

    function bindtextdomain()
    {
    }

    function textdomain()
    {
    }

}