/
Registry.php
2920 lines (2553 loc) · 97.2 KB
/
Registry.php
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
<?php
/**
* Copyright 1999-2014 Horde LLC (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you
* did not receive this file, see http://www.horde.org/licenses/lgpl21.
*
* @category Horde
* @copyright 1999-2014 Horde LLC
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
* @package Core
*/
/**
* The registry provides a set of methods for communication between Horde
* applications and keeping track of application configuration information.
*
* @author Chuck Hagenbuch <chuck@horde.org>
* @author Jon Parise <jon@horde.org>
* @author Anil Madhavapeddy <anil@recoil.org>
* @author Michael Slusarz <slusarz@horde.org>
* @category Horde
* @copyright 1999-2014 Horde LLC
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
* @package Core
*/
class Horde_Registry implements Horde_Shutdown_Task
{
/* Session flags. */
const SESSION_NONE = 1;
const SESSION_READONLY = 2;
/* Error codes for pushApp(). */
const AUTH_FAILURE = 1;
const NOT_ACTIVE = 2;
const PERMISSION_DENIED = 3;
const HOOK_FATAL = 4;
const INITCALLBACK_FATAL = 5;
/* View types. */
const VIEW_BASIC = 1;
const VIEW_DYNAMIC = 2;
const VIEW_MINIMAL = 3;
const VIEW_SMARTMOBILE = 4;
/* Session keys. */
const REGISTRY_CACHE = 'registry_cache';
/**
* Hash storing information on each registry-aware application.
*
* @var array
*/
public $applications = array();
/**
* Original authentication exception. Set if 'fallback' auth is used, and
* authentication fails.
*
* @since 2.11.0
* @todo Fix this up for H6 (framework needs to do better job of
* supporting bootstrapping before authentication).
*
* @var Exception
*/
public $authException;
/**
* A flag that is set once the basic horde application has been
* minimally configured.
*
* @var boolean
*/
public $hordeInit = false;
/**
* The application that called appInit().
*
* @var string
*/
public $initialApp;
/**
* NLS configuration.
*
* @var Horde_Registry_Nlsconfig
*/
public $nlsconfig;
/**
* The current virtual host configuration file.
*
* @since 2.12.0
*
* @var string
*/
public $vhost = null;
/**
* The list of APIs.
*
* @var array
*/
protected $_apiList = array();
/**
* Stack of in-use applications.
*
* @var array
*/
protected $_appStack = array();
/**
* The list of applications initialized during this access.
*
* @var array
*/
protected $_appsInit = array();
/**
* The arguments that have been passed when instantiating the registry.
*
* @var array
*/
protected $_args = array();
/**
* Internal cached data.
*
* @var array
*/
protected $_cache = array(
'auth' => null,
'cfile' => array(),
'conf' => array(),
'existing' => array(),
'ob' => array()
);
/**
* Interfaces list.
*
* @var array
*/
protected $_interfaces = array();
/**
* The last modified time of the newest modified registry file.
*
* @var integer
*/
protected $_regmtime;
/**
* Application bootstrap initialization.
* Solves chicken-and-egg problem - need a way to init Horde environment
* from application without an active Horde_Registry object.
*
* Page compression will be started (if configured).
*
* Global variables defined:
* <pre>
* - $browser: Horde_Browser object
* - $cli: Horde_Cli object (if 'cli' is true)
* - $conf: Configuration array
* - $injector: Horde_Injector object
* - $language: Language
* - $notification: Horde_Notification object
* - $page_output: Horde_PageOutput object
* - $prefs: Horde_Prefs object
* - $registry: Horde_Registry object
* - $session: Horde_Session object
* </pre>
*
* @param string $app The application to initialize.
* @param array $args Optional arguments:
* <pre>
* - admin: (boolean) Require authenticated user to be an admin?
* DEFAULT: false
* - authentication: (string) The type of authentication to use:
* - none: Do not authenticate
* - fallback: Attempt to authenticate; if failure, then don't auth
* (@since 2.11.0).
* - [DEFAULT]: Authenticate; on no auth redirect to login screen
* - cli: (boolean) Initialize a CLI interface. Setting this to true
* implicitly sets 'authentication' to 'none' and 'admin' and
* 'nocompress' to true.
* DEFAULT: false
* - nocompress: (boolean) If set, the page will not be compressed.
* DEFAULT: false
* - nologintasks: (boolean) If set, don't perform logintasks (never
* performed if authentication is 'none').
* DEFAULT: false
* - nonotificationinit: (boolean) If set, don't initialize the
* application handlers for the notification
* system (@since 2.12.0).
* - permission: (array) The permission required by the user to access
* the page. The first element (REQUIRED) is the permission
* name. The second element (OPTION; defaults to SHOW) is
* the permission level.
* - session_cache_limiter: (string) Use this value for the session
* cache limiter.
* DEFAULT: Uses the value in the config.
* - session_control: (string) Special session control limitations:
* - netscape: TODO; start read/write session
* - none: Do not start a session
* - readonly: Start session readonly
* - [DEFAULT] - Start read/write session
* - test: (boolean) Is this the test script? If so, we relax several
* sanity checks and don't load things from the cache.
* DEFAULT: false
* - timezone: (boolean) Set the time zone?
* DEFAULT: false
* - user_admin: (boolean) Set authentication to an admin user?
* DEFAULT: false
* </pre>
*
* @return Horde_Registry_Application The application object.
* @throws Horde_Exception
*/
static public function appInit($app, array $args = array())
{
if (isset($GLOBALS['registry'])) {
return $GLOBALS['registry']->getApiInstance($app, 'application');
}
$args = array_merge(array(
'admin' => false,
'authentication' => null,
'cli' => null,
'nocompress' => false,
'nologintasks' => false,
'nonotificationinit' => false,
'permission' => false,
'session_cache_limiter' => null,
'session_control' => null,
'timezone' => false,
'user_admin' => null,
), $args);
/* CLI initialization. */
if ($args['cli']) {
/* Make sure no one runs from the web. */
if (!Horde_Cli::runningFromCLI()) {
throw new Horde_Exception(Horde_Core_Translation::t("Script must be run from the command line"));
}
/* Load the CLI environment - make sure there's no time limit,
* init some variables, etc. */
$GLOBALS['cli'] = Horde_Cli::init();
$args['nocompress'] = true;
$args['authentication'] = 'none';
}
// For 'fallback' authentication, try authentication first.
if ($args['authentication'] === 'fallback') {
$fallback_auth = true;
$args['authentication'] = null;
} else {
$fallback_auth = false;
}
// Registry.
$s_ctrl = 0;
switch ($args['session_control']) {
case 'netscape':
// Chicken/egg: Browser object doesn't exist yet.
// Can't use Horde_Core_Browser since it depends on registry to be
// configured.
$browser = new Horde_Browser();
if ($browser->isBrowser('mozilla')) {
$args['session_cache_limiter'] = 'private, must-revalidate';
}
break;
case 'none':
$s_ctrl = self::SESSION_NONE;
break;
case 'readonly':
$s_ctrl = self::SESSION_READONLY;
break;
}
$classname = __CLASS__;
$registry = $GLOBALS['registry'] = new $classname($s_ctrl, $args);
$registry->initialApp = $app;
$appob = $registry->getApiInstance($app, 'application');
$appob->initParams = $args;
do {
try {
$registry->pushApp($app, array(
'check_perms' => ($args['authentication'] != 'none'),
'logintasks' => !$args['nologintasks'],
'notransparent' => !empty($args['notransparent'])
));
if ($args['admin'] && !$registry->isAdmin()) {
throw new Horde_Exception(Horde_Core_Translation::t("Not an admin"));
}
$e = null;
} catch (Horde_Exception_PushApp $e) {
if ($fallback_auth) {
$registry->authException = $e;
$registry->setAuthenticationSetting('none');
$args['authentication'] = 'none';
$fallback_auth = false;
continue;
}
}
break;
} while (true);
if (!is_null($e)) {
$appob->appInitFailure($e);
switch ($e->getCode()) {
case self::AUTH_FAILURE:
$failure = new Horde_Exception_AuthenticationFailure($e->getMessage());
$failure->application = $app;
throw $failure;
case self::NOT_ACTIVE:
/* Try redirect to Horde if an app is not active. */
if (!$args['cli'] && $app != 'horde') {
$GLOBALS['notification']->push($e, 'horde.error');
Horde::url($registry->getInitialPage('horde'))->redirect();
}
/* Shouldn't reach here, but fall back to permission denied
* error if we can't even access Horde. */
// Fall-through
case self::PERMISSION_DENIED:
$failure = new Horde_Exception_AuthenticationFailure($e->getMessage(), Horde_Auth::REASON_MESSAGE);
$failure->application = $app;
throw $failure;
}
throw $e;
}
if ($args['timezone']) {
$registry->setTimeZone();
}
if (!$args['nocompress']) {
$GLOBALS['page_output']->startCompression();
}
if ($args['user_admin']) {
if (empty($GLOBALS['conf']['auth']['admins'])) {
throw new Horde_Exception(Horde_Core_Translation::t("Admin authentication requested, but no admin users defined in configuration."));
}
$registry->setAuth(reset($GLOBALS['conf']['auth']['admins']), array());
}
if ($args['permission']) {
$admin_opts = array(
'permission' => $args['permission'][0],
'permlevel' => (isset($args['permission'][1]) ? $args['permission'][1] : Horde_Perms::SHOW)
);
if (!$registry->isAdmin($admin_opts)) {
throw new Horde_Exception_PermissionDenied(Horde_Core_Translation::t("Permission denied."));
}
}
return $appob;
}
/**
* Create a new Horde_Registry instance.
*
* @param integer $session_flags Any session flags.
* @param array $args See appInit().
*
* @throws Horde_Exception
*/
public function __construct($session_flags = 0, array $args = array())
{
/* Set a valid timezone. */
date_default_timezone_set(
ini_get('date.timezone') ?: getenv('TZ') ?: 'UTC'
);
/* Save arguments. */
$this->_args = $args;
/* Define autoloader callbacks. */
$callbacks = array(
'Horde_Mime' => 'Horde_Core_Autoloader_Callback_Mime',
'Horde_Nls' => 'Horde_Core_Autoloader_Callback_Nls',
);
/* Define factories. By default, uses the 'create' method in the given
* classname (string). If other function needed, define as the second
* element in an array. */
$factories = array(
'Horde_ActiveSyncBackend' => 'Horde_Core_Factory_ActiveSyncBackend',
'Horde_ActiveSyncServer' => 'Horde_Core_Factory_ActiveSyncServer',
'Horde_ActiveSyncState' => 'Horde_Core_Factory_ActiveSyncState',
'Horde_Alarm' => 'Horde_Core_Factory_Alarm',
'Horde_Browser' => 'Horde_Core_Factory_Browser',
'Horde_Cache' => 'Horde_Core_Factory_Cache',
'Horde_Controller_Request' => 'Horde_Core_Factory_Request',
'Horde_Controller_RequestConfiguration' => array(
'Horde_Core_Controller_RequestMapper',
'getRequestConfiguration',
),
'Horde_Core_Auth_Signup' => 'Horde_Core_Factory_AuthSignup',
'Horde_Core_CssCache' => 'Horde_Core_Factory_CssCache',
'Horde_Core_JavascriptCache' => 'Horde_Core_Factory_JavascriptCache',
'Horde_Core_Perms' => 'Horde_Core_Factory_PermsCore',
'Horde_Dav_Server' => 'Horde_Core_Factory_DavServer',
'Horde_Dav_Storage' => 'Horde_Core_Factory_DavStorage',
'Horde_Db_Adapter' => 'Horde_Core_Factory_DbBase',
'Horde_Editor' => 'Horde_Core_Factory_Editor',
'Horde_ElasticSearch_Client' => 'Horde_Core_Factory_ElasticSearch',
'Horde_Group' => 'Horde_Core_Factory_Group',
'Horde_HashTable' => 'Horde_Core_Factory_HashTable',
'Horde_History' => 'Horde_Core_Factory_History',
'Horde_Kolab_Server_Composite' => 'Horde_Core_Factory_KolabServer',
'Horde_Kolab_Session' => 'Horde_Core_Factory_KolabSession',
'Horde_Kolab_Storage' => 'Horde_Core_Factory_KolabStorage',
'Horde_Lock' => 'Horde_Core_Factory_Lock',
'Horde_Log_Logger' => 'Horde_Core_Factory_Logger',
'Horde_Mail' => 'Horde_Core_Factory_MailBase',
'Horde_Memcache' => 'Horde_Core_Factory_Memcache',
'Horde_Nosql_Adapter' => 'Horde_Core_Factory_NosqlBase',
'Horde_Notification' => 'Horde_Core_Factory_Notification',
'Horde_Perms' => 'Horde_Core_Factory_Perms',
'Horde_Queue_Storage' => 'Horde_Core_Factory_QueueStorage',
'Horde_Routes_Mapper' => 'Horde_Core_Factory_Mapper',
'Horde_Routes_Matcher' => 'Horde_Core_Factory_Matcher',
'Horde_Secret' => 'Horde_Core_Factory_Secret',
'Horde_Service_Facebook' => 'Horde_Core_Factory_Facebook',
'Horde_Service_Twitter' => 'Horde_Core_Factory_Twitter',
'Horde_Service_UrlShortener' => 'Horde_Core_Factory_UrlShortener',
'Horde_SessionHandler' => 'Horde_Core_Factory_SessionHandler',
'Horde_Template' => 'Horde_Core_Factory_Template',
'Horde_Timezone' => 'Horde_Core_Factory_Timezone',
'Horde_Token' => 'Horde_Core_Factory_Token',
'Horde_Variables' => 'Horde_Core_Factory_Variables',
'Horde_View' => 'Horde_Core_Factory_View',
'Horde_View_Base' => 'Horde_Core_Factory_View',
'Horde_Weather' => 'Horde_Core_Factory_Weather',
'Net_DNS2_Resolver' => 'Horde_Core_Factory_Dns',
'Text_LanguageDetect' => 'Horde_Core_Factory_LanguageDetect',
);
/* Define implementations. */
$implementations = array(
'Horde_Controller_ResponseWriter' => 'Horde_Controller_ResponseWriter_Web'
);
/* Setup injector. */
$GLOBALS['injector'] = $injector = new Horde_Injector(new Horde_Injector_TopLevel());
foreach ($factories as $key => $val) {
if (is_string($val)) {
$val = array($val, 'create');
}
$injector->bindFactory($key, $val[0], $val[1]);
}
foreach ($implementations as $key => $val) {
$injector->bindImplementation($key, $val);
}
$GLOBALS['registry'] = $this;
$injector->setInstance(__CLASS__, $this);
/* Setup autoloader instance and callbacks.
* $__autoloader is defined in horde/lib/core.php */
$injector->setInstance('Horde_Autoloader', $GLOBALS['__autoloader']);
foreach ($callbacks as $key => $val) {
$GLOBALS['__autoloader']->addCallback($key, array($val, 'callback'));
}
/* Import and global Horde's configuration values. */
$this->importConfig('horde');
$conf = $GLOBALS['conf'];
/* Set the umask according to config settings. */
if (isset($conf['umask'])) {
umask($conf['umask']);
}
/* 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, but only if not running from the CLI */
if (!isset($GLOBALS['cli'])) {
set_time_limit($conf['max_exec_time']);
}
/* The basic framework is up and loaded, so set the init flag. */
$this->hordeInit = true;
/* Initial Horde-wide settings. */
/* Initialize browser object. */
$GLOBALS['browser'] = $injector->getInstance('Horde_Browser');
/* Get modified time of registry files. */
$regfiles = array(
HORDE_BASE . '/config/registry.php',
HORDE_BASE . '/config/registry.d'
);
if (file_exists(HORDE_BASE . '/config/registry.local.php')) {
$regfiles[] = HORDE_BASE . '/config/registry.local.php';
}
if (!empty($conf['vhosts'])) {
$vhost = HORDE_BASE . '/config/registry-' . $conf['server']['name'] . '.php';
if (file_exists($vhost)) {
$regfiles[] = $this->vhost = $vhost;
}
}
$this->_regmtime = max(array_map('filemtime', $regfiles));
/* Start a session. */
if ($session_flags & self::SESSION_NONE) {
/* Never start a session if the session flags include
SESSION_NONE. */
$GLOBALS['session'] = $session = new Horde_Session_Null();
$session->setup(true, $args['session_cache_limiter']);
} elseif ((PHP_SAPI === 'cli') ||
(empty($_SERVER['SERVER_NAME']) &&
((PHP_SAPI === 'cgi') || (PHP_SAPI === 'cgi-fcgi')))) {
$GLOBALS['session'] = $session = new Horde_Session();
$session->setup(false, $args['session_cache_limiter']);
} else {
$GLOBALS['session'] = $session = new Horde_Session();
$session->setup(true, $args['session_cache_limiter']);
if ($session_flags & self::SESSION_READONLY) {
/* Close the session immediately so no changes can be made but
values are still available. */
$session->close();
}
}
$injector->setInstance('Horde_Session', $session);
/* Always need to load applications information. */
$this->_loadApplications();
/* Stop system if Horde is inactive. */
if ($this->applications['horde']['status'] == 'inactive') {
throw new Horde_Exception(Horde_Core_Translation::t("This system is currently deactivated."));
}
/* Initialize language configuration object. */
$this->nlsconfig = new Horde_Registry_Nlsconfig();
/* Initialize the localization routines and variables. */
$this->setLanguageEnvironment(null, 'horde');
/* Initialize global page output object. */
$GLOBALS['page_output'] = $injector->getInstance('Horde_PageOutput');
/* Initialize notification object. Always attach status listener by
* default. */
$nclass = null;
switch ($this->getView()) {
case self::VIEW_DYNAMIC:
$nclass = 'Horde_Core_Notification_Listener_DynamicStatus';
break;
case self::VIEW_SMARTMOBILE:
$nclass = 'Horde_Core_Notification_Listener_SmartmobileStatus';
break;
}
$GLOBALS['notification'] = $injector->getInstance('Horde_Notification');
if (empty($args['nonotificationinit'])) {
$injector->getInstance('Horde_Core_Factory_Notification')->addApplicationHandlers();
}
$GLOBALS['notification']->attach('status', null, $nclass);
Horde_Shutdown::add($this);
}
/**
* (Re)set the authentication parameter. Useful for requests, such as Rpc
* requests where we actually don't perform authentication until later in
* the request, but still need Horde bootstrapped early in the request. Also
* clears the local app/api cache since applications will probably already
* have been initialized during Notification polling.
*
* @see appInit()
*
* @param string $authentication The authentication setting.
*/
public function setAuthenticationSetting($authentication)
{
$this->_args['authentication'] = $authentication;
$this->_cache['cfile'] = $this->_cache['ob'] = array();
$this->_cache['isauth'] = array();
$this->_appsInit = array();
while ($this->popApp());
}
/**
* Events to do on shutdown.
*/
public function shutdown()
{
/* Register access key logger for translators. */
if (!empty($GLOBALS['conf']['log_accesskeys'])) {
Horde::getAccessKey(null, null, true);
}
/* Register memory tracker if logging in debug mode. */
Horde::log('Max memory usage: ' . memory_get_peak_usage(true) . ' bytes', 'DEBUG');
}
/**
* A property call to the registry object will return a Caller object.
*/
public function __get($api)
{
if (in_array($api, $this->listAPIs())) {
return new Horde_Registry_Caller($this, $api);
}
}
/**
* Clone should never be called on this object. If it is, die.
*
* @throws Horde_Exception
*/
public function __clone()
{
throw new LogicException('Registry objects should never be cloned.');
}
/**
* serialize() should never be called on this object. If it is, die.
*
* @throws Horde_Exception
*/
public function __sleep()
{
throw new LogicException('Registry objects should never be serialized.');
}
/**
* Rebuild the registry configuration.
*/
public function rebuild()
{
global $session;
$app = $this->getApp();
$this->applications = $this->_apiList = $this->_cache['conf'] = $this->_cache['ob'] = $this->_interfaces = array();
$session->remove('horde', 'nls/');
$session->remove('horde', 'registry/');
$session->remove('horde', self::REGISTRY_CACHE);
$this->_loadApplications();
$this->importConfig('horde');
$this->importConfig($app);
}
/**
* Load application information from registry config files.
*/
protected function _loadApplications()
{
global $cli, $injector;
if (!empty($this->_interfaces)) {
return;
}
/* First, try to load from cache. */
if (!isset($cli) && !$this->isTest()) {
if (Horde_Util::extensionExists('apc')) {
$cstorage = 'Horde_Cache_Storage_Apc';
} elseif (Horde_Util::extensionExists('xcache')) {
$cstorage = 'Horde_Cache_Storage_Xcache';
} else {
$cstorage = 'Horde_Cache_Storage_File';
}
$cache = new Horde_Cache(
new $cstorage(array(
'no_gc' => true,
'prefix' => 'horde_registry_cache_'
)),
array(
'lifetime' => 0,
'logger' => $injector->getInstance('Horde_Log_Logger')
)
);
if (($cid = $this->_cacheId()) &&
($cdata = $cache->get($cid, 0))) {
try {
list($this->applications, $this->_interfaces) =
$injector->getInstance('Horde_Pack')->unpack($cdata);
return;
} catch (Horde_Pack_Exception $e) {}
}
}
$config = new Horde_Registry_Registryconfig($this);
$this->applications = $config->applications;
$this->_interfaces = $config->interfaces;
if (!isset($cache)) {
return;
}
/* Need to determine hash of generated data, since it is possible that
* there is dynamic data in the config files. This only needs to
* be done once per session. */
$packed_data = $injector->getInstance('Horde_Pack')->pack(array(
$this->applications,
$this->_interfaces
));
$cid = $this->_cacheId($packed_data);
if (!$cache->exists($cid, 0)) {
$cache->set($cid, $packed_data);
}
}
/**
* Get the cache ID for the registry information.
*
* @param string $hash If set, hash this value and use as the hash of the
* registry. If false, uses session stored value.
*/
protected function _cacheId($hash = null)
{
global $session;
if (!is_null($hash)) {
$hash = hash((PHP_MINOR_VERSION >= 4) ? 'fnv132' : 'sha1', $hash);
$session->set('horde', self::REGISTRY_CACHE, $hash);
} elseif (!($hash = $session->get('horde', self::REGISTRY_CACHE))) {
return false;
}
/* Generate cache ID. */
return implode('|', array(
gethostname() ?: php_uname(),
__FILE__,
$this->_regmtime,
$hash
));
}
/**
* Load an application's API object.
*
* @param string $app The application to load.
*
* @return Horde_Registry_Api The API object, or null if not available.
*/
protected function _loadApi($app)
{
if (isset($this->_cache['ob'][$app]['api'])) {
return $this->_cache['ob'][$app]['api'];
}
$api = null;
$status = array('active', 'notoolbar', 'hidden');
$status[] = $this->isAdmin()
? 'admin'
: 'noadmin';
if (in_array($this->applications[$app]['status'], $status)) {
try {
$api = $this->getApiInstance($app, 'api');
} catch (Horde_Exception $e) {
Horde::log($e, 'DEBUG');
}
}
$this->_cache['ob'][$app]['api'] = $api;
return $api;
}
/**
* Retrieve an API object.
*
* @param string $app The application to load.
* @param string $type Either 'application' or 'api'.
*
* @return Horde_Registry_Api|Horde_Registry_Application The API object.
* @throws Horde_Exception
*/
public function getApiInstance($app, $type)
{
if (isset($this->_cache['ob'][$app][$type])) {
return $this->_cache['ob'][$app][$type];
}
$path = $this->get('fileroot', $app) . '/lib';
/* Set up autoload paths for the current application. This needs to
* be done here because it is possible to try to load app-specific
* libraries from other applications. */
if (!isset($this->_cache['ob'][$app])) {
$autoloader = $GLOBALS['injector']->getInstance('Horde_Autoloader');
$app_mappers = array(
'Controller' => 'controllers',
'Helper' => 'helpers',
'SettingsExporter' => 'settings'
);
$applicationMapper = new Horde_Autoloader_ClassPathMapper_Application($this->get('fileroot', $app) . '/app');
foreach ($app_mappers as $key => $val) {
$applicationMapper->addMapping($key, $val);
}
$autoloader->addClassPathMapper($applicationMapper);
/* Skip horde, since this was already setup in core.php. */
if ($app != 'horde') {
$autoloader->addClassPathMapper(
new Horde_Autoloader_ClassPathMapper_PrefixString($app, $path)
);
}
}
$cname = Horde_String::ucfirst($type);
/* Can't autoload here, since the application may not have been
* initialized yet. */
$classname = Horde_String::ucfirst($app) . '_' . $cname;
$path = $path . '/' . $cname . '.php';
if (file_exists($path)) {
include_once $path;
} else {
$classname = __CLASS__ . '_' . $cname;
}
if (!class_exists($classname, false)) {
throw new Horde_Exception("$app does not have an API");
}
$this->_cache['ob'][$app][$type] = ($type == 'application')
? new $classname($app)
: new $classname();
return $this->_cache['ob'][$app][$type];
}
/**
* 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 Return hash with app names as keys and config
* parameters as values?
* @param integer $perms The permission level to check for in the list.
* If null, skips permission check.
*
* @return array List of apps registered with Horde. If no
* applications are defined returns an empty array.
*/
public function listApps($filter = null, $assoc = false,
$perms = Horde_Perms::SHOW)
{
if (is_null($filter)) {
$filter = array('notoolbar', 'active');
}
if (!$this->isAdmin() &&
in_array('active', $filter) &&
!in_array('noadmin', $filter)) {
$filter[] = 'noadmin';
}
$apps = array();
foreach ($this->applications as $app => $params) {
if (in_array($params['status'], $filter)) {
/* Topbar apps can only be displayed if the parent app is
* active. */
if (($params['status'] == 'topbar') &&
$this->isInactive($params['app'])) {
continue;
}
if ((is_null($perms) || $this->hasPermission($app, $perms))) {
$apps[$app] = $params;
}
}
}
return $assoc ? $apps : array_keys($apps);
}
/**
* Return a list of all applications, ignoring permissions.
*
* @return array List of all apps registered with Horde.
*/
public function listAllApps()
{
// Default to all installed (but possibly not configured) applications.
return $this->listApps(array(
'active', 'admin', 'noadmin', 'hidden', 'inactive', 'notoolbar'
), false, null);
}
/**
* Is the given application inactive?
*
* @param string $app The application to check.
*
* @return boolean True if inactive.
*/
public function isInactive($app)
{
return (!isset($this->applications[$app]) ||
($this->applications[$app]['status'] == 'inactive') ||
(($this->applications[$app]['status'] == 'admin') &&
!$this->isAdmin()) ||
(($this->applications[$app]['status'] == 'noadmin') &&
$this->currentProcessAuth() &&
$this->isAdmin()));
}
/**
* Returns all available registry APIs.
*
* @return array The API list.
*/
public function listAPIs()
{
if (empty($this->_apiList) && !empty($this->_interfaces)) {
$apis = array();
foreach (array_keys($this->_interfaces) as $interface) {
list($api,) = explode('/', $interface, 2);
$apis[$api] = true;
}
$this->_apiList = array_keys($apis);
}
return $this->_apiList;
}
/**
* 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. If null, returns all methods.
*
* @return array The method list.
*/
public function listMethods($api = null)
{
$methods = array();
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);
}
foreach ($provides as $method) {
if (strpos($method, '/') !== false) {
if (is_null($api) ||
(substr($method, 0, strlen($api)) == $api)) {
$methods[$method] = true;
}
} elseif (($api_ob = $this->_loadApi($app)) &&
(is_null($api) || ($method == $api))) {
foreach ($api_ob->methods() as $service) {
$methods[$method . '/' . $service] = true;
}
}
}
}
}
return array_keys($methods);
}
/**
* 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.