File: Registry.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 (1144 lines) | stat: -rw-r--r-- 38,010 bytes parent folder | download
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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
<?php

/** Do not start a session. */
define('HORDE_SESSION_NONE', 1);

/** Do not write changes to session. */
define('HORDE_SESSION_READONLY', 2);

/**
 * The Registry:: class provides a set of methods for communication
 * between Horde applications and keeping track of application
 * configuration information.
 *
 * $Horde: framework/Horde/Horde/Registry.php,v 1.243.2.22 2006/05/04 22:35:26 jan Exp $
 *
 * Copyright 1999-2006 Chuck Hagenbuch <chuck@horde.org>
 * Copyright 1999-2006 Jon Parise <jon@horde.org>
 * Copyright 1999-2006 Anil Madhavapeddy <anil@recoil.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>
 * @author  Anil Madhavapeddy <anil@recoil.org>
 * @since   Horde 1.3
 * @package Horde_Framework
 */
class Registry {

    /**
     * Hash storing all of the known services and callbacks.
     *
     * @var array
     */
    var $_apiCache = array();

    /**
     * Hash storing all known data types.
     *
     * @var array
     */
    var $_typeCache = array();

    /**
     * Hash storing all of the registered interfaces that applications
     * provide.
     *
     * @var array
     */
    var $_interfaces = array();

    /**
     * Hash storing information on each registry-aware application.
     *
     * @var array
     */
    var $applications = array();

    /**
     * Stack of in-use applications.
     *
     * @var array
     */
    var $_appStack = array();

    /**
     * Quick pointer to the current application.
     *
     * @var string
     */
    var $_currentApp = null;

    /**
     * Cache of $prefs objects
     *
     * @var array
     */
    var $_prefsCache = array();

    /**
     * Cache of application configurations.
     *
     * @var array
     */
    var $_confCache = array();

    /**
     * Are we using registry caching?
     *
     * @param boolean
     */
    var $_usecache = false;

    /**
     * Update these cache entries on shutdown.
     *
     * @param array
     */
    var $_updatecache = array();

    /**
     * Update these mtime entries on shutdown.
     *
     * @param array
     */
    var $_updatemtime = array();

    /**
     * Don't update cache at end of request?
     *
     * @param boolean
     */
    var $_nocache = false;

    /**
     * Returns a reference to the global Registry object, only
     * creating it if it doesn't already exist.
     *
     * This method must be invoked as: $registry = &Registry::singleton()
     *
     * @param integer $session_flags  Any session flags.
     *
     * @return Registry  The Horde Registry instance.
     */
    function &singleton($session_flags = 0)
    {
        static $registry;

        if (!isset($registry)) {
            $registry = new Registry($session_flags);
        }

        return $registry;
    }

    /**
     * Create a new registry instance. Should never be called except
     * by &Registry::singleton().
     *
     * @param integer $session_flags  Any session flags.
     *
     * @access private
     */
    function Registry($session_flags = 0)
    {
        /* Import and global Horde's configuration values. */
        $this->importConfig('horde');

        /* Start a session. */
        if ($session_flags & HORDE_SESSION_NONE) {
            /* Never start a session if the session flags include
               HORDE_SESSION_NONE. */
            $_SESSION = array();
        } else {
            Horde::setupSessionHandler();
            @session_start();
            if ($session_flags & HORDE_SESSION_READONLY) {
                /* Close the session immediately so no changes can be
                   made but values are still available. */
                @session_write_close();
            } else {
                $this->_usecache = true;
            }
        }

        /* Initialize the localization routines and variables. */
        NLS::setLang();
        NLS::setTextdomain('horde', HORDE_BASE . '/locale', NLS::getCharset());
        String::setDefaultCharset(NLS::getCharset());

        $reg_mtime = filemtime(HORDE_BASE . '/config/registry.php');

        /* Load registry information from the session, if available. */
        if (!empty($_SESSION['_registrycache']) &&
            ($_SESSION['_registrymtime']['registry.php'] == $reg_mtime)) {
            foreach ($_SESSION['_registrycache'] as $key => $val) {
                $this->$key = $val;
            }
        } else {
            /* Read the registry configuration file. */
            require_once HORDE_BASE . '/config/registry.php';

            /* Stop system if Horde is inactive. */
            if ($this->applications['horde']['status'] == 'inactive') {
                Horde::fatal(_("This system is currently deactivated."), __FILE__, __LINE__);
            }

            /* Scan for all APIs provided by each app, and set other
             * common defaults like templates and graphics. */
            $appList = array_keys($this->applications);
            foreach ($appList as $appName) {
                $app = &$this->applications[$appName];
                if (($app['status'] == 'heading') ||
                    ($app['status'] == 'inactive') ||
                    ($app['status'] == 'admin' && !Auth::isAdmin())) {
                    continue;
                }
                if (isset($app['provides'])) {
                    if (is_array($app['provides'])) {
                        foreach ($app['provides'] as $interface) {
                            $this->_interfaces[$interface] = $appName;
                        }
                    } else {
                        $this->_interfaces[$app['provides']] = $appName;
                    }
                }
                if (!isset($app['templates']) && isset($app['fileroot'])) {
                    $app['templates'] = $app['fileroot'] . '/templates';
                }
                if (!isset($app['jsuri']) && isset($app['webroot'])) {
                    $app['jsuri'] = $app['webroot'] . '/js';
                }
                if (!isset($app['jsfs']) && isset($app['fileroot'])) {
                    $app['jsfs'] = $app['fileroot'] . '/js';
                }
                if (!isset($app['themesuri']) && isset($app['webroot'])) {
                    $app['themesuri'] = $app['webroot'] . '/themes';
                }
                if (!isset($app['themesfs']) && isset($app['fileroot'])) {
                    $app['themesfs'] = $app['fileroot'] . '/themes';
                }
            }

            /* Clear out the API & Type caches, if they exists. */
            $this->_apiCache = $this->_typeCache = array();

            $this->_cacheVars(array('applications', '_interfaces', '_apiCache', '_typeCache'), array('registry.php' => $reg_mtime));
        }

        /* Create the global Perms object. */
        $GLOBALS['perms'] = &Perms::singleton();

        /* Attach javascript notification listener. */
        $notification = &Notification::singleton();
        $notification->attach('javascript');

        /* Register access key logger for translators. */
        if (@$GLOBALS['conf']['log_accesskeys']) {
            register_shutdown_function(create_function('', 'Horde::getAccessKey(null, null, true);'));
        }
    }

    /**
     * Add a list of variable names and modification times to be cached.
     *
     * @access private
     *
     * @param array $vars    A list of variable names to be cached.
     * @param array $mtimes  A list of file modificaion times to be cached.
     */
    function _cacheVars($vars = array(), $mtimes = array())
    {
        static $regcacheshutdown = false;

        if ($this->_usecache) {
            $this->_updatecache = array_merge($this->_updatecache, $vars);
            $this->_updatemtime = array_merge($this->_updatemtime, $mtimes);
            if (!$regcacheshutdown) {
                register_shutdown_function(array(&$this, '_shutdowncache'));
                $regcacheshutdown = true;
            }
        }
    }

    /**
     * Stores cacheable member variables in the session at shutdown.
     *
     * @access private
     */
    function _shutdowncache()
    {
        if (isset($_SESSION) && Auth::getAuth() && !$this->_nocache) {
            if (!isset($_SESSION['_registrycache'])) {
                $_SESSION['_registrycache'] = array();
            }

            foreach (array_unique($this->_updatecache) as $val) {
                $_SESSION['_registrycache'][$val] = $this->$val;
            }

            if (!isset($_SESSION['_registrymtime'])) {
                $_SESSION['_registrymtime'] = array();
            }

            foreach (array_unique($this->_updatemtime) as $key => $val) {
                $_SESSION['_registrymtime'][$key] = $val;
            }
        }
    }

    /**
     * Clear the registry cache.
     *
     * @since Horde 3.1
     */
    function clearCache()
    {
        unset($_SESSION['_registrycache']);
        $this->_nocache = true;
    }

    /**
     * Fills the registry's API cache with the available services.
     *
     * @access private
     */
    function _fillAPICache()
    {
        if (!empty($this->_apiCache)) {
            return;
        }

        $status = array('active', 'notoolbar', 'hidden');
        if (Auth::isAdmin()) {
            $status[] = 'admin';
        }
        $apps = $this->listApps($status);
        foreach ($apps as $app) {
            $_services = $_types = null;
            $api = $this->get('fileroot', $app) . '/lib/api.php';
            if (is_readable($api)) {
                include_once $api;
            }
            if (!isset($_services)) {
                $this->_apiCache[$app] = array();
            } else {
                $this->_apiCache[$app] = $_services;
            }
            if (isset($_types)) {
                foreach ($_types as $type => $params) {
                    /* Prefix non-Horde types with the application
                     * name. */
                    $prefix = $app == 'horde' ? '' : "${app}_";
                    $this->_typeCache[$prefix . $type] = $params;
                }
            }
        }

        $this->_cacheVars(array('_apiCache', '_typeCache'));
    }

    /**
     * Return a list of the installed and registered applications.
     *
     * @param array   $filter      An array of the statuses that should be
     *                             returned. Defaults to non-hidden.
     * @param boolean $assoc       Associative array with app names as keys.
     * @param integer $permission  The permission level to check for in the
     *                             list. Defaults to PERMS_SHOW.
     *
     * @return array  List of apps registered with Horde. If no
     *                applications are defined returns an empty array.
     */
    function listApps($filter = null, $assoc = false, $permission = PERMS_SHOW)
    {
        $apps = array();
        if (is_null($filter)) {
            $filter = array('notoolbar', 'active');
        }

        foreach ($this->applications as $app => $params) {
            if (in_array($params['status'], $filter) &&
                (defined('AUTH_HANDLER') || $this->hasPermission($app, $permission))) {
                $assoc ? $apps[$app] = $app : $apps[] = $app;
            }
        }

        return $apps;
    }

    /**
     * Returns all available registry APIs.
     *
     * @return array  The API list.
     */
    function listAPIs()
    {
        static $apis = array();
        if ($apis) {
            return $apis;
        }

        foreach (array_keys($this->_interfaces) as $interface) {
            @list($api, ) = explode('/', $interface);
            $apis[] = $api;
        }

        return array_unique($apis);
    }

    /**
     * Returns all of the available registry methods, or alternately
     * only those for a specified API.
     *
     * @param string $api  Defines the API for which the methods shall be
     *                     returned.
     *
     * @return array  The method list.
     */
    function listMethods($api = null)
    {
        $methods = array();

        $this->_fillAPICache();

        foreach (array_keys($this->applications) as $app) {
            if (isset($this->applications[$app]['provides'])) {
                $provides = $this->applications[$app]['provides'];
                if (!is_array($provides)) {
                    $provides = array($provides);
                }
            } else {
                $provides = array();
            }

            foreach ($provides as $method) {
                if (strpos($method, '/') !== false) {
                    if (is_null($api) ||
                        (substr($method, 0, strlen($api)) == $api)) {
                        $methods[] = $method;
                    }
                } elseif (is_null($api) || ($method == $api)) {
                    if (isset($this->_apiCache[$app])) {
                        foreach (array_keys($this->_apiCache[$app]) as $service) {
                            $methods[] = $method . '/' . $service;
                        }
                    }
                }
            }
        }

        return array_unique($methods);
    }

    /**
     * Returns all of the available registry data types.
     *
     * @return array  The data type list.
     */
    function listTypes()
    {
        $this->_fillAPICache();
        return $this->_typeCache;
    }

    /**
     * Returns a method's signature.
     *
     * @param string $method  The full name of the method to check for.
     *
     * @return array  A two dimensional array. The first element contains an
     *                array with the parameter names, the second one the return
     *                type.
     */
    function getSignature($method)
    {
        if (!($app = $this->hasMethod($method))) {
            return;
        }

        $this->_fillAPICache();

        @list(, $function) = explode('/', $method);
        if (isset($this->_apiCache[$app][$function]['type']) &&
            isset($this->_apiCache[$app][$function]['args'])) {
            return array($this->_apiCache[$app][$function]['args'], $this->_apiCache[$app][$function]['type']);
        }
    }

    /**
     * Determine if an interface is implemented by an active application.
     *
     * @param string $interface  The interface to check for.
     *
     * @return mixed  The application implementing $interface if we have it,
     *                false if the interface is not implemented.
     */
    function hasInterface($interface)
    {
        return !empty($this->_interfaces[$interface]) ?
            $this->_interfaces[$interface] :
            false;
    }

    /**
     * Determine if a method has been registered with the registry.
     *
     * @param string $method  The full name of the method to check for.
     * @param string $app     Only check this application.
     *
     * @return mixed  The application implementing $method if we have it,
     *                false if the method doesn't exist.
     */
    function hasMethod($method, $app = null)
    {
        if (is_null($app)) {
            @list($interface, $call) = explode('/', $method);
            if (!empty($this->_interfaces[$method])) {
                $app = $this->_interfaces[$method];
            } elseif (!empty($this->_interfaces[$interface])) {
                $app = $this->_interfaces[$interface];
            } else {
                return false;
            }
        } else {
            $call = $method;
        }

        $this->_fillAPICache();

        return !empty($this->_apiCache[$app][$call]) ? $app : false;
    }

    /**
     * Return the hook corresponding to the default package that
     * provides the functionality requested by the $method
     * parameter. $method is a string consisting of
     * "packagetype/methodname".
     *
     * @param string $method  The method to call.
     * @param array $args     Arguments to the method.
     *
     * @return  TODO
     *          Returns PEAR_Error on error.
     */
    function call($method, $args = array())
    {
        @list($interface, $call) = explode('/', $method);

        if (!empty($this->_interfaces[$method])) {
            $app = $this->_interfaces[$method];
        } elseif (!empty($this->_interfaces[$interface])) {
            $app = $this->_interfaces[$interface];
        } else {
            return PEAR::raiseError('The method "' . $method . '" is not defined in the Horde Registry.');
        }

        return $this->callByPackage($app, $call, $args);
    }

    /**
     * Output the hook corresponding to the specific package named.
     *
     * @param string $app   The application being called.
     * @param string $call  The method to call.
     * @param array $args   Arguments to the method.
     *
     * @return  TODO
     *          Returns PEAR_Error on error.
     */
    function callByPackage($app, $call, $args = array())
    {
        /* Note: calling hasMethod() makes sure that we've cached
         * $app's services and included the API file, so we don't try
         * to do it again explicitly in this method. */
        if (!$this->hasMethod($call, $app)) {
            return PEAR::raiseError(sprintf('The method "%s" is not defined in the API for %s.', $call, $app));
        }

        /* Load the API now. */
        if (!empty($_SESSION['_registrycache']['_apiCache'])) {
            $api = $this->get('fileroot', $app) . '/lib/api.php';
            if (is_readable($api)) {
                include_once $api;
            }
        }

        /* Make sure that the function actually exists. */
        $function = '_' . $app . '_' . $call;
        if (!function_exists($function)) {
            return PEAR::raiseError('The function implementing ' . $call . ' (' . $function . ') is not defined in ' . $app . '\'s API.');
        }

        $checkPerms = isset($this->_apiCache[$app][$call]['checkperms']) ?
                      $this->_apiCache[$app][$call]['checkperms'] : true;

        /* Switch application contexts now, if necessary, before
         * including any files which might do it for us. Return an
         * error immediately if pushApp() fails. */
        $pushed = $this->pushApp($app, $checkPerms);
        if (is_a($pushed, 'PEAR_Error')) {
            return $pushed;
        }

        $res = call_user_func_array($function, $args);

        /* If we changed application context in the course of this
         * call, undo that change now. */
        if ($pushed === true) {
            $this->popApp();
        }

        return $res;
    }

    /**
     * Return the hook corresponding to the default package that
     * provides the functionality requested by the $method
     * parameter. $method is a string consisting of
     * "packagetype/methodname".
     *
     * @param string $method  The method to link to.
     * @param array $args     Arguments to the method.
     * @param mixed $extra    Extra, non-standard arguments to the method.
     *
     * @return  TODO
     *          Returns PEAR_Error on error.
     */
    function link($method, $args = array(), $extra = '')
    {
        @list($interface, $call) = explode('/', $method);

        if (!empty($this->_interfaces[$method])) {
            $app = $this->_interfaces[$method];
        } elseif (!empty($this->_interfaces[$interface])) {
            $app = $this->_interfaces[$interface];
        } else {
            return PEAR::raiseError('The method "' . $method . '" is not defined in the Horde Registry.');
        }

        return $this->linkByPackage($app, $call, $args, $extra);
    }

    /**
     * Output the hook corresponding to the specific package named.
     *
     * @param string $app   The application being called.
     * @param string $call  The method to link to.
     * @param array $args   Arguments to the method.
     * @param mixed $extra  Extra, non-standard arguments to the method.
     *
     * @return  TODO
     *          Returns PEAR_Error on error.
     */
    function linkByPackage($app, $call, $args = array(), $extra = '')
    {
        /* Note: calling hasMethod makes sure that we've cached $app's
         * services and included the API file, so we don't try to do
         * it it again explicitly in this method. */
        if (!$this->hasMethod($call, $app)) {
            return PEAR::raiseError('The method "' . $call . '" is not defined in ' . $app . '\'s API.');
        }

        /* Make sure the link is defined. */
        if (empty($this->_apiCache[$app][$call]['link'])) {
            return PEAR::raiseError('The link ' . $call . ' is not defined in ' . $app . '\'s API.');
        }

        /* Initial link value. */
        $link = $this->_apiCache[$app][$call]['link'];

        /* Fill in html-encoded arguments. */
        foreach ($args as $key => $val) {
            $link = str_replace('%' . $key . '%', htmlentities($val), $link);
        }
        if (isset($this->applications[$app]['webroot'])) {
            $link = str_replace('%application%', $this->get('webroot', $app), $link);
        }

        /* Replace htmlencoded arguments that haven't been specified with
           an empty string (this is where the default would be substituted
           in a stricter registry implementation). */
        $link = preg_replace('|%.+%|U', '', $link);

        /* Fill in urlencoded arguments. */
        foreach ($args as $key => $val) {
            $link = str_replace('|' . String::lower($key) . '|', urlencode($val), $link);
        }

        /* Append any extra, non-standard arguments. */
        if (is_array($extra)) {
            $extra_args = '';
            foreach ($extra as $key => $val) {
                $extra_args .- '&' . urlencode($key) . '=' . urlencode($val);
            }
        } else {
            $extra_args = $extra;
        }
        $link = str_replace('|extra|', $extra_args, $link);

        /* Replace html-encoded arguments that haven't been specified with
           an empty string (this is where the default would be substituted
           in a stricter registry implementation). */
        $link = preg_replace('|\|.+\||U', '', $link);

        return $link;
    }

    /**
     * Replace any %application% strings with the filesystem path to the
     * application.
     *
     * @param string $path  The application string.
     * @param string $app   The application being called.
     *
     * @return  TODO
     *          Returns PEAR_Error on error.
     */
    function applicationFilePath($path, $app = null)
    {
        if (is_null($app)) {
            $app = $this->_currentApp;
        }

        if (!isset($this->applications[$app])) {
            return PEAR::raiseError(sprintf(_("\"%s\" is not configured in the Horde Registry."), $app));
        }

        return str_replace('%application%', $this->applications[$app]['fileroot'], $path);
    }

    /**
     * Replace any %application% strings with the web path to the application.
     *
     * @param string $path  The application string.
     * @param string $app   The application being called.
     *
     * @return  TODO
     *          Returns PEAR_Error on error.
     */
    function applicationWebPath($path, $app = null)
    {
        if (!isset($app)) {
            $app = $this->_currentApp;
        }

        return str_replace('%application%', $this->applications[$app]['webroot'], $path);
    }

    /**
     * Set the current application, adding it to the top of the Horde
     * application stack. If this is the first application to be
     * pushed, retrieve session information as well.
     *
     * pushApp() also reads the application's configuration file and
     * sets up its global $conf hash.
     *
     * @param string  $app         The name of the application to push.
     * @param boolean $checkPerms  Make sure that the current user has
     *                             permissions to the application being loaded
     *                             Defaults to true. Should ONLY be disabled by
     *                             system scripts (cron jobs, etc.) and scripts
     *                             that handle login.
     *
     * @return boolean  Whether or not the _appStack was modified.
     *                  Return PEAR_Error on error.
     */
    function pushApp($app, $checkPerms = true)
    {
        if ($app == $this->_currentApp) {
            return false;
        }

        /* Bail out if application is not present or inactive. */
        if (!isset($this->applications[$app]) ||
            $this->applications[$app]['status'] == 'inactive' ||
            ($this->applications[$app]['status'] == 'admin' && !Auth::isAdmin())) {
            Horde::fatal($app . ' is not activated', __FILE__, __LINE__);
        }

        /* If permissions checking is requested, return an error if
         * the current user does not have read perms to the
         * application being loaded. We allow access:
         *
         *  - To all admins.
         *  - To all authenticated users if no permission is set on $app.
         *  - To anyone who is allowed by an explicit ACL on $app. */
        if ($checkPerms && !$this->hasPermission($app)) {
            Horde::logMessage(sprintf('User %s does not have READ permission for %s', Auth::getAuth(), $app), __FILE__, __LINE__, PEAR_LOG_DEBUG);
            return PEAR::raiseError(sprintf(_("User %s is not authorised for %s."), Auth::getAuth(), $this->applications[$app]['name']), 'permission_denied');
        }

        /* Import this application's configuration values. */
        $success = $this->importConfig($app);
        if (is_a($success, 'PEAR_Error')) {
            return $success;
        }

        /* Load preferences after the configuration has been loaded to
         * make sure the prefs file has all the information it needs. */
        $this->loadPrefs($app);

        /* Reset the language in case there is a different one
         * selected in the preferences. */
        $language = '';
        if (isset($this->_prefsCache[$app]) &&
            isset($this->_prefsCache[$app]->_prefs['language'])) {
            $language = $this->_prefsCache[$app]->getValue('language');
        }
        NLS::setLang($language);
        NLS::setTextdomain($app, $this->applications[$app]['fileroot'] . '/locale', NLS::getCharset());
        String::setDefaultCharset(NLS::getCharset());

        /* Once we know everything succeeded and is in a consistent
         * state again, push the new application onto the stack. */
        $this->_appStack[] = $app;
        $this->_currentApp = $app;

        return true;
    }

    /**
     * Remove the current app from the application stack, setting the current
     * app to whichever app was current before this one took over.
     *
     * @return string  The name of the application that was popped.
     */
    function popApp()
    {
        /* Pop the current application off of the stack. */
        $previous = array_pop($this->_appStack);

        /* Import the new active application's configuration values
         * and set the gettext domain and the preferred language. */
        $this->_currentApp = count($this->_appStack) ? end($this->_appStack) : null;
        if ($this->_currentApp) {
            $this->importConfig($this->_currentApp);
            $this->loadPrefs($this->_currentApp);
            $language = $GLOBALS['prefs']->getValue('language');
            if (isset($language)) {
                NLS::setLang($language);
            }
            NLS::setTextdomain($this->_currentApp, $this->applications[$this->_currentApp]['fileroot'] . '/locale', NLS::getCharset());
            String::setDefaultCharset(NLS::getCharset());
        }

        return $previous;
    }

    /**
     * Return the current application - the app at the top of the application
     * stack.
     *
     * @return string  The current application.
     */
    function getApp()
    {
        return $this->_currentApp;
    }

    /**
     * Check permissions on an application.
     *
     * @return boolean  Whether or not access is allowed.
     */
    function hasPermission($app, $permission = PERMS_READ)
    {
        return Auth::isAdmin() ||
            ($GLOBALS['perms']->exists($app)
             ? $GLOBALS['perms']->hasPermission($app, Auth::getAuth(), $permission)
             : (bool)Auth::getAuth());
    }

    /**
     * Reads the configuration values for the given application and imports
     * them into the global $conf variable.
     *
     * @param string $app  The name of the application.
     *
     * @return boolean  True on success, PEAR_Error on error.
     */
    function importConfig($app)
    {
        /* Don't make config files global $registry themselves. */
        global $registry;

        /* Cache config values so that we don't re-read files on every
         * popApp() call. */
        if (!isset($this->_confCache[$app])) {
            if (!isset($this->_confCache['horde'])) {
                $conf = array();
                ob_start();
                $success = include HORDE_BASE . '/config/conf.php';
                $errors = ob_get_contents();
                ob_end_clean();
                if (!empty($errors)) {
                    return PEAR::raiseError('Failed to import Horde configuration: ' . strip_tags($errors));
                }
                if (!$success) {
                    return PEAR::raiseError('Failed to import Horde configuration.');
                }

                /* Initial Horde-wide settings. */

                /* Set the error reporting level in accordance with
                 * the config settings. */
                error_reporting($conf['debug_level']);

                /* Set the maximum execution time in accordance with
                 * the config settings. */
                @set_time_limit($conf['max_exec_time']);

                /* Set the umask according to config settings. */
                if (isset($conf['umask'])) {
                    umask($conf['umask']);
                }
            } else {
                $conf = $this->_confCache['horde'];
            }

            if ($app !== 'horde') {
                ob_start();
                $success = include $this->applications[$app]['fileroot'] . '/config/conf.php';
                $errors = ob_get_contents();
                ob_end_clean();
                if (!empty($errors)) {
                    return PEAR::raiseError('Failed to import application configuration for ' . $app . ': ' . strip_tags($errors));
                }
                if (!$success) {
                    return PEAR::raiseError('Failed to import application configuration for ' . $app);
                }
            }

            $this->_cacheVars(array('_confCache'));

            $this->_confCache[$app] = &$conf;
        }

        $GLOBALS['conf'] = &$this->_confCache[$app];
        return true;
    }

    /**
     * Loads the preferences for the current user for the current application
     * and imports them into the global $prefs variable.
     *
     * @param string $app  The name of the application.
     */
    function loadPrefs($app = null)
    {
        static $prefs_default = false;

        require_once 'Horde/Prefs.php';

        if ($app === null) {
            $app = $this->_currentApp;
        }

        /* If there is no logged in user, return an empty Prefs::
         * object with just default preferences. */
        if (!Auth::getAuth()) {
            $prefs = &Prefs::factory('session', $app, '', '', null, false);
            $prefs->retrieve();
            $this->_prefsCache[$app] = &$prefs;
            $GLOBALS['prefs'] = &$this->_prefsCache[$app];
            $prefs_default = true;
            return;
        }

        /* Cache prefs objects so that we don't re-load them on every
         * popApp() call. */
        if (!isset($this->_prefsCache[$app]) ||
            !empty($prefs_default)) {
            $prefs = &Prefs::factory($GLOBALS['conf']['prefs']['driver'], $app,
                                     Auth::getAuth(), Auth::getCredential('password'));
            $prefs->retrieve();
            $this->_prefsCache[$app] = &$prefs;
        }

        $GLOBALS['prefs'] = &$this->_prefsCache[$app];
    }

    /**
     * Unload preferences from an application or (if no application is
     * specified) from ALL applications. Useful when a user has logged
     * out but you need to continue on the same page, etc.
     *
     * After unloading, if there is an application on the app stack to
     * load preferences from, then we reload a fresh set.
     *
     * @param string $app  The application to unload prefrences for. If null,
     *                     ALL preferences are reset.
     */
    function unloadPrefs($app = null)
    {
        if ($app === null) {
            $this->_prefsCache = array();
        } elseif (isset($this->_prefsCache[$app])) {
            unset($this->_prefsCache[$app]);
        } else {
            return;
        }

        if ($this->_currentApp) {
            $this->loadPrefs();
        }
    }

    /**
     * Return the requested configuration parameter for the specified
     * application. If no application is specified, the value of
     * $this->_currentApp (the current application) is used. However,
     * if the parameter is not present for that application, the
     * Horde-wide value is used instead. If that is not present, we
     * return null.
     *
     * @param string $parameter  The configuration value to retrieve.
     * @param string $app        The application to get the value for.
     *
     * @return string  The requested parameter, or null if it is not set.
     */
    function get($parameter, $app = null)
    {
        if (is_null($app)) {
            $app = $this->_currentApp;
        }

        if (isset($this->applications[$app][$parameter])) {
            $pval = $this->applications[$app][$parameter];
        } else {
            if ($parameter == 'icon') {
                $pval = $this->_getIcon($app);
            } else {
                $pval = isset($this->applications['horde'][$parameter]) ? $this->applications['horde'][$parameter] : null;
            }
        }

        if ($parameter == 'name') {
            return _($pval);
        } else {
            return $pval;
        }
    }

    /**
     * Function to work out an application's graphics URI, taking into account
     * any themes directories that may be set up.
     *
     * @param string $app  The application for which to get the image
     *                     directory. If blank will default to current
     *                     application.
     *
     * @return string  The image directory uri path.
     */
    function getImageDir($app = null)
    {
        if (empty($app)) {
            $app = $this->_currentApp;
        }

        static $img_dir = array();
        if (isset($img_dir[$app])) {
            return $img_dir[$app];
        }

        /* This is the default location for the graphics. */
        $img_dir[$app] = $this->get('themesuri', $app) . '/graphics';

        static $theme_icons;

        /* Figure out if this is going to be overridden by any theme
         * settings. */
        if (isset($GLOBALS['prefs']) &&
            ($theme = $GLOBALS['prefs']->getValue('theme')) &&
            (isset($theme_icons) ||
             // backport security patch from Horde 3.1.7 for etch
             //((@include $this->get('themesfs', 'horde') . '/' . $theme . '/info.php') &&
             ((@include $this->get('themesfs', 'horde') . '/' . basename($theme) . '/info.php') &&
              isset($theme_icons))) &&
            in_array($app, $theme_icons)) {
            $img_dir[$app] = $this->get('themesuri', $app) . '/' . $theme . '/graphics';
        }

        return $img_dir[$app];
    }

    /**
     * Returns the path to an application's icon, respecting whether the
     * current theme has its own icons.
     *
     * @access private
     *
     * @param string $app  The application for which to get the icon.
     */
    function _getIcon($app)
    {
        return $this->getImageDir($app) . '/' . $app . '.png';
    }

    /**
     * Query the initial page for an application - the webroot, if there is no
     * initial_page set, and the initial_page, if it is set.
     *
     * @param string $app  The name of the application.
     *
     * @return string  URL pointing to the inital page of the application.
     *                 Returns PEAR_Error on error.
     */
    function getInitialPage($app = null)
    {
        if (is_null($app)) {
            $app = $this->_currentApp;
        }

        if (!isset($this->applications[$app])) {
            return PEAR::raiseError(sprintf(_("\"%s\" is not configured in the Horde Registry."), $app));
        }
        return $this->applications[$app]['webroot'] . '/' . (isset($this->applications[$app]['initial_page']) ? $this->applications[$app]['initial_page'] : '');
    }

    /**
     * @since Horde 3.1
     */
    function __get($api)
    {
        if (in_array($api, $this->listAPIs())) {
            return new RegistryCaller($this, $api);
        }
    }

    /**
     * Clone should never be called on Registry objects. If it is, die.
     *
     * @since Horde 3.1
     */
    function __clone()
    {
        Horde::fatal('Registry objects should never be cloned.', __FILE__, __LINE__);
    }

}

/**
 * @package Horde_Framework
 * @since Horde 3.1
 */
class RegistryCaller {

    var $registry;
    var $api;

    function __construct($registry, $api)
    {
        $this->registry = $registry;
        $this->api = $api;
    }

    function __call($method, $args)
    {
        return $this->registry->call($this->api . '/' . $method, $args);
    }

}