Code

Updated RPC handling
[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     private $jsonRPChandle = NULL; 
69   public $configRegistry = NULL;
71   /*! \brief Class constructor of the config class
72    *  
73    *  \param string 'filename' path to the configuration file
74    *  \param string 'basedir' base directory
75    *
76    * */
77   function config($filename, $basedir= "")
78   {
79     $this->parser = xml_parser_create();
80     $this->basedir= $basedir;
82     xml_set_object($this->parser, $this);
83     xml_set_element_handler($this->parser, "tag_open", "tag_close");
85     /* Parse config file directly? */
86     if ($filename != ""){
87       $this->parse($filename);
88     }
90     // Load configuration registry
91     $this->configRegistry = new configRegistry($this);
92   }
95   /*! \brief Check and reload the configuration
96    * 
97    * This function checks if the configuration has changed, since it was
98    * read the last time and reloads it. It uses the file mtime to check
99    * weither the file changed or not.
100    *
101    * */ 
102   function check_and_reload()
103   {
104     global $ui;
106     /* Check if class_location.inc has changed, this is the case 
107         if we have installed or removed plugins. 
108      */
109     if(session::global_is_set("class_location.inc:timestamp")){
110       $tmp = stat("../include/class_location.inc");
111       if($tmp['mtime'] != session::global_get("class_location.inc:timestamp")){
112         session::global_un_set("plist");
113       }
114     }
115     $tmp = stat("../include/class_location.inc");
116     session::global_set("class_location.inc:timestamp",$tmp['mtime']);
118     if($this->filename != "" && filemtime($this->filename) != $this->last_modified){
120       $this->config_found= FALSE;
121       $this->tags= array();
122       $this->level= 0;
123       $this->gpc= 0;
124       $this->section= "";
125       $this->currentLocation= "";
127       $this->parser = xml_parser_create();
128       xml_set_object($this->parser, $this);
129       xml_set_element_handler($this->parser, "tag_open", "tag_close");
130       $this->parse($this->filename);
131       $this->set_current($this->current['NAME']);
132     }
133   }  
136   /*! \brief Parse the given configuration file 
137    *
138    *  Parses the configuration file and displays errors if there
139    *  is something wrong with it.
140    *
141    *  \param string 'filename' The filename of the configuration file.
142    * */
144   function parse($filename)
145   {
146     $this->data = array(
147         "TABS"      => array(), 
148         "LOCATIONS" => array(), 
149         "MAIN"      => array(), 
150         "MENU"      => array(), 
151         "SERVICE"   => array());
153     $this->last_modified = filemtime($filename);
154     $this->filename = $filename;
155     $fh= fopen($filename, "r"); 
156     $xmldata= fread($fh, 100000);
157     fclose($fh);
158     if(!xml_parse($this->parser, chop($xmldata))){
159       $msg = sprintf(_("XML error in gosa.conf: %s at line %d"),
160             bold(xml_error_string(xml_get_error_code($this->parser))),
161             bold(xml_get_current_line_number($this->parser)));
162       msg_dialog::display(_("Configuration error"), $msg, FATAL_ERROR_DIALOG);
163       exit;
164     }
165   }
167   function tag_open($parser, $tag, $attrs)
168   {
169     /* Save last and current tag for reference */
170     $this->tags[$this->level]= $tag;
171     $this->level++;
173     /* Trigger on CONF section */
174     if ($tag == 'CONF'){
175       $this->config_found= TRUE;
176       if(isset($attrs['CONFIGVERSION'])){
177         $this->config_version = $attrs['CONFIGVERSION'];
178       }
179     }
181     /* Return if we're not in config section */
182     if (!$this->config_found){
183       return;
184     }
186     /* yes/no to true/false and upper case TRUE to true and so on*/
187     foreach($attrs as $name => $value){
188       if(preg_match("/^(true|yes)$/i",$value)){
189         $attrs[$name] = "true";
190       }elseif(preg_match("/^(false|no)$/i",$value)){
191         $attrs[$name] = "false";
192       } 
193     }
195     /* Look through attributes */
196     switch ($this->tags[$this->level-1]){
199       /* Handle tab section */
200       case 'TAB':       $name= $this->tags[$this->level-2];
202                   /* Create new array? */
203                   if (!isset($this->data['TABS'][$name])){
204                     $this->data['TABS'][$name]= array();
205                   }
207                   /* Add elements */
208                   $this->data['TABS'][$name][]= $attrs;
209                   break;
211                   /* Handle location */
212       case 'LOCATION':
213                   if ($this->tags[$this->level-2] == 'MAIN'){
214                     $name= $attrs['NAME'];
215                     $name = preg_replace("/[<>\"']/","",$name);
216                     $attrs['NAME'] = $name;
217                     $this->currentLocation= $name;
219                     /* Add location elements */
220                     $this->data['LOCATIONS'][$name]= $attrs;
221                   }
222                   break;
224                   /* Handle referral tags */
225       case 'REFERRAL':
226                   if ($this->tags[$this->level-2] == 'LOCATION'){
227                     $url= $attrs['URI'];
228                     $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
230                     /* Add location elements */
231                     if (!isset($this->data['LOCATIONS'][$this->currentLocation]['REFERRAL'])){
232                       $this->data['LOCATIONS'][$this->currentLocation]['REFERRAL']= array();
233                     }
235                     $this->data['LOCATIONS'][$this->currentLocation]['REFERRAL'][$server]= $attrs;
236                   }
237                   break;
239                   /* Load main parameters */
240       case 'MAIN':
241                   $this->data['MAIN']= array_merge ($this->data['MAIN'], $attrs);
242                   break;
244                   /* Load menu */
245       case 'SECTION':
246                   if ($this->tags[$this->level-2] == 'MENU'){
247                     $this->section= $attrs['NAME'];
248                     $this->data['MENU'][$this->section]= array(); ;
249                   }
250                   break;
252       case 'PATHMENU':
253                   $this->data['PATHMENU']= array(); ;
254                   break;
256                   /* Inser plugins */
257       case 'PLUGIN':
258                   if ($this->tags[$this->level-3] == 'MENU' &&
259                       $this->tags[$this->level-2] == 'SECTION'){
261                     $this->data['MENU'][$this->section][$this->gpc++]= $attrs;
262                   }
263                   if ($this->tags[$this->level-2] == 'PATHMENU'){
264                     $this->data['PATHMENU'][$this->gpc++]= $attrs;
265                   }
266                   if ($this->tags[$this->level-2] == 'SERVICEMENU'){
267                     $this->data['SERVICE'][$attrs['CLASS']]= $attrs;
268                   }
269                   break;
270     }
271   }
273   function tag_close($parser, $tag)
274   {
275     /* Close config section */
276     if ($tag == 'CONF'){
277       $this->config_found= FALSE;
278     }
279     $this->level--;
280   }
283   function get_credentials($creds)
284   {
285     if (isset($_SERVER['HTTP_GOSA_KEY'])){
286       if (!session::global_is_set('HTTP_GOSA_KEY_CACHE')){
287         session::global_set('HTTP_GOSA_KEY_CACHE',array());
288       }
289       $cache = session::global_get('HTTP_GOSA_KEY_CACHE');
290       if(!isset($cache[$creds])){
291         $cache[$creds] = cred_decrypt($creds, $_SERVER['HTTP_GOSA_KEY']);
292         session::global_set('HTTP_GOSA_KEY_CACHE',$cache);
293       }
294       return ($cache[$creds]);
295     }
296     return ($creds);
297   }
300   function getRpcHandle()
301   {
302       // Create jsonRPC handle on demand.
303       if(!$this->jsonRPChandle){
304           $this->jsonRPChandle = new jsonRPC($this);
305       }
306       return($this->jsonRPChandle);
307   }
308     
310   /*! \brief Get a LDAP link object
311    *
312    * This function can be used to get an ldap object, which in turn can
313    * be used to query the LDAP. See the LDAP class for more information
314    * on how to use it.
315    *
316    * Example usage:
317    * \code
318    * $ldap = $this->config->get_ldap_link();
319    * \endcode
320    *
321    * \param boolean sizelimit Weither to impose a sizelimit on the LDAP object or not.
322    * Defaults to false. If set to true, the size limit in the configuration
323    * file will be used to set the option LDAP_OPT_SIZELIMIT.
324    * \return ldapMultiplexer object
325    */
326   function get_ldap_link($sizelimit= FALSE)
327   {
328     if($this->ldap === NULL || !is_resource($this->ldap->cid)){
330       /* Build new connection */
331       $this->ldap= ldap_init ($this->current['SERVER'], $this->current['BASE'],
332           $this->current['ADMINDN'], $this->get_credentials($this->current['ADMINPASSWORD']));
334       /* Check for connection */
335       if (is_null($this->ldap) || (is_int($this->ldap) && $this->ldap == 0)){
336         $smarty= get_smarty();
337         msg_dialog::display(_("LDAP error"), _("Cannot bind to LDAP!"), FATAL_ERROR_DIALOG);
338         exit();
339       }
341       /* Move referrals */
342       if (!isset($this->current['REFERRAL'])){
343         $this->ldap->referrals= array();
344       } else {
345         $this->ldap->referrals= $this->current['REFERRAL'];
346       }
348       if (!session::global_is_set('size_limit')){
349         session::global_set('size_limit', $this->get_cfg_value('core', 'ldapSizelimit'));
350         session::global_set('size_ignore', $this->boolValueIsTrue('core', 'ldapSizeIgnore'));
351       }
352     }
354     $obj  = new ldapMultiplexer($this->ldap);
355     if ($sizelimit){
356       $obj->set_size_limit(session::global_get('size_limit'));
357     } else {
358       $obj->set_size_limit(0);
359     }
360     return($obj);
361   }
363   /*! \brief Set the current location
364    *  
365    *  \param string name the name of the location
366    */
367   function set_current($name)
368   {
369     $this->current= $this->data['LOCATIONS'][$name];
371     if (isset($this->current['INITIAL_BASE'])){
372       session::global_set('CurrentMainBase',$this->current['INITIAL_BASE']);
373     }
374   
375     /* Sort referrals, if present */
376     if (isset ($this->current['REFERRAL'])){
377       $bases= array();
378       $servers= array();
379       foreach ($this->current['REFERRAL'] as $ref){
380         $server= preg_replace('%^(.*://[^/]+)/.*$%', '\\1', $ref['URI']);
381         $base= preg_replace('%^.*://[^/]+/(.*)$%', '\\1', $ref['URI']);
382         $bases[$base]= strlen($base);
383         $servers[$base]= $server;
384       }
385       asort($bases);
386       reset($bases);
387     }
389     /* SERVER not defined? Load the one with the shortest base */
390     if (!isset($this->current['SERVER'])){
391       $this->current['SERVER']= $servers[key($bases)];
392     }
394     /* BASE not defined? Load the one with the shortest base */
395     if (!isset($this->current['BASE'])){
396       $this->current['BASE']= key($bases);
397     }
399     /* Convert BASE to have escaped special characters */
400     $this->current['BASE']= @LDAP::convert($this->current['BASE']);
402     /* Parse LDAP referral informations */
403     if (!isset($this->current['ADMINDN']) || !isset($this->current['ADMINPASSWORD'])){
404       $url= $this->current['SERVER'];
405       $referral= $this->current['REFERRAL'][$url];
406       $this->current['ADMINDN']= $referral['ADMINDN'];
407       $this->current['ADMINPASSWORD']= $referral['ADMINPASSWORD'];
408     }
410     /* Load server informations */
411     $this->load_servers();
412   }
415   /*! \brief Load server information from config/LDAP
416    *
417    *  This function searches the LDAP for servers (e.g. goImapServer, goMailServer etc.)
418    *  and stores information about them $this->data['SERVERS']. In the case of mailservers
419    *  the main section of the configuration file is searched, too.
420    */
421   function load_servers ()
422   {
423     /* Only perform actions if current is set */
424     if ($this->current === NULL){
425       return;
426     }
428     /* Fill imap servers */
429     $ldap= $this->get_ldap_link();
430     $ldap->cd ($this->current['BASE']);
432     /* Search mailMethod konfiguration in main section too 
433      */
434     $tmp = $this->get_cfg_value("core","mailMethod");
435     if ($tmp){
436       $ldap->search ("(objectClass=goMailServer)", array('cn'));
437       $this->data['SERVERS']['IMAP']= array();
438       while ($attrs= $ldap->fetch()){
439         $name= $attrs['cn'][0];
440         $this->data['SERVERS']['IMAP'][$name]= 
441           array( 
442               "server_dn"   => $attrs['dn'],
443               "connect"     => "",
444               "admin"       => "",
445               "password"    => "",
446               "sieve_server"=> "",
447               "sieve_option"=> "",
448               "sieve_port"  => "");
449       }
450     } else {
451       $ldap->search ("(&(objectClass=goImapServer)(goImapSieveServer=*))", 
452                     array('goImapName', 'goImapConnect', 'goImapAdmin', 'goImapPassword',
453             'goImapSieveServer', 'goImapSievePort'));
455       $this->data['SERVERS']['IMAP']= array();
457       while ($attrs= $ldap->fetch()){
459         /* Check if the given goImapSieveServer is in the new style "{cn:port/option}"
460            or the old style just "cn".
461          */
462         if(preg_match("/\{/",$attrs['goImapSieveServer'][0])){
463           $sieve_server = preg_replace("/^\{([^:]*).*$/","\\1",$attrs['goImapSieveServer'][0]);
464           $sieve_option = preg_replace("/^[^:]*[^\/]*+\/(.*)\}$/","\\1",$attrs['goImapSieveServer'][0]);
465         }else{
466           $sieve_server = $attrs['goImapSieveServer'][0];
467           $sieve_option = "";
468         }
470         $pwd            = $attrs['goImapPassword'][0];
471         $imap_admin     = $attrs['goImapAdmin'][0];
472         $imap_connect   = $attrs['goImapConnect'][0];
473         $imap_server    = $attrs['goImapName'][0];
474         $sieve_port     = $attrs['goImapSievePort'][0];
475         
476         $this->data['SERVERS']['IMAP'][$imap_server]= 
477             array( 
478             "server_dn"   => $attrs['dn'],
479             "connect"     => $imap_connect,
480             "admin"       => $imap_admin,
481             "password"    => $pwd,
482             "sieve_server"=> $sieve_server,
483             "sieve_option"=> $sieve_option,
484             "sieve_port"  => $sieve_port);
485       }
486     }
488     /* Get kerberos server. FIXME: only one is supported currently */
489     $ldap->cd ($this->current['BASE']);
490     $ldap->search ("(&(goKrbRealm=*)(goKrbAdmin=*)(objectClass=goKrbServer))");
491     if ($ldap->count()){
492       $attrs= $ldap->fetch();
493       $this->data['SERVERS']['KERBEROS']= array( 'SERVER' => $attrs['cn'][0],
494           'REALM' => $attrs['goKrbRealm'][0],
495           'ADMIN' => $attrs['goKrbAdmin'][0]);
496     }
498     /* Get cups server. FIXME: only one is supported currently */
499     $ldap->cd ($this->current['BASE']);
500     $ldap->search ("(objectClass=goCupsServer)");
501     if ($ldap->count()){
502       $attrs= $ldap->fetch();
503       $this->data['SERVERS']['CUPS']= $attrs['cn'][0];  
504     }
506     /* Get fax server. FIXME: only one is supported currently */
507     $ldap->cd ($this->current['BASE']);
508     $ldap->search ("(objectClass=goFaxServer)");
509     if ($ldap->count()){
510       $attrs= $ldap->fetch();
511       $this->data['SERVERS']['FAX']= array( 'SERVER' => $attrs['cn'][0],
512           'LOGIN' => $attrs['goFaxAdmin'][0],
513           'PASSWORD' => $attrs['goFaxPassword'][0]);
514     }
517     /* Get asterisk servers */
518     $ldap->cd ($this->current['BASE']);
519     $ldap->search ("(objectClass=goFonServer)");
520     $this->data['SERVERS']['FON']= array();
521     if ($ldap->count()){
522       while ($attrs= $ldap->fetch()){
524         /* Add 0 entry for development */
525         if(count($this->data['SERVERS']['FON']) == 0){
526           $this->data['SERVERS']['FON'][0]= array(
527               'DN'      => $attrs['dn'],
528               'SERVER'  => $attrs['cn'][0],
529               'LOGIN'   => $attrs['goFonAdmin'][0],
530               'PASSWORD'  => $attrs['goFonPassword'][0],
531               'DB'    => "gophone",
532               'SIP_TABLE'   => "sip_users",
533               'EXT_TABLE'   => "extensions",
534               'VOICE_TABLE' => "voicemail_users",
535               'QUEUE_TABLE' => "queues",
536               'QUEUE_MEMBER_TABLE'  => "queue_members");
537         }
539         /* Add entry with 'dn' as index */
540         $this->data['SERVERS']['FON'][$attrs['dn']]= array(
541             'DN'      => $attrs['dn'],
542             'SERVER'  => $attrs['cn'][0],
543             'LOGIN'   => $attrs['goFonAdmin'][0],
544             'PASSWORD'  => $attrs['goFonPassword'][0],
545             'DB'    => "gophone",
546             'SIP_TABLE'   => "sip_users",
547             'EXT_TABLE'   => "extensions",
548             'VOICE_TABLE' => "voicemail_users",
549             'QUEUE_TABLE' => "queues",
550             'QUEUE_MEMBER_TABLE'  => "queue_members");
551       }
552     }
555     /* Get glpi server */
556     $ldap->cd ($this->current['BASE']);
557     $ldap->search ("(&(objectClass=goGlpiServer)(cn=*)(goGlpiAdmin=*)(goGlpiDatabase=*))",array("cn","goGlpiPassword","goGlpiAdmin","goGlpiDatabase"));
558     if ($ldap->count()){
559       $attrs= $ldap->fetch();
560       if(!isset($attrs['goGlpiPassword'])){
561         $attrs['goGlpiPassword'][0] ="";
562       }
563       $this->data['SERVERS']['GLPI']= array( 
564           'SERVER'      => $attrs['cn'][0],
565           'LOGIN'       => $attrs['goGlpiAdmin'][0],
566           'PASSWORD'    => $attrs['goGlpiPassword'][0],
567           'DB'          => $attrs['goGlpiDatabase'][0]);
568     }
571     /* Get logdb server */
572     $ldap->cd ($this->current['BASE']);
573     $ldap->search ("(objectClass=goLogDBServer)");
574     if ($ldap->count()){
575       $attrs= $ldap->fetch();
576       if(!isset($attrs['gosaLogDB'][0])){
577         $attrs['gosaLogDB'][0] = "gomon";
578       }
579       $this->data['SERVERS']['LOG']= array( 'SERVER' => $attrs['cn'][0],
580           'LOGIN' => $attrs['goLogAdmin'][0],
581           'DB' => $attrs['gosaLogDB'][0],
582           'PASSWORD' => $attrs['goLogPassword'][0]);
583     }
586     /* GOsa logging databases */
587     $ldap->cd ($this->current['BASE']);
588     $ldap->search ("(objectClass=gosaLogServer)");
589     if ($ldap->count()){
590       while($attrs= $ldap->fetch()){
591       $this->data['SERVERS']['LOGGING'][$attrs['cn'][0]]= 
592           array(
593           'DN'    => $attrs['dn'],
594           'USER'  => $attrs['goLogDBUser'][0],
595           'DB'    => $attrs['goLogDB'][0],
596           'PWD'   => $attrs['goLogDBPassword'][0]);
597       }
598     }
601     /* Get NFS server lists */
602     $tmp= array("default");
603     $tmp2= array("default");
604     $ldap->cd ($this->current['BASE']);
605     $ldap->search ("(&(objectClass=goShareServer)(goExportEntry=*))");
606     while ($attrs= $ldap->fetch()){
607       for ($i= 0; $i<$attrs["goExportEntry"]["count"]; $i++){
608         if(preg_match('/^[^|]+\|[^|]+\|NFS\|.*$/', $attrs["goExportEntry"][$i])){
609           $path= preg_replace ("/^[^|]+\|[^|]+\|[^|]+\|[^|]+\|([^|]+).*$/", '\1', $attrs["goExportEntry"][$i]);
610           $tmp[]= $attrs["cn"][0].":$path";
611         }
612         if(preg_match('/^[^|]+\|[^|]+\|NBD\|.*$/', $attrs["goExportEntry"][$i])){
613           $path= preg_replace ("/^[^|]+\|[^|]+\|[^|]+\|[^|]+\|([^|]+).*$/", '\1', $attrs["goExportEntry"][$i]);
614           $tmp2[]= $attrs["cn"][0].":$path";
615         }
616       }
617     }
618     $this->data['SERVERS']['NFS']= $tmp;
619     $this->data['SERVERS']['NBD']= $tmp2;
621     /* Load Terminalservers */
622     $ldap->cd ($this->current['BASE']);
623     $ldap->search ("(objectClass=goTerminalServer)",array("cn","gotoSessionType"));
624     $this->data['SERVERS']['TERMINAL']= array();
625     $this->data['SERVERS']['TERMINAL'][]= "default";
626     $this->data['SERVERS']['TERMINAL_SESSION_TYPES'] = array();
629     while ($attrs= $ldap->fetch()){
630       $this->data['SERVERS']['TERMINAL'][]= $attrs["cn"][0];
631       if(isset( $attrs["gotoSessionType"]['count'])){
632         for($i =0 ; $i < $attrs["gotoSessionType"]['count'] ; $i++){
633           $this->data['SERVERS']['TERMINAL_SESSION_TYPES'][$attrs["cn"][0]][] = $attrs["gotoSessionType"][$i]; 
634         }
635       }
636     }
638     /* Ldap Server 
639      */
640     $this->data['SERVERS']['LDAP']= array();
641     $ldap->cd ($this->current['BASE']);
642     $ldap->search ("(&(objectClass=goLdapServer)(goLdapBase=*))");
643     while ($attrs= $ldap->fetch()){
644       $this->data['SERVERS']['LDAP'][$attrs['dn']] = $attrs;
645     }
647     /* Get misc server lists */
648     $this->data['SERVERS']['SYSLOG']= array("default");
649     $this->data['SERVERS']['NTP']= array("default");
650     $ldap->cd ($this->current['BASE']);
651     $ldap->search ("(objectClass=goNtpServer)");
652     while ($attrs= $ldap->fetch()){
653       $this->data['SERVERS']['NTP'][]= $attrs["cn"][0];
654     }
655     $ldap->cd ($this->current['BASE']);
656     $ldap->search ("(objectClass=goSyslogServer)");
657     while ($attrs= $ldap->fetch()){
658       $this->data['SERVERS']['SYSLOG'][]= $attrs["cn"][0];
659     }
661     /* Get samba servers from LDAP, in case of samba3 */
662     $this->data['SERVERS']['SAMBA']= array();
663     $ldap->cd ($this->current['BASE']);
664     $ldap->search ("(objectClass=sambaDomain)");
665     while ($attrs= $ldap->fetch()){
666       $this->data['SERVERS']['SAMBA'][$attrs['sambaDomainName'][0]]= array( "SID" =>"","RIDBASE" =>"");
667       if(isset($attrs["sambaSID"][0])){
668         $this->data['SERVERS']['SAMBA'][$attrs['sambaDomainName'][0]]["SID"]  = $attrs["sambaSID"][0];
669       }
670       if(isset($attrs["sambaAlgorithmicRidBase"][0])){
671         $this->data['SERVERS']['SAMBA'][$attrs['sambaDomainName'][0]]["RIDBASE"] = $attrs["sambaAlgorithmicRidBase"][0];
672       }
673     }
675     /* If no samba servers are found, look for configured sid/ridbase */
676     if (count($this->data['SERVERS']['SAMBA']) == 0){
677       if (!isset($this->current["SAMBASID"]) || !isset($this->current["SAMBARIDBASE"])){
678         msg_dialog::display(_("Configuration error"), _("sambaSID and/or sambaRidBase missing in the configuration!"), ERROR_DIALOG);
679       } else {
680         $this->data['SERVERS']['SAMBA']['DEFAULT']= array(
681             "SID" => $this->current["SAMBASID"],
682             "RIDBASE" => $this->current["SAMBARIDBASE"]);
683       }
684     }
685     
686   }
689   function get_departments($ignore_dn= "")
690   {
691     global $config;
693     /* Initialize result hash */
694     $result= array();
695     $administrative= array();
696     $result['/']= $this->current['BASE'];
697     $this->tdepartments= array();
699     /* Get all department types from department Management, to be able detect the department type.
700         -It is possible that differnty department types have the same name, 
701          in this case we have to mark the department name to be able to differentiate.
702           (e.g l=Name  or   o=Name)
703      */    
704     $types = departmentManagement::get_support_departments();
705     
706     /* Create a list of attributes to fetch */
707     $ldap_values = array("objectClass","gosaUnitTag", "description");
708     $filter = "";
709     foreach($types as $type){
710       $ldap_values[] = $type['ATTR'];
711       $filter .= "(objectClass=".$type['OC'].")";
712     }
713     $filter = "(&(objectClass=gosaDepartment)(|".$filter."))";
715     /* Get list of department objects */
716     $ldap= $this->get_ldap_link();
717     $ldap->cd ($this->current['BASE']);
718     $ldap->search ($filter, $ldap_values);
719     while ($attrs= $ldap->fetch()){
721       /* Detect department type */
722       $type_data = array();
723       foreach($types as $t => $data){
724         if(in_array($data['OC'],$attrs['objectClass'])){
725           $type_data = $data;
726           break;
727         }
728       }
730       /* Unknown department type -> skip */
731       if(!count($type_data)) continue;
733       $dn= $ldap->getDN();
734       $this->tdepartments[$dn]= "";
735       $this->department_info[$dn]= array("img" => $type_data['IMG'],
736                                          "description" => isset($attrs['description'][0])?$attrs['description'][0]:"",
737                                          "name" => $attrs[$type_data['ATTR']][0]);
739       /* Save administrative departments */
740       if (in_array_ics("gosaAdministrativeUnit", $attrs['objectClass']) &&
741           isset($attrs['gosaUnitTag'][0])){
742         $administrative[$dn]= $attrs['gosaUnitTag'][0];
743         $this->tdepartments[$dn]= $attrs['gosaUnitTag'][0];
744       }
745     
746       if (in_array_ics("gosaAdministrativeUnitTag", $attrs['objectClass']) &&
747           isset($attrs['gosaUnitTag'][0])){
748         $this->tdepartments[$dn]= $attrs['gosaUnitTag'][0];
749       }
750     
751       if ($dn == $ignore_dn){
752         continue;
753       }
754       $c_dn = convert_department_dn($dn)." (".$type_data['ATTR'].")";
756       /* Only assign non-root departments */
757       if ($dn != $result['/']){
758         $result[$c_dn]= $dn;
759       }
760     }
762     $this->adepartments= $administrative;
763     $this->departments= $result;
764   }
767   function make_idepartments($max_size= 28)
768   {
769     global $config;
770     $base = $config->current['BASE'];
771                 $qbase = preg_quote($base, '/');
772     $utags= isset($config->current['HONOURUNITTAGS']) && preg_match('/true/i', $config->current['HONOURUNITTAGS']);
774     $arr = array();
775     $ui= get_userinfo();
777     $this->idepartments= array();
779     /* Create multidimensional array, with all departments. */
780     foreach ($this->departments as $key => $val){
782       /* When using strict_units, filter non relevant parts */
783       if ($utags){
784         if ($ui->gosaUnitTag != '' && isset($this->tdepartments[$val]) &&
785             $this->tdepartments[$val] != $ui->gosaUnitTag){
787                                                 #TODO: link with strict*
788                                                 #continue;
789         }
790       }
792       /* Split dn into single department pieces */
793       $elements = array_reverse(explode(',',preg_replace("/$qbase$/",'',$val)));                
795       /* Add last ou element of current dn to our array */
796       $last = &$arr;
797       foreach($elements as $key => $ele){
799         /* skip empty */
800         if(empty($ele)) continue;
802         /* Extract department name */           
803         $elestr = trim(preg_replace('/^[^=]*+=/','', $ele),',');
804         $nameA  = trim(preg_replace('/=.*$/','', $ele),',');
805         if($nameA != 'ou'){
806           $nameA = " ($nameA)";
807         }else{
808           $nameA = '';
809         }
810     
811         /* Add to array */      
812         if($key == (count($elements)-1)){
813           $last[$elestr.$nameA]['ENTRY'] = $val;
814         }
816         /* Set next array appending position */
817         $last = &$last[$elestr.$nameA]['SUB'];
818       }
819     }
822     /* Add base entry */
823     $ret['/']['ENTRY']  = $base;
824     $ret['/']['SUB']    = $arr;
825     $this->idepartments= $this->generateDepartmentArray($ret,-1,$max_size);
826   }
829   /* Creates display friendly output from make_idepartments */
830   function generateDepartmentArray($arr,$depth = -1,$max_size = 256)
831   {
832     $ret = array();
833     $depth ++;
835     /* Walk through array */    
836     ksort($arr);
837     foreach($arr as $name => $entries){
839       /* If this department is the last in the current tree position 
840        * remove it, to avoid generating output for it */
841       if(count($entries['SUB'])==0){
842         unset($entries['SUB']);
843       }
845       /* Fix name, if it contains a replace tag */
846       $name= preg_replace('/\\\\,/', ',', LDAP::fix($name));
848       /* Check if current name is too long, then cut it */
849       if(mb_strlen($name, 'UTF-8')> $max_size){
850         $name = mb_substr($name,0,($max_size-3), 'UTF-8')." ...";
851       }
853       /* Append the name to the list */ 
854       if(isset($entries['ENTRY'])){
855         $a = "";
856         for($i = 0 ; $i < $depth ; $i ++){
857           $a.=".";
858         }
859         $ret[$entries['ENTRY']]=$a."&nbsp;".$name;
860       } 
862       /* recursive add of subdepartments */
863       if(isset($entries['SUB'])){
864         $ret = array_merge($ret,$this->generateDepartmentArray($entries['SUB'],$depth,$max_size));
865       }
866     }
868     return($ret);
869   }
871   /*! \brief Get all available shares defined in the current LDAP
872    *
873    *  This function returns all available Shares defined in this ldap
874    *  
875    *  \param boolean listboxEntry If set to TRUE, only name and path are
876    *  attached to the array. If FALSE, the whole entry will be parsed an atached to the result.
877    *  \return array
878    */
879   function getShareList($listboxEntry = false)
880   {
881     $tmp = get_sub_list("(&(objectClass=goShareServer)(goExportEntry=*))","server",get_ou("servgeneric", "serverRDN"),
882         $this->current['BASE'],array("goExportEntry","cn"), GL_NONE);
883     $return =array();
884     foreach($tmp as $entry){
886       if(isset($entry['goExportEntry']['count'])){
887         unset($entry['goExportEntry']['count']);
888       }
889       if(isset($entry['goExportEntry'])){
890         foreach($entry['goExportEntry'] as $export){
891           $shareAttrs = explode("|",$export);
892           if($listboxEntry) {
893             $return[$shareAttrs[0]."|".$entry['cn'][0]] = $shareAttrs[0]." - ".$entry['cn'][0];
894           }else{
895             $return[$shareAttrs[0]."|".$entry['cn'][0]]['server']       = $entry['cn'][0];
896             $return[$shareAttrs[0]."|".$entry['cn'][0]]['name']         = $shareAttrs[0];
897             $return[$shareAttrs[0]."|".$entry['cn'][0]]['description']  = $shareAttrs[1];
898             $return[$shareAttrs[0]."|".$entry['cn'][0]]['type']         = $shareAttrs[2];
899             $return[$shareAttrs[0]."|".$entry['cn'][0]]['charset']      = $shareAttrs[3];
900             $return[$shareAttrs[0]."|".$entry['cn'][0]]['path']         = $shareAttrs[4];
901             $return[$shareAttrs[0]."|".$entry['cn'][0]]['option']       = $shareAttrs[5];
902           }
903         }
904       }
905     }
906     return($return);
907   }
910   /*! \brief Return al available share servers
911    *
912    * This function returns all available ShareServers.
913    *
914    * \return array
915    * */
916   function getShareServerList()
917   {
918     global $config;
919     $return = array();
920     $ui = get_userinfo();
921     $base = $config->current['BASE'];
922     $res= get_sub_list("(&(objectClass=goShareServer)(goExportEntry=*))", "server",
923           get_ou("servgeneric", "serverRDN"), $base,array("goExportEntry","cn"),GL_NONE | GL_NO_ACL_CHECK);
925     foreach($res as $entry){
926         
927         $acl = $ui->get_permissions($entry['dn'],"server","");
928         if(isset($entry['goExportEntry']['count'])){
929           unset($entry['goExportEntry']['count']);
930         }
931         foreach($entry['goExportEntry'] as $share){
932           $a_share = explode("|",$share);
933           $sharename = $a_share[0];
934           $data= array();
935           $data['NAME']   = $sharename;
936           $data['ACL']    = $acl;
937           $data['SERVER'] = $entry['cn']['0'];
938           $data['SHARE']  = $sharename;
939           $data['DISPLAY']= $entry['cn'][0]." [".$sharename."]";
940           $return[$entry['cn'][0]."|".$sharename] = $data;
941         }
942     }
943     return($return);
944   }
947   /*! \brief Checks if there's a bool property set in the configuration.
948    *
949    *  The function checks, weither the specified bool value is set to a true
950    *  value in the configuration file. 
951    *
952    *  Example usage:
953    *  \code
954    *  if ($this->config->boolValueIsTrue("core", "copyPaste")) {
955    *    echo "Copy Paste Handling is enabled";
956    *  }
957    *  \endcode
958    *
959    *  \param string 'class' The properties class. e.g. 'core','user','sudo',...
960    *  \param string 'value' Key in the given section, which is subject to check
961    *
962    *
963    * */
964   function boolValueIsTrue($class, $name)
965   {
966     return(preg_match("/true/i", $this->get_cfg_value($class,$name)));
967   }
970   function __search(&$arr, $name, $return)
971   {
972     $return= strtoupper($return);
973     if (is_array($arr)){
974       foreach ($arr as &$a){
975         if (isset($a['CLASS']) && strcasecmp($name, $a['CLASS']) == 0){
976           return(isset($a[$return])?$a[$return]:"");
977         } else {
978           $res= $this->__search ($a, $name, $return);
979           if ($res != ""){
980             return $res;
981           }
982         }
983       }
984     }
985     return ("");
986   }
989   /*! Outdated - try to use pluginEnabled, boolValueIsTrue or get_cfg_value instead. 
990    *
991    *  (Search for a configuration setting in different categories
992    *
993    *  Searches for the value of a given key in the configuration data.
994    *  Optionally the list of categories to search (tabs, main, locations) can
995    *  be specified. The first value that matches is returned.
996    *
997    *  Example usage:
998    *  \code
999    *  $postcmd = $this->config->search(get_class($this), "POSTCOMMAND", array("menu", "tabs"));
1000    *  \endcode
1001    *  ) 
1002    *
1003    * */
1004   function search($class, $value, $categories= "")
1005   {
1006     if (is_array($categories)){
1007       foreach ($categories as $category){
1008         $res= $this->__search($this->data[strtoupper($category)], $class, $value);
1009         if ($res != ""){
1010           return $res;
1011         }
1012       }
1013     } else {
1014       if ($categories == "") {
1015         return $this->__search($this->data, $class, $value);
1016       } else {
1017         return $this->__search($this->data[strtoupper($categories)], $class, $value);
1018       }
1019     } 
1021     return ("");
1022   }
1024    
1025   /*! \brief          Check whether a plugin is activated or not 
1026    */ 
1027   function pluginEnabled($class){
1028       $tmp = $this->search($class, "CLASS",array('menu','tabs'));
1029       return(!empty($tmp));
1030   }
1033   /*! \brief Get a configuration value from the config
1034    *
1035    *  This returns a configuration value from the config. It either
1036    *  uses the data of the current location ($this->current),
1037    *  if it contains the value (e.g. current['BASE']) or otherwise
1038    *  uses the data from the main configuration section.
1039    *
1040    *  If no value is found and an optional default has been specified,
1041    *  then the default is returned.
1042    *
1043    *  \param string 'name' the configuration key (case-insensitive)
1044    *  \param string 'default' a default that is returned, if no value is found
1045    *
1046    *
1047    */
1048   function get_cfg_value($class,$name, $default= NULL) 
1049   {
1050     // The default parameter is deprecated 
1051     if($default != NULL){
1052 #        trigger_error("Third parameter 'default' is deprecated for function 'get_cfg_value'!");
1053     }
1055     // Return the matching property value if it exists.
1056     if($this->configRegistry->propertyExists($class,$name)){
1057         return($this->configRegistry->getPropertyValue($class,$name));
1058     }
1060     // Show a warning in the syslog if there is an undefined property requested.
1061     if($this->configRegistry->propertyInitializationComplete() && 
1062             "{$class}::{$name}" != 'core::config' &&  // <--- This on is never set, only in gosa.conf. 
1063             "{$class}::{$name}" != 'core::logging'){  // <--- This one may cause endless recursions in class_log.inc
1064         new log("debug","","Unconfigured property: '{$class}::{$name}'",array(),'');
1065     }
1067     // Try to find the property in the config file directly.
1068     $name= strtoupper($name);
1069     if (isset($this->current[$name])) return ($this->current[$name]);
1070     if (isset($this->data["MAIN"][$name])) return ($this->data["MAIN"][$name]);
1071     return ("");
1072   }
1075   /*! \brief Check if current configuration version matches the GOsa version
1076    *
1077    *  This function checks if the configuration file version matches the
1078    *  version of the gosa version, by comparing it with the configuration
1079    *  file version of the example gosa.conf that comes with GOsa.
1080    *  If a version mismatch occurs an error is triggered.
1081    * */
1082   function check_config_version()
1083   {
1084     /* Skip check, if we've already mentioned the mismatch 
1085      */
1086     if(session::global_is_set("LastChecked") && session::global_get("LastChecked") == $this->config_version) return;
1087   
1088     /* Remember last checked version 
1089      */
1090     session::global_set("LastChecked",$this->config_version);
1092     $current = md5(file_get_contents(CONFIG_TEMPLATE_DIR."/gosa.conf"));
1094     /* Check contributed config version and current config version.
1095      */
1096     if(($this->config_version == "NOT SET") || ($this->config_version != $current && !empty($this->config_version))){
1097       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."));
1098     }
1099   }
1102   /*! \brief Check if session lifetime matches session.gc_maxlifetime 
1103    *
1104    *  On debian systems the session files are deleted with
1105    *  a cronjob, which detects all files older than specified 
1106    *  in php.ini:'session.gc_maxlifetime' and removes them.
1107    *  This function checks if the gosa.conf value matches the range
1108    *  defined by session.gc_maxlifetime.
1109    *
1110    *  \return boolean TRUE or FALSE depending on weither the settings match
1111    *  or not. If SESSIONLIFETIME is not configured in GOsa it always returns
1112    *  TRUE.
1113    */
1114   function check_session_lifetime()
1115   {
1116     if(isset($this->data['MAIN']['SESSIONLIFETIME'])){
1117       $cfg_lifetime = $this->data['MAIN']['SESSIONLIFETIME'];
1118       $ini_lifetime = ini_get('session.gc_maxlifetime');
1119       $deb_system   = file_exists('/etc/debian_version');
1120       return(!($deb_system && ($ini_lifetime < $cfg_lifetime)));  
1121     }else{
1122       return(TRUE);
1123     }
1124   }
1126   /* Returns true if snapshots are enabled, and false if it is disalbed
1127      There will also be some errors psoted, if the configuration failed */
1128   function snapshotEnabled()
1129   {
1130     if($this->get_cfg_value("core","enableSnapshots") == "true"){
1132       /* Check if the snapshot_base is defined */
1133       if ($this->get_cfg_value("core","snapshotBase") == ""){
1135         /* Send message if not done already */
1136         if(!session::is_set("snapshotFailMessageSend")){
1137           session::set("snapshotFailMessageSend",TRUE);
1138           msg_dialog::display(_("Configuration error"),
1139               sprintf(_("The snapshot functionality is enabled, but the required variable %s is not set."),
1140                       bold("snapshotBase")), ERROR_DIALOG);
1141         }
1142         return(FALSE);
1143       }
1145       /* Check if the snapshot_base is defined */
1146       if (!is_callable("gzcompress")){
1148         /* Send message if not done already */
1149         if(!session::is_set("snapshotFailMessageSend")){
1150           session::set("snapshotFailMessageSend",TRUE);
1151           msg_dialog::display(_("Configuration error"),
1152               sprintf(_("The snapshot functionality is enabled, but the required compression module is missing. Please install %s."), bold("php5-zip / php5-gzip")), ERROR_DIALOG);
1153         }
1154         return(FALSE);
1155       }
1157       /* check if there are special server configurations for snapshots */
1158       if ($this->get_cfg_value("core","snapshotURI") != ""){
1160         /* check if all required vars are available to create a new ldap connection */
1161         $missing = "";
1162         foreach(array("snapshotURI","snapshotAdminDn","snapshotAdminPassword","snapshotBase") as $var){
1163           if($this->get_cfg_value("core",$var) == ""){
1164             $missing .= $var." ";
1166             /* Send message if not done already */
1167             if(!session::is_set("snapshotFailMessageSend")){
1168               session::set("snapshotFailMessageSend",TRUE);
1169               msg_dialog::display(_("Configuration error"),
1170                   sprintf(_("The snapshot functionality is enabled, but the required variable %s is not set."),
1171                     bold($missing)), ERROR_DIALOG);
1172             }
1173             return(FALSE);
1174           }
1175                     }
1176             }
1177             return(TRUE);
1178     }
1179     return(FALSE);
1180   }
1184 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1185 ?>