Code

Removed jpgraph | qpl license doesn't match our needs
[gosa.git] / gosa-core / include / class_config.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 /*! \brief Configuration class
24  *  \ingroup coreclasses
25  *
26  * The configuration class, responsible for parsing and querying the
27  * gosa configuration file.
28  */
30 class config  {
32     /* XML parser */
33     var $parser;
34     var $config_found= FALSE;
35     var $tags= array();
36     var $level= 0;
37     var $gpc= 0;
38     var $section= "";
39     var $currentLocation= "";
41     /*! \brief Store configuration for current location */
42     var $current= array(); 
44     /* Link to LDAP-server */
45     var $ldap= NULL;
46     var $referrals= array();
48     /* \brief Configuration data
49      *
50      * - $data['SERVERS'] contains server informations.
51      * */
52     var $data= array( 'TABS' => array(), 'LOCATIONS' => array(), 'SERVERS' => array(),
53             'MAIN' => array(),
54             'MENU' => array(), 'SERVICE' => array());
55     var $basedir= "";
56     var $config_version ="NOT SET";
58     /* Keep a copy of the current deparment list */
59     var $departments= array();
60     var $idepartments= array();
61     var $adepartments= array();
62     var $tdepartments= array();
63     var $department_info= array();
64     var $filename = "";
65     var $last_modified = 0;
67     var $gosaUUID = "";
69     private $jsonRPChandle = NULL; 
71     public $configRegistry = NULL;
73     /*! \brief Class constructor of the config class
74      *  
75      *  \param string 'filename' path to the configuration file
76      *  \param string 'basedir' base directory
77      *
78      * */
79     function config($filename, $basedir= "")
80     {
81         $this->parser = xml_parser_create();
82         $this->basedir= $basedir;
84         $this->gosaUUID = uniqid();
86         xml_set_object($this->parser, $this);
87         xml_set_element_handler($this->parser, "tag_open", "tag_close");
89         /* Parse config file directly? */
90         if ($filename != ""){
91             $this->parse($filename);
92         }
94         // Load configuration registry
95         $this->configRegistry = new configRegistry($this);
96     }
99     function getGOsaUUID()
100     {
101         return($this->gosaUUID);
102     }    
105     /*! \brief Check and reload the configuration
106      * 
107      * This function checks if the configuration has changed, since it was
108      * read the last time and reloads it. It uses the file mtime to check
109      * weither the file changed or not.
110      *
111      * */ 
112     function check_and_reload()
113     {
114         global $ui;
116         /* Check if class_location.inc has changed, this is the case 
117            if we have installed or removed plugins. 
118          */
119         if(session::global_is_set("class_location.inc:timestamp")){
120             $tmp = stat("../include/class_location.inc");
121             if($tmp['mtime'] != session::global_get("class_location.inc:timestamp")){
122                 session::global_un_set("plist");
123             }
124         }
125         $tmp = stat("../include/class_location.inc");
126         session::global_set("class_location.inc:timestamp",$tmp['mtime']);
128         if($this->filename != "" && filemtime($this->filename) != $this->last_modified){
130             $this->config_found= FALSE;
131             $this->tags= array();
132             $this->level= 0;
133             $this->gpc= 0;
134             $this->section= "";
135             $this->currentLocation= "";
137             $this->parser = xml_parser_create();
138             xml_set_object($this->parser, $this);
139             xml_set_element_handler($this->parser, "tag_open", "tag_close");
140             $this->parse($this->filename);
141             $this->set_current($this->current['NAME']);
142         }
143     }  
146     /*! \brief Parse the given configuration file 
147      *
148      *  Parses the configuration file and displays errors if there
149      *  is something wrong with it.
150      *
151      *  \param string 'filename' The filename of the configuration file.
152      * */
154     function parse($filename)
155     {
156         $this->data = array(
157                 "TABS"      => array(), 
158                 "LOCATIONS" => array(), 
159                 "MAIN"      => array(), 
160                 "MENU"      => array(), 
161                 "SERVICE"   => array());
163         $this->last_modified = filemtime($filename);
164         $this->filename = $filename;
165         $fh= fopen($filename, "r"); 
166         $xmldata= fread($fh, 100000);
167         fclose($fh);
168         if(!xml_parse($this->parser, chop($xmldata))){
169             $msg = sprintf(_("XML error in gosa.conf: %s at line %d"),
170                     bold(xml_error_string(xml_get_error_code($this->parser))),
171                     bold(xml_get_current_line_number($this->parser)));
172             msg_dialog::display(_("Configuration error"), $msg, FATAL_ERROR_DIALOG);
173             exit;
174         }
175     }
177     function tag_open($parser, $tag, $attrs)
178     {
179         /* Save last and current tag for reference */
180         $this->tags[$this->level]= $tag;
181         $this->level++;
183         /* Trigger on CONF section */
184         if ($tag == 'CONF'){
185             $this->config_found= TRUE;
186             if(isset($attrs['CONFIGVERSION'])){
187                 $this->config_version = $attrs['CONFIGVERSION'];
188             }
189         }
191         /* Return if we're not in config section */
192         if (!$this->config_found){
193             return;
194         }
196         /* yes/no to true/false and upper case TRUE to true and so on*/
197         foreach($attrs as $name => $value){
198             if(preg_match("/^(true|yes)$/i",$value)){
199                 $attrs[$name] = "true";
200             }elseif(preg_match("/^(false|no)$/i",$value)){
201                 $attrs[$name] = "false";
202             } 
203         }
205         /* Look through attributes */
206         switch ($this->tags[$this->level-1]){
209             /* Handle tab section */
210             case 'TAB': $name= $this->tags[$this->level-2];
212                         /* Create new array? */
213                         if (!isset($this->data['TABS'][$name])){
214                             $this->data['TABS'][$name]= array();
215                         }
217                         /* Add elements */
218                         $this->data['TABS'][$name][]= $attrs;
219                         break;
221                         /* Handle location */
222             case 'LOCATION':
223                         if ($this->tags[$this->level-2] == 'MAIN'){
224                             $name= $attrs['NAME'];
225                             $name = preg_replace("/[<>\"']/","",$name);
226                             $attrs['NAME'] = $name;
227                             $this->currentLocation= $name;
229                             /* Add location elements */
230                             $this->data['LOCATIONS'][$name]= $attrs;
231                         }
232                         break;
234                         /* Handle referral tags */
235             case 'REFERRAL':
236                         if ($this->tags[$this->level-2] == 'LOCATION'){
237                             $url= $attrs['URI'];
238                             $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
240                             /* Add location elements */
241                             if (!isset($this->data['LOCATIONS'][$this->currentLocation]['REFERRAL'])){
242                                 $this->data['LOCATIONS'][$this->currentLocation]['REFERRAL']= array();
243                             }
245                             $this->data['LOCATIONS'][$this->currentLocation]['REFERRAL'][$server]= $attrs;
246                         }
247                         break;
249                         /* Load main parameters */
250             case 'MAIN':
251                         $this->data['MAIN']= array_merge ($this->data['MAIN'], $attrs);
252                         break;
254                         /* Load menu */
255             case 'SECTION':
256                         if ($this->tags[$this->level-2] == 'MENU'){
257                             $this->section= $attrs['NAME'];
258                             $this->data['MENU'][$this->section]= array(); ;
259                         }
260                         break;
262             case 'PATHMENU':
263                         $this->data['PATHMENU']= array(); ;
264                         break;
266             case 'SHORTCUTMENU':
267                         $this->data['SHORTCUTMENU']= array(); ;
268                         break;
270                         /* Inser plugins */
271             case 'PLUGIN':
272                         if ($this->tags[$this->level-3] == 'MENU' &&
273                                 $this->tags[$this->level-2] == 'SECTION'){
275                             $this->data['MENU'][$this->section][$this->gpc++]= $attrs;
276                         }
277                         if ($this->tags[$this->level-2] == 'PATHMENU'){
278                             $this->data['PATHMENU'][$this->gpc++]= $attrs;
279                         }
280                         if ($this->tags[$this->level-2] == 'SHORTCUTMENU'){
281                             $this->data['SHORTCUTMENU'][$this->gpc++]= $attrs;
282                         }
283                         if ($this->tags[$this->level-2] == 'SERVICEMENU'){
284                             $this->data['SERVICE'][$attrs['CLASS']]= $attrs;
285                         }
286                         break;
287         }
288     }
290     function tag_close($parser, $tag)
291     {
292         /* Close config section */
293         if ($tag == 'CONF'){
294             $this->config_found= FALSE;
295         }
296         $this->level--;
297     }
300     function get_credentials($creds)
301     {
302         if (isset($_SERVER['HTTP_GOSA_KEY'])){
303             if (!session::global_is_set('HTTP_GOSA_KEY_CACHE')){
304                 session::global_set('HTTP_GOSA_KEY_CACHE',array());
305             }
306             $cache = session::global_get('HTTP_GOSA_KEY_CACHE');
307             if(!isset($cache[$creds])){
308                 $cache[$creds] = cred_decrypt($creds, $_SERVER['HTTP_GOSA_KEY']);
309                 session::global_set('HTTP_GOSA_KEY_CACHE',$cache);
310             }
311             return ($cache[$creds]);
312         }
313         return ($creds);
314     }
317     function getRpcHandle($connectUrl="", $username="", $userPassword="", $authModeDigest=FALSE)
318     {
319         // Get conenct information, if no info was given use the default values from gosa.conf
320         $connectUrl   = (!empty($connectUrl))   ? $connectUrl   : $this->get_cfg_value('core','gosaRpcServer');
321         $username     = (!empty($username))     ? $username     : $this->get_cfg_value('core','gosaRpcUser');
322         $userPassword = (!empty($userPassword)) ? $userPassword : $this->get_cfg_value('core','gosaRpcPassword');
323         $authModeDigest = $authModeDigest;
325         // Create jsonRPC handle on demand.
326         if(!isset($this->jsonRPChandle[$connectUrl][$username]) || !$this->jsonRPChandle[$connectUrl][$username]){
327             $this->jsonRPChandle[$connectUrl][$username] = new jsonRPC($this, $connectUrl, $username, $userPassword, $authModeDigest);
328         }
329         return($this->jsonRPChandle[$connectUrl][$username]);
330     }
333     /*! \brief Get a LDAP link object
334      *
335      * This function can be used to get an ldap object, which in turn can
336      * be used to query the LDAP. See the LDAP class for more information
337      * on how to use it.
338      *
339      * Example usage:
340      * \code
341      * $ldap = $this->config->get_ldap_link();
342      * \endcode
343      *
344      * \param boolean sizelimit Weither to impose a sizelimit on the LDAP object or not.
345      * Defaults to false. If set to true, the size limit in the configuration
346      * file will be used to set the option LDAP_OPT_SIZELIMIT.
347      * \return ldapMultiplexer object
348      */
349     function get_ldap_link($sizelimit= FALSE)
350     {
351         if($this->ldap === NULL || !is_resource($this->ldap->cid)){
353             /* Build new connection */
354             $this->ldap= ldap_init ($this->current['SERVER'], $this->current['BASE'],
355                     $this->current['ADMINDN'], $this->get_credentials($this->current['ADMINPASSWORD']));
357             /* Check for connection */
358             if (is_null($this->ldap) || (is_int($this->ldap) && $this->ldap == 0)){
359                 $smarty= get_smarty();
360                 msg_dialog::display(_("LDAP error"), _("Cannot bind to LDAP!"), FATAL_ERROR_DIALOG);
361                 exit();
362             }
364             /* Move referrals */
365             if (!isset($this->current['REFERRAL'])){
366                 $this->ldap->referrals= array();
367             } else {
368                 $this->ldap->referrals= $this->current['REFERRAL'];
369             }
371             if (!session::global_is_set('size_limit')){
372                 session::global_set('size_limit', $this->get_cfg_value('core', 'ldapSizelimit'));
373                 session::global_set('size_ignore', $this->boolValueIsTrue('core', 'ldapSizeIgnore'));
374             }
375         }
377         $obj  = new ldapMultiplexer($this->ldap);
378         if ($sizelimit){
379             $obj->set_size_limit(session::global_get('size_limit'));
380         } else {
381             $obj->set_size_limit(0);
382         }
383         return($obj);
384     }
386     /*! \brief Set the current location
387      *  
388      *  \param string name the name of the location
389      */
390     function set_current($name)
391     {
392         $this->current= $this->data['LOCATIONS'][$name];
394         if (isset($this->current['INITIAL_BASE'])){
395             session::global_set('CurrentMainBase',$this->current['INITIAL_BASE']);
396         }
398         /* Sort referrals, if present */
399         if (isset ($this->current['REFERRAL'])){
400             $bases= array();
401             $servers= array();
402             foreach ($this->current['REFERRAL'] as $ref){
403                 $server= preg_replace('%^(.*://[^/]+)/.*$%', '\\1', $ref['URI']);
404                 $base= preg_replace('%^.*://[^/]+/(.*)$%', '\\1', $ref['URI']);
405                 $bases[$base]= strlen($base);
406                 $servers[$base]= $server;
407             }
408             asort($bases);
409             reset($bases);
410         }
412         /* SERVER not defined? Load the one with the shortest base */
413         if (!isset($this->current['SERVER'])){
414             $this->current['SERVER']= $servers[key($bases)];
415         }
417         /* BASE not defined? Load the one with the shortest base */
418         if (!isset($this->current['BASE'])){
419             $this->current['BASE']= key($bases);
420         }
422         /* Convert BASE to have escaped special characters */
423         $this->current['BASE']= @LDAP::convert($this->current['BASE']);
425         /* Parse LDAP referral informations */
426         if (!isset($this->current['ADMINDN']) || !isset($this->current['ADMINPASSWORD'])){
427             $url= $this->current['SERVER'];
428             $referral= $this->current['REFERRAL'][$url];
429             $this->current['ADMINDN']= $referral['ADMINDN'];
430             $this->current['ADMINPASSWORD']= $referral['ADMINPASSWORD'];
431         }
433         /* Load server informations */
434         $this->load_servers();
435     }
438     /*! \brief Load server information from config/LDAP
439      *
440      *  This function searches the LDAP for servers (e.g. goImapServer, goMailServer etc.)
441      *  and stores information about them $this->data['SERVERS']. In the case of mailservers
442      *  the main section of the configuration file is searched, too.
443      */
444     function load_servers ()
445     {
446         /* Only perform actions if current is set */
447         if ($this->current === NULL){
448             return;
449         }
451         /* Fill imap servers */
452         $ldap= $this->get_ldap_link();
453         $ldap->cd ($this->current['BASE']);
455         /* Search mailMethod konfiguration in main section too 
456          */
457         $tmp = $this->get_cfg_value("core","mailMethod");
458         if ($tmp){
459             $ldap->search ("(objectClass=goMailServer)", array('cn'));
460             $this->data['SERVERS']['IMAP']= array();
461             while ($attrs= $ldap->fetch()){
462                 $name= $attrs['cn'][0];
463                 $this->data['SERVERS']['IMAP'][$name]= 
464                     array( 
465                             "server_dn"   => $attrs['dn'],
466                             "connect"     => "",
467                             "admin"       => "",
468                             "password"    => "",
469                             "sieve_server"=> "",
470                             "sieve_option"=> "",
471                             "sieve_port"  => "");
472             }
473         } else {
474             $ldap->search ("(&(objectClass=goImapServer)(goImapSieveServer=*))", 
475                     array('goImapName', 'goImapConnect', 'goImapAdmin', 'goImapPassword',
476                         'goImapSieveServer', 'goImapSievePort'));
478             $this->data['SERVERS']['IMAP']= array();
480             while ($attrs= $ldap->fetch()){
482                 /* Check if the given goImapSieveServer is in the new style "{cn:port/option}"
483                    or the old style just "cn".
484                  */
485                 if(preg_match("/\{/",$attrs['goImapSieveServer'][0])){
486                     $sieve_server = preg_replace("/^\{([^:]*).*$/","\\1",$attrs['goImapSieveServer'][0]);
487                     $sieve_option = preg_replace("/^[^:]*[^\/]*+\/(.*)\}$/","\\1",$attrs['goImapSieveServer'][0]);
488                 }else{
489                     $sieve_server = $attrs['goImapSieveServer'][0];
490                     $sieve_option = "";
491                 }
493                 $pwd            = $attrs['goImapPassword'][0];
494                 $imap_admin     = $attrs['goImapAdmin'][0];
495                 $imap_connect   = $attrs['goImapConnect'][0];
496                 $imap_server    = $attrs['goImapName'][0];
497                 $sieve_port     = $attrs['goImapSievePort'][0];
499                 $this->data['SERVERS']['IMAP'][$imap_server]= 
500                     array( 
501                             "server_dn"   => $attrs['dn'],
502                             "connect"     => $imap_connect,
503                             "admin"       => $imap_admin,
504                             "password"    => $pwd,
505                             "sieve_server"=> $sieve_server,
506                             "sieve_option"=> $sieve_option,
507                             "sieve_port"  => $sieve_port);
508             }
509         }
511         /* Get kerberos server. FIXME: only one is supported currently */
512         $ldap->cd ($this->current['BASE']);
513         $ldap->search ("(&(goKrbRealm=*)(goKrbAdmin=*)(objectClass=goKrbServer))");
514         if ($ldap->count()){
515             $attrs= $ldap->fetch();
516             $this->data['SERVERS']['KERBEROS']= array( 'SERVER' => $attrs['cn'][0],
517                     'REALM' => $attrs['goKrbRealm'][0],
518                     'ADMIN' => $attrs['goKrbAdmin'][0]);
519         }
521         /* Get cups server. FIXME: only one is supported currently */
522         $ldap->cd ($this->current['BASE']);
523         $ldap->search ("(objectClass=goCupsServer)");
524         if ($ldap->count()){
525             $attrs= $ldap->fetch();
526             $this->data['SERVERS']['CUPS']= $attrs['cn'][0];    
527         }
529         /* Get fax server. FIXME: only one is supported currently */
530         $ldap->cd ($this->current['BASE']);
531         $ldap->search ("(objectClass=goFaxServer)");
532         if ($ldap->count()){
533             $attrs= $ldap->fetch();
534             $this->data['SERVERS']['FAX']= array( 'SERVER' => $attrs['cn'][0],
535                     'LOGIN' => $attrs['goFaxAdmin'][0],
536                     'PASSWORD' => $attrs['goFaxPassword'][0]);
537         }
540         /* Get asterisk servers */
541         $ldap->cd ($this->current['BASE']);
542         $ldap->search ("(objectClass=goFonServer)");
543         $this->data['SERVERS']['FON']= array();
544         if ($ldap->count()){
545             while ($attrs= $ldap->fetch()){
547                 /* Add 0 entry for development */
548                 if(count($this->data['SERVERS']['FON']) == 0){
549                     $this->data['SERVERS']['FON'][0]= array(
550                             'DN'      => $attrs['dn'],
551                             'SERVER'  => $attrs['cn'][0],
552                             'LOGIN'   => $attrs['goFonAdmin'][0],
553                             'PASSWORD'  => $attrs['goFonPassword'][0],
554                             'DB'    => "gophone",
555                             'SIP_TABLE'   => "sip_users",
556                             'EXT_TABLE'   => "extensions",
557                             'VOICE_TABLE' => "voicemail_users",
558                             'QUEUE_TABLE' => "queues",
559                             'QUEUE_MEMBER_TABLE'  => "queue_members");
560                 }
562                 /* Add entry with 'dn' as index */
563                 $this->data['SERVERS']['FON'][$attrs['dn']]= array(
564                         'DN'      => $attrs['dn'],
565                         'SERVER'  => $attrs['cn'][0],
566                         'LOGIN'   => $attrs['goFonAdmin'][0],
567                         'PASSWORD'  => $attrs['goFonPassword'][0],
568                         'DB'    => "gophone",
569                         'SIP_TABLE'   => "sip_users",
570                         'EXT_TABLE'   => "extensions",
571                         'VOICE_TABLE' => "voicemail_users",
572                         'QUEUE_TABLE' => "queues",
573                         'QUEUE_MEMBER_TABLE'  => "queue_members");
574             }
575         }
578         /* Get glpi server */
579         $ldap->cd ($this->current['BASE']);
580         $ldap->search ("(&(objectClass=goGlpiServer)(cn=*)(goGlpiAdmin=*)(goGlpiDatabase=*))",array("cn","goGlpiPassword","goGlpiAdmin","goGlpiDatabase"));
581         if ($ldap->count()){
582             $attrs= $ldap->fetch();
583             if(!isset($attrs['goGlpiPassword'])){
584                 $attrs['goGlpiPassword'][0] ="";
585             }
586             $this->data['SERVERS']['GLPI']= array( 
587                     'SERVER'    => $attrs['cn'][0],
588                     'LOGIN'     => $attrs['goGlpiAdmin'][0],
589                     'PASSWORD'  => $attrs['goGlpiPassword'][0],
590                     'DB'                => $attrs['goGlpiDatabase'][0]);
591         }
594         /* Get logdb server */
595         $ldap->cd ($this->current['BASE']);
596         $ldap->search ("(objectClass=goLogDBServer)");
597         if ($ldap->count()){
598             $attrs= $ldap->fetch();
599             if(!isset($attrs['gosaLogDB'][0])){
600                 $attrs['gosaLogDB'][0] = "gomon";
601             }
602             $this->data['SERVERS']['LOG']= array( 'SERVER' => $attrs['cn'][0],
603                     'LOGIN' => $attrs['goLogAdmin'][0],
604                     'DB' => $attrs['gosaLogDB'][0],
605                     'PASSWORD' => $attrs['goLogPassword'][0]);
606         }
609         /* GOsa logging databases */
610         $ldap->cd ($this->current['BASE']);
611         $ldap->search ("(objectClass=gosaLogServer)");
612         if ($ldap->count()){
613             while($attrs= $ldap->fetch()){
614                 $this->data['SERVERS']['LOGGING'][$attrs['cn'][0]]= 
615                     array(
616                             'DN'    => $attrs['dn'],
617                             'USER'  => $attrs['goLogDBUser'][0],
618                             'DB'    => $attrs['goLogDB'][0],
619                             'PWD'   => $attrs['goLogDBPassword'][0]);
620             }
621         }
624         /* Get NFS server lists */
625         $tmp= array("default");
626         $tmp2= array("default");
627         $ldap->cd ($this->current['BASE']);
628         $ldap->search ("(&(objectClass=goShareServer)(goExportEntry=*))");
629         while ($attrs= $ldap->fetch()){
630             for ($i= 0; $i<$attrs["goExportEntry"]["count"]; $i++){
631                 if(preg_match('/^[^|]+\|[^|]+\|NFS\|.*$/', $attrs["goExportEntry"][$i])){
632                     $path= preg_replace ("/^[^|]+\|[^|]+\|[^|]+\|[^|]+\|([^|]+).*$/", '\1', $attrs["goExportEntry"][$i]);
633                     $tmp[]= $attrs["cn"][0].":$path";
634                 }
635                 if(preg_match('/^[^|]+\|[^|]+\|NBD\|.*$/', $attrs["goExportEntry"][$i])){
636                     $path= preg_replace ("/^[^|]+\|[^|]+\|[^|]+\|[^|]+\|([^|]+).*$/", '\1', $attrs["goExportEntry"][$i]);
637                     $tmp2[]= $attrs["cn"][0].":$path";
638                 }
639             }
640         }
641         $this->data['SERVERS']['NFS']= $tmp;
642         $this->data['SERVERS']['NBD']= $tmp2;
644         /* Load Terminalservers */
645         $ldap->cd ($this->current['BASE']);
646         $ldap->search ("(objectClass=goTerminalServer)",array("cn","gotoSessionType"));
647         $this->data['SERVERS']['TERMINAL']= array();
648         $this->data['SERVERS']['TERMINAL'][]= "default";
649         $this->data['SERVERS']['TERMINAL_SESSION_TYPES'] = array();
652         while ($attrs= $ldap->fetch()){
653             $this->data['SERVERS']['TERMINAL'][]= $attrs["cn"][0];
654             if(isset( $attrs["gotoSessionType"]['count'])){
655                 for($i =0 ; $i < $attrs["gotoSessionType"]['count'] ; $i++){
656                     $this->data['SERVERS']['TERMINAL_SESSION_TYPES'][$attrs["cn"][0]][] = $attrs["gotoSessionType"][$i]; 
657                 }
658             }
659         }
661         /* Ldap Server 
662          */
663         $this->data['SERVERS']['LDAP']= array();
664         $ldap->cd ($this->current['BASE']);
665         $ldap->search ("(&(objectClass=goLdapServer)(goLdapBase=*))");
666         while ($attrs= $ldap->fetch()){
667             $this->data['SERVERS']['LDAP'][$attrs['dn']] = $attrs;
668         }
670         /* Get misc server lists */
671         $this->data['SERVERS']['SYSLOG']= array("default");
672         $this->data['SERVERS']['NTP']= array("default");
673         $ldap->cd ($this->current['BASE']);
674         $ldap->search ("(objectClass=goNtpServer)");
675         while ($attrs= $ldap->fetch()){
676             $this->data['SERVERS']['NTP'][]= $attrs["cn"][0];
677         }
678         $ldap->cd ($this->current['BASE']);
679         $ldap->search ("(objectClass=goSyslogServer)");
680         while ($attrs= $ldap->fetch()){
681             $this->data['SERVERS']['SYSLOG'][]= $attrs["cn"][0];
682         }
684         /* Get samba servers from LDAP, in case of samba3 */
685         $this->data['SERVERS']['SAMBA']= array();
686         $ldap->cd ($this->current['BASE']);
687         $ldap->search ("(objectClass=sambaDomain)");
688         while ($attrs= $ldap->fetch()){
689             $this->data['SERVERS']['SAMBA'][$attrs['sambaDomainName'][0]]= array( "SID" =>"","RIDBASE" =>"");
690             if(isset($attrs["sambaSID"][0])){
691                 $this->data['SERVERS']['SAMBA'][$attrs['sambaDomainName'][0]]["SID"]  = $attrs["sambaSID"][0];
692             }
693             if(isset($attrs["sambaAlgorithmicRidBase"][0])){
694                 $this->data['SERVERS']['SAMBA'][$attrs['sambaDomainName'][0]]["RIDBASE"] = $attrs["sambaAlgorithmicRidBase"][0];
695             }
696         }
698         /* If no samba servers are found, look for configured sid/ridbase */
699         if (count($this->data['SERVERS']['SAMBA']) == 0){
700             if (!isset($this->current["SAMBASID"]) || !isset($this->current["SAMBARIDBASE"])){
701                 msg_dialog::display(_("Configuration error"), _("sambaSID and/or sambaRidBase missing in the configuration!"), ERROR_DIALOG);
702             } else {
703                 $this->data['SERVERS']['SAMBA']['DEFAULT']= array(
704                         "SID" => $this->current["SAMBASID"],
705                         "RIDBASE" => $this->current["SAMBARIDBASE"]);
706             }
707         }
709     }
712     function get_departments($ignore_dn= "")
713     {
714         global $config;
716         /* Initialize result hash */
717         $result= array();
718         $administrative= array();
719         $result['/']= $this->current['BASE'];
720         $this->tdepartments= array();
722         /* Get all department types from department Management, to be able detect the department type.
723            -It is possible that differnty department types have the same name, 
724            in this case we have to mark the department name to be able to differentiate.
725            (e.g l=Name  or   o=Name)
726          */    
727         $types = departmentManagement::get_support_departments();
729         /* Create a list of attributes to fetch */
730         $ldap_values = array("objectClass","gosaUnitTag", "description");
731         $filter = "";
732         foreach($types as $type){
733             $ldap_values[] = $type['ATTR'];
734             $filter .= "(objectClass=".$type['OC'].")";
735         }
736         $filter = "(&(objectClass=gosaDepartment)(|".$filter."))";
738         /* Get list of department objects */
739         $ldap= $this->get_ldap_link();
740         $ldap->cd ($this->current['BASE']);
741         $ldap->search ($filter, $ldap_values);
742         while ($attrs= $ldap->fetch()){
744             /* Detect department type */
745             $type_data = array();
746             foreach($types as $t => $data){
747                 if(in_array($data['OC'],$attrs['objectClass'])){
748                     $type_data = $data;
749                     break;
750                 }
751             }
753             /* Unknown department type -> skip */
754             if(!count($type_data)) continue;
756             $dn= $ldap->getDN();
757             $this->tdepartments[$dn]= "";
758             $this->department_info[$dn]= array("img" => $type_data['IMG'],
759                     "description" => isset($attrs['description'][0])?$attrs['description'][0]:"",
760                     "name" => $attrs[$type_data['ATTR']][0]);
762             /* Save administrative departments */
763             if (in_array_ics("gosaAdministrativeUnit", $attrs['objectClass']) &&
764                     isset($attrs['gosaUnitTag'][0])){
765                 $administrative[$dn]= $attrs['gosaUnitTag'][0];
766                 $this->tdepartments[$dn]= $attrs['gosaUnitTag'][0];
767             }
769             if (in_array_ics("gosaAdministrativeUnitTag", $attrs['objectClass']) &&
770                     isset($attrs['gosaUnitTag'][0])){
771                 $this->tdepartments[$dn]= $attrs['gosaUnitTag'][0];
772             }
774             if ($dn == $ignore_dn){
775                 continue;
776             }
777             $c_dn = convert_department_dn($dn)." (".$type_data['ATTR'].")";
779             /* Only assign non-root departments */
780             if ($dn != $result['/']){
781                 $result[$c_dn]= $dn;
782             }
783         }
785         $this->adepartments= $administrative;
786         $this->departments= $result;
787     }
790     function make_idepartments($max_size= 28)
791     {
792         global $config;
793         $base = $config->current['BASE'];
794         $qbase = preg_quote($base, '/');
795         $utags= isset($config->current['HONOURUNITTAGS']) && preg_match('/true/i', $config->current['HONOURUNITTAGS']);
797         $arr = array();
798         $ui= get_userinfo();
800         $this->idepartments= array();
802         /* Create multidimensional array, with all departments. */
803         foreach ($this->departments as $key => $val){
805             /* When using strict_units, filter non relevant parts */
806             if ($utags){
807                 if ($ui->gosaUnitTag != '' && isset($this->tdepartments[$val]) &&
808                         $this->tdepartments[$val] != $ui->gosaUnitTag){
810 #TODO: link with strict*
811 #continue;
812                 }
813             }
815             /* Split dn into single department pieces */
816             $elements = array_reverse(explode(',',preg_replace("/$qbase$/",'',$val)));          
818             /* Add last ou element of current dn to our array */
819             $last = &$arr;
820             foreach($elements as $key => $ele){
822                 /* skip empty */
823                 if(empty($ele)) continue;
825                 /* Extract department name */           
826                 $elestr = trim(preg_replace('/^[^=]*+=/','', $ele),',');
827                 $nameA  = trim(preg_replace('/=.*$/','', $ele),',');
828                 if($nameA != 'ou'){
829                     $nameA = " ($nameA)";
830                 }else{
831                     $nameA = '';
832                 }
834                 /* Add to array */      
835                 if($key == (count($elements)-1)){
836                     $last[$elestr.$nameA]['ENTRY'] = $val;
837                 }
839                 /* Set next array appending position */
840                 $last = &$last[$elestr.$nameA]['SUB'];
841             }
842         }
845         /* Add base entry */
846         $ret['/']['ENTRY']      = $base;
847         $ret['/']['SUB']        = $arr;
848         $this->idepartments= $this->generateDepartmentArray($ret,-1,$max_size);
849     }
852     /* Creates display friendly output from make_idepartments */
853     function generateDepartmentArray($arr,$depth = -1,$max_size = 256)
854     {
855         $ret = array();
856         $depth ++;
858         /* Walk through array */        
859         ksort($arr);
860         foreach($arr as $name => $entries){
862             /* If this department is the last in the current tree position 
863              * remove it, to avoid generating output for it */
864             if(count($entries['SUB'])==0){
865                 unset($entries['SUB']);
866             }
868             /* Fix name, if it contains a replace tag */
869             $name= preg_replace('/\\\\,/', ',', LDAP::fix($name));
871             /* Check if current name is too long, then cut it */
872             if(mb_strlen($name, 'UTF-8')> $max_size){
873                 $name = mb_substr($name,0,($max_size-3), 'UTF-8')." ...";
874             }
876             /* Append the name to the list */   
877             if(isset($entries['ENTRY'])){
878                 $a = "";
879                 for($i = 0 ; $i < $depth ; $i ++){
880                     $a.=".";
881                 }
882                 $ret[$entries['ENTRY']]=$a."&nbsp;".$name;
883             }   
885             /* recursive add of subdepartments */
886             if(isset($entries['SUB'])){
887                 $ret = array_merge($ret,$this->generateDepartmentArray($entries['SUB'],$depth,$max_size));
888             }
889         }
891         return($ret);
892     }
894     /*! \brief Get all available shares defined in the current LDAP
895      *
896      *  This function returns all available Shares defined in this ldap
897      *  
898      *  \param boolean listboxEntry If set to TRUE, only name and path are
899      *  attached to the array. If FALSE, the whole entry will be parsed an atached to the result.
900      *  \return array
901      */
902     function getShareList($listboxEntry = false)
903     {
904         $tmp = get_sub_list("(&(objectClass=goShareServer)(goExportEntry=*))","server",get_ou("servgeneric", "serverRDN"),
905                 $this->current['BASE'],array("goExportEntry","cn"), GL_NONE);
906         $return =array();
907         foreach($tmp as $entry){
909             if(isset($entry['goExportEntry']['count'])){
910                 unset($entry['goExportEntry']['count']);
911             }
912             if(isset($entry['goExportEntry'])){
913                 foreach($entry['goExportEntry'] as $export){
914                     $shareAttrs = explode("|",$export);
915                     if($listboxEntry) {
916                         $return[$shareAttrs[0]."|".$entry['cn'][0]] = $shareAttrs[0]." - ".$entry['cn'][0];
917                     }else{
918                         $return[$shareAttrs[0]."|".$entry['cn'][0]]['server']       = $entry['cn'][0];
919                         $return[$shareAttrs[0]."|".$entry['cn'][0]]['name']         = $shareAttrs[0];
920                         $return[$shareAttrs[0]."|".$entry['cn'][0]]['description']  = $shareAttrs[1];
921                         $return[$shareAttrs[0]."|".$entry['cn'][0]]['type']         = $shareAttrs[2];
922                         $return[$shareAttrs[0]."|".$entry['cn'][0]]['charset']      = $shareAttrs[3];
923                         $return[$shareAttrs[0]."|".$entry['cn'][0]]['path']         = $shareAttrs[4];
924                         $return[$shareAttrs[0]."|".$entry['cn'][0]]['option']       = $shareAttrs[5];
925                     }
926                 }
927             }
928         }
929         return($return);
930     }
933     /*! \brief Return al available share servers
934      *
935      * This function returns all available ShareServers.
936      *
937      * \return array
938      * */
939     function getShareServerList()
940     {
941         global $config;
942         $return = array();
943         $ui = get_userinfo();
944         $base = $config->current['BASE'];
945         $res= get_sub_list("(&(objectClass=goShareServer)(goExportEntry=*))", "server",
946                 get_ou("servgeneric", "serverRDN"), $base,array("goExportEntry","cn"),GL_NONE | GL_NO_ACL_CHECK);
948         foreach($res as $entry){
950             $acl = $ui->get_permissions($entry['dn'],"server","");
951             if(isset($entry['goExportEntry']['count'])){
952                 unset($entry['goExportEntry']['count']);
953             }
954             foreach($entry['goExportEntry'] as $share){
955                 $a_share = explode("|",$share);
956                 $sharename = $a_share[0];
957                 $data= array();
958                 $data['NAME']   = $sharename;
959                 $data['ACL']    = $acl;
960                 $data['SERVER'] = $entry['cn']['0'];
961                 $data['SHARE']  = $sharename;
962                 $data['DISPLAY']= $entry['cn'][0]." [".$sharename."]";
963                 $return[$entry['cn'][0]."|".$sharename] = $data;
964             }
965         }
966         return($return);
967     }
970     /*! \brief Checks if there's a bool property set in the configuration.
971      *
972      *  The function checks, weither the specified bool value is set to a true
973      *  value in the configuration file. 
974      *
975      *  Example usage:
976      *  \code
977      *  if ($this->config->boolValueIsTrue("core", "copyPaste")) {
978      *    echo "Copy Paste Handling is enabled";
979      *  }
980      *  \endcode
981      *
982      *  \param string 'class' The properties class. e.g. 'core','user','sudo',...
983      *  \param string 'value' Key in the given section, which is subject to check
984      *
985      *
986      * */
987     function boolValueIsTrue($class, $name)
988     {
989         return(preg_match("/true/i", $this->get_cfg_value($class,$name)));
990     }
993     function __search(&$arr, $name, $return)
994     {
995         $return= strtoupper($return);
996         if (is_array($arr)){
997             foreach ($arr as &$a){
998                 if (isset($a['CLASS']) && strcasecmp($name, $a['CLASS']) == 0){
999                     return(isset($a[$return])?$a[$return]:"");
1000                 } else {
1001                     $res= $this->__search ($a, $name, $return);
1002                     if ($res != ""){
1003                         return $res;
1004                     }
1005                 }
1006             }
1007         }
1008         return ("");
1009     }
1012     /*! Outdated - try to use pluginEnabled, boolValueIsTrue or get_cfg_value instead. 
1013      *
1014      *  (Search for a configuration setting in different categories
1015      *
1016      *  Searches for the value of a given key in the configuration data.
1017      *  Optionally the list of categories to search (tabs, main, locations) can
1018      *  be specified. The first value that matches is returned.
1019      *
1020      *  Example usage:
1021      *  \code
1022      *  $postcmd = $this->config->search(get_class($this), "POSTCOMMAND", array("menu", "tabs"));
1023      *  \endcode
1024      *  ) 
1025      *
1026      * */
1027     function search($class, $value, $categories= "")
1028     {
1029         if (is_array($categories)){
1030             foreach ($categories as $category){
1031                 $res= $this->__search($this->data[strtoupper($category)], $class, $value);
1032                 if ($res != ""){
1033                     return $res;
1034                 }
1035             }
1036         } else {
1037             if ($categories == "") {
1038                 return $this->__search($this->data, $class, $value);
1039             } else {
1040                 return $this->__search($this->data[strtoupper($categories)], $class, $value);
1041             }
1042         } 
1044         return ("");
1045     }
1048     /*! \brief          Check whether a plugin is activated or not 
1049      */ 
1050     function pluginEnabled($class){
1051         $tmp = $this->search($class, "CLASS",array('menu','tabs'));
1052         return(!empty($tmp));
1053     }
1056     /*! \brief Get a configuration value from the config
1057      *
1058      *  This returns a configuration value from the config. It either
1059      *  uses the data of the current location ($this->current),
1060      *  if it contains the value (e.g. current['BASE']) or otherwise
1061      *  uses the data from the main configuration section.
1062      *
1063      *  If no value is found and an optional default has been specified,
1064      *  then the default is returned.
1065      *
1066      *  \param string 'name' the configuration key (case-insensitive)
1067      *  \param string 'default' a default that is returned, if no value is found
1068      *
1069      *
1070      */
1071     function get_cfg_value($class,$name, $default= NULL) 
1072     {
1073         // The default parameter is deprecated 
1074         if($default != NULL){
1075 #        trigger_error("Third parameter 'default' is deprecated for function 'get_cfg_value'!");
1076         }
1078         // Return the matching property value if it exists.
1079         if($this->configRegistry->propertyExists($class,$name)){
1080             return($this->configRegistry->getPropertyValue($class,$name));
1081         }
1083         // Show a warning in the syslog if there is an undefined property requested.
1084         if($this->configRegistry->propertyInitializationComplete() && 
1085                 "{$class}::{$name}" != 'core::config' &&  // <--- This on is never set, only in gosa.conf. 
1086                 "{$class}::{$name}" != 'core::logging'){  // <--- This one may cause endless recursions in class_log.inc
1087             new log("debug","","Unconfigured property: '{$class}::{$name}'",array(),'');
1088         }
1090         // Try to find the property in the config file directly.
1091         $name= strtoupper($name);
1092         if (isset($this->current[$name])) return ($this->current[$name]);
1093         if (isset($this->data["MAIN"][$name])) return ($this->data["MAIN"][$name]);
1094         return ("");
1095     }
1098     /*! \brief Check if current configuration version matches the GOsa version
1099      *
1100      *  This function checks if the configuration file version matches the
1101      *  version of the gosa version, by comparing it with the configuration
1102      *  file version of the example gosa.conf that comes with GOsa.
1103      *  If a version mismatch occurs an error is triggered.
1104      * */
1105     function check_config_version()
1106     {
1107         /* Skip check, if we've already mentioned the mismatch 
1108          */
1109         if(session::global_is_set("LastChecked") && session::global_get("LastChecked") == $this->config_version) return;
1111         /* Remember last checked version 
1112          */
1113         session::global_set("LastChecked",$this->config_version);
1115         $current = md5(file_get_contents(CONFIG_TEMPLATE_DIR."/gosa.conf"));
1117         /* Check contributed config version and current config version.
1118          */
1119         if(($this->config_version == "NOT SET") || ($this->config_version != $current && !empty($this->config_version))){
1120             msg_dialog::display(_("Configuration"),_("The configuration file you are using is outdated. Please move the GOsa configuration file away to run the GOsa setup again."));
1121         }
1122     }
1125     /*! \brief Check if session lifetime matches session.gc_maxlifetime 
1126      *
1127      *  On debian systems the session files are deleted with
1128      *  a cronjob, which detects all files older than specified 
1129      *  in php.ini:'session.gc_maxlifetime' and removes them.
1130      *  This function checks if the gosa.conf value matches the range
1131      *  defined by session.gc_maxlifetime.
1132      *
1133      *  \return boolean TRUE or FALSE depending on weither the settings match
1134      *  or not. If SESSIONLIFETIME is not configured in GOsa it always returns
1135      *  TRUE.
1136      */
1137     function check_session_lifetime()
1138     {
1139         if(isset($this->data['MAIN']['SESSIONLIFETIME'])){
1140             $cfg_lifetime = $this->data['MAIN']['SESSIONLIFETIME'];
1141             $ini_lifetime = ini_get('session.gc_maxlifetime');
1142             $deb_system   = file_exists('/etc/debian_version');
1143             return(!($deb_system && ($ini_lifetime < $cfg_lifetime)));  
1144         }else{
1145             return(TRUE);
1146         }
1147     }
1149     /* Returns true if snapshots are enabled, and false if it is disalbed
1150        There will also be some errors psoted, if the configuration failed */
1151     function snapshotEnabled()
1152     {
1153         if($this->get_cfg_value("core","enableSnapshots") == "true"){
1155             /* Check if the snapshot_base is defined */
1156             if ($this->get_cfg_value("core","snapshotBase") == ""){
1158                 /* Send message if not done already */
1159                 if(!session::is_set("snapshotFailMessageSend")){
1160                     session::set("snapshotFailMessageSend",TRUE);
1161                     msg_dialog::display(_("Configuration error"),
1162                             sprintf(_("The snapshot functionality is enabled, but the required variable %s is not set."),
1163                                 bold("snapshotBase")), ERROR_DIALOG);
1164                 }
1165                 return(FALSE);
1166             }
1168             /* Check if the snapshot_base is defined */
1169             if (!is_callable("gzcompress")){
1171                 /* Send message if not done already */
1172                 if(!session::is_set("snapshotFailMessageSend")){
1173                     session::set("snapshotFailMessageSend",TRUE);
1174                     msg_dialog::display(_("Configuration error"),
1175                             sprintf(_("The snapshot functionality is enabled, but the required compression module is missing. Please install %s."), bold("php5-zip / php5-gzip")), ERROR_DIALOG);
1176                 }
1177                 return(FALSE);
1178             }
1180             /* check if there are special server configurations for snapshots */
1181             if ($this->get_cfg_value("core","snapshotURI") != ""){
1183                 /* check if all required vars are available to create a new ldap connection */
1184                 $missing = "";
1185                 foreach(array("snapshotURI","snapshotAdminDn","snapshotAdminPassword","snapshotBase") as $var){
1186                     if($this->get_cfg_value("core",$var) == ""){
1187                         $missing .= $var." ";
1189                         /* Send message if not done already */
1190                         if(!session::is_set("snapshotFailMessageSend")){
1191                             session::set("snapshotFailMessageSend",TRUE);
1192                             msg_dialog::display(_("Configuration error"),
1193                                     sprintf(_("The snapshot functionality is enabled, but the required variable %s is not set."),
1194                                         bold($missing)), ERROR_DIALOG);
1195                         }
1196                         return(FALSE);
1197                     }
1198                 }
1199             }
1200             return(TRUE);
1201         }
1202         return(FALSE);
1203     }
1207 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1208 ?>