Code

Updated curl 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     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($url="", $user="", $pwd="", $digest = FALSE )
318     {
319         // Create jsonRPC handle on demand.
320         if(!$this->jsonRPChandle || TRUE){
321             $this->jsonRPChandle = new jsonRPC($this, $url, $user, $pwd, $digest);
322         }
323         return($this->jsonRPChandle);
324     }
327     /*! \brief Get a LDAP link object
328      *
329      * This function can be used to get an ldap object, which in turn can
330      * be used to query the LDAP. See the LDAP class for more information
331      * on how to use it.
332      *
333      * Example usage:
334      * \code
335      * $ldap = $this->config->get_ldap_link();
336      * \endcode
337      *
338      * \param boolean sizelimit Weither to impose a sizelimit on the LDAP object or not.
339      * Defaults to false. If set to true, the size limit in the configuration
340      * file will be used to set the option LDAP_OPT_SIZELIMIT.
341      * \return ldapMultiplexer object
342      */
343     function get_ldap_link($sizelimit= FALSE)
344     {
345         if($this->ldap === NULL || !is_resource($this->ldap->cid)){
347             /* Build new connection */
348             $this->ldap= ldap_init ($this->current['SERVER'], $this->current['BASE'],
349                     $this->current['ADMINDN'], $this->get_credentials($this->current['ADMINPASSWORD']));
351             /* Check for connection */
352             if (is_null($this->ldap) || (is_int($this->ldap) && $this->ldap == 0)){
353                 $smarty= get_smarty();
354                 msg_dialog::display(_("LDAP error"), _("Cannot bind to LDAP!"), FATAL_ERROR_DIALOG);
355                 exit();
356             }
358             /* Move referrals */
359             if (!isset($this->current['REFERRAL'])){
360                 $this->ldap->referrals= array();
361             } else {
362                 $this->ldap->referrals= $this->current['REFERRAL'];
363             }
365             if (!session::global_is_set('size_limit')){
366                 session::global_set('size_limit', $this->get_cfg_value('core', 'ldapSizelimit'));
367                 session::global_set('size_ignore', $this->boolValueIsTrue('core', 'ldapSizeIgnore'));
368             }
369         }
371         $obj  = new ldapMultiplexer($this->ldap);
372         if ($sizelimit){
373             $obj->set_size_limit(session::global_get('size_limit'));
374         } else {
375             $obj->set_size_limit(0);
376         }
377         return($obj);
378     }
380     /*! \brief Set the current location
381      *  
382      *  \param string name the name of the location
383      */
384     function set_current($name)
385     {
386         $this->current= $this->data['LOCATIONS'][$name];
388         if (isset($this->current['INITIAL_BASE'])){
389             session::global_set('CurrentMainBase',$this->current['INITIAL_BASE']);
390         }
392         /* Sort referrals, if present */
393         if (isset ($this->current['REFERRAL'])){
394             $bases= array();
395             $servers= array();
396             foreach ($this->current['REFERRAL'] as $ref){
397                 $server= preg_replace('%^(.*://[^/]+)/.*$%', '\\1', $ref['URI']);
398                 $base= preg_replace('%^.*://[^/]+/(.*)$%', '\\1', $ref['URI']);
399                 $bases[$base]= strlen($base);
400                 $servers[$base]= $server;
401             }
402             asort($bases);
403             reset($bases);
404         }
406         /* SERVER not defined? Load the one with the shortest base */
407         if (!isset($this->current['SERVER'])){
408             $this->current['SERVER']= $servers[key($bases)];
409         }
411         /* BASE not defined? Load the one with the shortest base */
412         if (!isset($this->current['BASE'])){
413             $this->current['BASE']= key($bases);
414         }
416         /* Convert BASE to have escaped special characters */
417         $this->current['BASE']= @LDAP::convert($this->current['BASE']);
419         /* Parse LDAP referral informations */
420         if (!isset($this->current['ADMINDN']) || !isset($this->current['ADMINPASSWORD'])){
421             $url= $this->current['SERVER'];
422             $referral= $this->current['REFERRAL'][$url];
423             $this->current['ADMINDN']= $referral['ADMINDN'];
424             $this->current['ADMINPASSWORD']= $referral['ADMINPASSWORD'];
425         }
427         /* Load server informations */
428         $this->load_servers();
429     }
432     /*! \brief Load server information from config/LDAP
433      *
434      *  This function searches the LDAP for servers (e.g. goImapServer, goMailServer etc.)
435      *  and stores information about them $this->data['SERVERS']. In the case of mailservers
436      *  the main section of the configuration file is searched, too.
437      */
438     function load_servers ()
439     {
440         /* Only perform actions if current is set */
441         if ($this->current === NULL){
442             return;
443         }
445         /* Fill imap servers */
446         $ldap= $this->get_ldap_link();
447         $ldap->cd ($this->current['BASE']);
449         /* Search mailMethod konfiguration in main section too 
450          */
451         $tmp = $this->get_cfg_value("core","mailMethod");
452         if ($tmp){
453             $ldap->search ("(objectClass=goMailServer)", array('cn'));
454             $this->data['SERVERS']['IMAP']= array();
455             while ($attrs= $ldap->fetch()){
456                 $name= $attrs['cn'][0];
457                 $this->data['SERVERS']['IMAP'][$name]= 
458                     array( 
459                             "server_dn"   => $attrs['dn'],
460                             "connect"     => "",
461                             "admin"       => "",
462                             "password"    => "",
463                             "sieve_server"=> "",
464                             "sieve_option"=> "",
465                             "sieve_port"  => "");
466             }
467         } else {
468             $ldap->search ("(&(objectClass=goImapServer)(goImapSieveServer=*))", 
469                     array('goImapName', 'goImapConnect', 'goImapAdmin', 'goImapPassword',
470                         'goImapSieveServer', 'goImapSievePort'));
472             $this->data['SERVERS']['IMAP']= array();
474             while ($attrs= $ldap->fetch()){
476                 /* Check if the given goImapSieveServer is in the new style "{cn:port/option}"
477                    or the old style just "cn".
478                  */
479                 if(preg_match("/\{/",$attrs['goImapSieveServer'][0])){
480                     $sieve_server = preg_replace("/^\{([^:]*).*$/","\\1",$attrs['goImapSieveServer'][0]);
481                     $sieve_option = preg_replace("/^[^:]*[^\/]*+\/(.*)\}$/","\\1",$attrs['goImapSieveServer'][0]);
482                 }else{
483                     $sieve_server = $attrs['goImapSieveServer'][0];
484                     $sieve_option = "";
485                 }
487                 $pwd            = $attrs['goImapPassword'][0];
488                 $imap_admin     = $attrs['goImapAdmin'][0];
489                 $imap_connect   = $attrs['goImapConnect'][0];
490                 $imap_server    = $attrs['goImapName'][0];
491                 $sieve_port     = $attrs['goImapSievePort'][0];
493                 $this->data['SERVERS']['IMAP'][$imap_server]= 
494                     array( 
495                             "server_dn"   => $attrs['dn'],
496                             "connect"     => $imap_connect,
497                             "admin"       => $imap_admin,
498                             "password"    => $pwd,
499                             "sieve_server"=> $sieve_server,
500                             "sieve_option"=> $sieve_option,
501                             "sieve_port"  => $sieve_port);
502             }
503         }
505         /* Get kerberos server. FIXME: only one is supported currently */
506         $ldap->cd ($this->current['BASE']);
507         $ldap->search ("(&(goKrbRealm=*)(goKrbAdmin=*)(objectClass=goKrbServer))");
508         if ($ldap->count()){
509             $attrs= $ldap->fetch();
510             $this->data['SERVERS']['KERBEROS']= array( 'SERVER' => $attrs['cn'][0],
511                     'REALM' => $attrs['goKrbRealm'][0],
512                     'ADMIN' => $attrs['goKrbAdmin'][0]);
513         }
515         /* Get cups server. FIXME: only one is supported currently */
516         $ldap->cd ($this->current['BASE']);
517         $ldap->search ("(objectClass=goCupsServer)");
518         if ($ldap->count()){
519             $attrs= $ldap->fetch();
520             $this->data['SERVERS']['CUPS']= $attrs['cn'][0];    
521         }
523         /* Get fax server. FIXME: only one is supported currently */
524         $ldap->cd ($this->current['BASE']);
525         $ldap->search ("(objectClass=goFaxServer)");
526         if ($ldap->count()){
527             $attrs= $ldap->fetch();
528             $this->data['SERVERS']['FAX']= array( 'SERVER' => $attrs['cn'][0],
529                     'LOGIN' => $attrs['goFaxAdmin'][0],
530                     'PASSWORD' => $attrs['goFaxPassword'][0]);
531         }
534         /* Get asterisk servers */
535         $ldap->cd ($this->current['BASE']);
536         $ldap->search ("(objectClass=goFonServer)");
537         $this->data['SERVERS']['FON']= array();
538         if ($ldap->count()){
539             while ($attrs= $ldap->fetch()){
541                 /* Add 0 entry for development */
542                 if(count($this->data['SERVERS']['FON']) == 0){
543                     $this->data['SERVERS']['FON'][0]= array(
544                             'DN'      => $attrs['dn'],
545                             'SERVER'  => $attrs['cn'][0],
546                             'LOGIN'   => $attrs['goFonAdmin'][0],
547                             'PASSWORD'  => $attrs['goFonPassword'][0],
548                             'DB'    => "gophone",
549                             'SIP_TABLE'   => "sip_users",
550                             'EXT_TABLE'   => "extensions",
551                             'VOICE_TABLE' => "voicemail_users",
552                             'QUEUE_TABLE' => "queues",
553                             'QUEUE_MEMBER_TABLE'  => "queue_members");
554                 }
556                 /* Add entry with 'dn' as index */
557                 $this->data['SERVERS']['FON'][$attrs['dn']]= array(
558                         'DN'      => $attrs['dn'],
559                         'SERVER'  => $attrs['cn'][0],
560                         'LOGIN'   => $attrs['goFonAdmin'][0],
561                         'PASSWORD'  => $attrs['goFonPassword'][0],
562                         'DB'    => "gophone",
563                         'SIP_TABLE'   => "sip_users",
564                         'EXT_TABLE'   => "extensions",
565                         'VOICE_TABLE' => "voicemail_users",
566                         'QUEUE_TABLE' => "queues",
567                         'QUEUE_MEMBER_TABLE'  => "queue_members");
568             }
569         }
572         /* Get glpi server */
573         $ldap->cd ($this->current['BASE']);
574         $ldap->search ("(&(objectClass=goGlpiServer)(cn=*)(goGlpiAdmin=*)(goGlpiDatabase=*))",array("cn","goGlpiPassword","goGlpiAdmin","goGlpiDatabase"));
575         if ($ldap->count()){
576             $attrs= $ldap->fetch();
577             if(!isset($attrs['goGlpiPassword'])){
578                 $attrs['goGlpiPassword'][0] ="";
579             }
580             $this->data['SERVERS']['GLPI']= array( 
581                     'SERVER'    => $attrs['cn'][0],
582                     'LOGIN'     => $attrs['goGlpiAdmin'][0],
583                     'PASSWORD'  => $attrs['goGlpiPassword'][0],
584                     'DB'                => $attrs['goGlpiDatabase'][0]);
585         }
588         /* Get logdb server */
589         $ldap->cd ($this->current['BASE']);
590         $ldap->search ("(objectClass=goLogDBServer)");
591         if ($ldap->count()){
592             $attrs= $ldap->fetch();
593             if(!isset($attrs['gosaLogDB'][0])){
594                 $attrs['gosaLogDB'][0] = "gomon";
595             }
596             $this->data['SERVERS']['LOG']= array( 'SERVER' => $attrs['cn'][0],
597                     'LOGIN' => $attrs['goLogAdmin'][0],
598                     'DB' => $attrs['gosaLogDB'][0],
599                     'PASSWORD' => $attrs['goLogPassword'][0]);
600         }
603         /* GOsa logging databases */
604         $ldap->cd ($this->current['BASE']);
605         $ldap->search ("(objectClass=gosaLogServer)");
606         if ($ldap->count()){
607             while($attrs= $ldap->fetch()){
608                 $this->data['SERVERS']['LOGGING'][$attrs['cn'][0]]= 
609                     array(
610                             'DN'    => $attrs['dn'],
611                             'USER'  => $attrs['goLogDBUser'][0],
612                             'DB'    => $attrs['goLogDB'][0],
613                             'PWD'   => $attrs['goLogDBPassword'][0]);
614             }
615         }
618         /* Get NFS server lists */
619         $tmp= array("default");
620         $tmp2= array("default");
621         $ldap->cd ($this->current['BASE']);
622         $ldap->search ("(&(objectClass=goShareServer)(goExportEntry=*))");
623         while ($attrs= $ldap->fetch()){
624             for ($i= 0; $i<$attrs["goExportEntry"]["count"]; $i++){
625                 if(preg_match('/^[^|]+\|[^|]+\|NFS\|.*$/', $attrs["goExportEntry"][$i])){
626                     $path= preg_replace ("/^[^|]+\|[^|]+\|[^|]+\|[^|]+\|([^|]+).*$/", '\1', $attrs["goExportEntry"][$i]);
627                     $tmp[]= $attrs["cn"][0].":$path";
628                 }
629                 if(preg_match('/^[^|]+\|[^|]+\|NBD\|.*$/', $attrs["goExportEntry"][$i])){
630                     $path= preg_replace ("/^[^|]+\|[^|]+\|[^|]+\|[^|]+\|([^|]+).*$/", '\1', $attrs["goExportEntry"][$i]);
631                     $tmp2[]= $attrs["cn"][0].":$path";
632                 }
633             }
634         }
635         $this->data['SERVERS']['NFS']= $tmp;
636         $this->data['SERVERS']['NBD']= $tmp2;
638         /* Load Terminalservers */
639         $ldap->cd ($this->current['BASE']);
640         $ldap->search ("(objectClass=goTerminalServer)",array("cn","gotoSessionType"));
641         $this->data['SERVERS']['TERMINAL']= array();
642         $this->data['SERVERS']['TERMINAL'][]= "default";
643         $this->data['SERVERS']['TERMINAL_SESSION_TYPES'] = array();
646         while ($attrs= $ldap->fetch()){
647             $this->data['SERVERS']['TERMINAL'][]= $attrs["cn"][0];
648             if(isset( $attrs["gotoSessionType"]['count'])){
649                 for($i =0 ; $i < $attrs["gotoSessionType"]['count'] ; $i++){
650                     $this->data['SERVERS']['TERMINAL_SESSION_TYPES'][$attrs["cn"][0]][] = $attrs["gotoSessionType"][$i]; 
651                 }
652             }
653         }
655         /* Ldap Server 
656          */
657         $this->data['SERVERS']['LDAP']= array();
658         $ldap->cd ($this->current['BASE']);
659         $ldap->search ("(&(objectClass=goLdapServer)(goLdapBase=*))");
660         while ($attrs= $ldap->fetch()){
661             $this->data['SERVERS']['LDAP'][$attrs['dn']] = $attrs;
662         }
664         /* Get misc server lists */
665         $this->data['SERVERS']['SYSLOG']= array("default");
666         $this->data['SERVERS']['NTP']= array("default");
667         $ldap->cd ($this->current['BASE']);
668         $ldap->search ("(objectClass=goNtpServer)");
669         while ($attrs= $ldap->fetch()){
670             $this->data['SERVERS']['NTP'][]= $attrs["cn"][0];
671         }
672         $ldap->cd ($this->current['BASE']);
673         $ldap->search ("(objectClass=goSyslogServer)");
674         while ($attrs= $ldap->fetch()){
675             $this->data['SERVERS']['SYSLOG'][]= $attrs["cn"][0];
676         }
678         /* Get samba servers from LDAP, in case of samba3 */
679         $this->data['SERVERS']['SAMBA']= array();
680         $ldap->cd ($this->current['BASE']);
681         $ldap->search ("(objectClass=sambaDomain)");
682         while ($attrs= $ldap->fetch()){
683             $this->data['SERVERS']['SAMBA'][$attrs['sambaDomainName'][0]]= array( "SID" =>"","RIDBASE" =>"");
684             if(isset($attrs["sambaSID"][0])){
685                 $this->data['SERVERS']['SAMBA'][$attrs['sambaDomainName'][0]]["SID"]  = $attrs["sambaSID"][0];
686             }
687             if(isset($attrs["sambaAlgorithmicRidBase"][0])){
688                 $this->data['SERVERS']['SAMBA'][$attrs['sambaDomainName'][0]]["RIDBASE"] = $attrs["sambaAlgorithmicRidBase"][0];
689             }
690         }
692         /* If no samba servers are found, look for configured sid/ridbase */
693         if (count($this->data['SERVERS']['SAMBA']) == 0){
694             if (!isset($this->current["SAMBASID"]) || !isset($this->current["SAMBARIDBASE"])){
695                 msg_dialog::display(_("Configuration error"), _("sambaSID and/or sambaRidBase missing in the configuration!"), ERROR_DIALOG);
696             } else {
697                 $this->data['SERVERS']['SAMBA']['DEFAULT']= array(
698                         "SID" => $this->current["SAMBASID"],
699                         "RIDBASE" => $this->current["SAMBARIDBASE"]);
700             }
701         }
703     }
706     function get_departments($ignore_dn= "")
707     {
708         global $config;
710         /* Initialize result hash */
711         $result= array();
712         $administrative= array();
713         $result['/']= $this->current['BASE'];
714         $this->tdepartments= array();
716         /* Get all department types from department Management, to be able detect the department type.
717            -It is possible that differnty department types have the same name, 
718            in this case we have to mark the department name to be able to differentiate.
719            (e.g l=Name  or   o=Name)
720          */    
721         $types = departmentManagement::get_support_departments();
723         /* Create a list of attributes to fetch */
724         $ldap_values = array("objectClass","gosaUnitTag", "description");
725         $filter = "";
726         foreach($types as $type){
727             $ldap_values[] = $type['ATTR'];
728             $filter .= "(objectClass=".$type['OC'].")";
729         }
730         $filter = "(&(objectClass=gosaDepartment)(|".$filter."))";
732         /* Get list of department objects */
733         $ldap= $this->get_ldap_link();
734         $ldap->cd ($this->current['BASE']);
735         $ldap->search ($filter, $ldap_values);
736         while ($attrs= $ldap->fetch()){
738             /* Detect department type */
739             $type_data = array();
740             foreach($types as $t => $data){
741                 if(in_array($data['OC'],$attrs['objectClass'])){
742                     $type_data = $data;
743                     break;
744                 }
745             }
747             /* Unknown department type -> skip */
748             if(!count($type_data)) continue;
750             $dn= $ldap->getDN();
751             $this->tdepartments[$dn]= "";
752             $this->department_info[$dn]= array("img" => $type_data['IMG'],
753                     "description" => isset($attrs['description'][0])?$attrs['description'][0]:"",
754                     "name" => $attrs[$type_data['ATTR']][0]);
756             /* Save administrative departments */
757             if (in_array_ics("gosaAdministrativeUnit", $attrs['objectClass']) &&
758                     isset($attrs['gosaUnitTag'][0])){
759                 $administrative[$dn]= $attrs['gosaUnitTag'][0];
760                 $this->tdepartments[$dn]= $attrs['gosaUnitTag'][0];
761             }
763             if (in_array_ics("gosaAdministrativeUnitTag", $attrs['objectClass']) &&
764                     isset($attrs['gosaUnitTag'][0])){
765                 $this->tdepartments[$dn]= $attrs['gosaUnitTag'][0];
766             }
768             if ($dn == $ignore_dn){
769                 continue;
770             }
771             $c_dn = convert_department_dn($dn)." (".$type_data['ATTR'].")";
773             /* Only assign non-root departments */
774             if ($dn != $result['/']){
775                 $result[$c_dn]= $dn;
776             }
777         }
779         $this->adepartments= $administrative;
780         $this->departments= $result;
781     }
784     function make_idepartments($max_size= 28)
785     {
786         global $config;
787         $base = $config->current['BASE'];
788         $qbase = preg_quote($base, '/');
789         $utags= isset($config->current['HONOURUNITTAGS']) && preg_match('/true/i', $config->current['HONOURUNITTAGS']);
791         $arr = array();
792         $ui= get_userinfo();
794         $this->idepartments= array();
796         /* Create multidimensional array, with all departments. */
797         foreach ($this->departments as $key => $val){
799             /* When using strict_units, filter non relevant parts */
800             if ($utags){
801                 if ($ui->gosaUnitTag != '' && isset($this->tdepartments[$val]) &&
802                         $this->tdepartments[$val] != $ui->gosaUnitTag){
804 #TODO: link with strict*
805 #continue;
806                 }
807             }
809             /* Split dn into single department pieces */
810             $elements = array_reverse(explode(',',preg_replace("/$qbase$/",'',$val)));          
812             /* Add last ou element of current dn to our array */
813             $last = &$arr;
814             foreach($elements as $key => $ele){
816                 /* skip empty */
817                 if(empty($ele)) continue;
819                 /* Extract department name */           
820                 $elestr = trim(preg_replace('/^[^=]*+=/','', $ele),',');
821                 $nameA  = trim(preg_replace('/=.*$/','', $ele),',');
822                 if($nameA != 'ou'){
823                     $nameA = " ($nameA)";
824                 }else{
825                     $nameA = '';
826                 }
828                 /* Add to array */      
829                 if($key == (count($elements)-1)){
830                     $last[$elestr.$nameA]['ENTRY'] = $val;
831                 }
833                 /* Set next array appending position */
834                 $last = &$last[$elestr.$nameA]['SUB'];
835             }
836         }
839         /* Add base entry */
840         $ret['/']['ENTRY']      = $base;
841         $ret['/']['SUB']        = $arr;
842         $this->idepartments= $this->generateDepartmentArray($ret,-1,$max_size);
843     }
846     /* Creates display friendly output from make_idepartments */
847     function generateDepartmentArray($arr,$depth = -1,$max_size = 256)
848     {
849         $ret = array();
850         $depth ++;
852         /* Walk through array */        
853         ksort($arr);
854         foreach($arr as $name => $entries){
856             /* If this department is the last in the current tree position 
857              * remove it, to avoid generating output for it */
858             if(count($entries['SUB'])==0){
859                 unset($entries['SUB']);
860             }
862             /* Fix name, if it contains a replace tag */
863             $name= preg_replace('/\\\\,/', ',', LDAP::fix($name));
865             /* Check if current name is too long, then cut it */
866             if(mb_strlen($name, 'UTF-8')> $max_size){
867                 $name = mb_substr($name,0,($max_size-3), 'UTF-8')." ...";
868             }
870             /* Append the name to the list */   
871             if(isset($entries['ENTRY'])){
872                 $a = "";
873                 for($i = 0 ; $i < $depth ; $i ++){
874                     $a.=".";
875                 }
876                 $ret[$entries['ENTRY']]=$a."&nbsp;".$name;
877             }   
879             /* recursive add of subdepartments */
880             if(isset($entries['SUB'])){
881                 $ret = array_merge($ret,$this->generateDepartmentArray($entries['SUB'],$depth,$max_size));
882             }
883         }
885         return($ret);
886     }
888     /*! \brief Get all available shares defined in the current LDAP
889      *
890      *  This function returns all available Shares defined in this ldap
891      *  
892      *  \param boolean listboxEntry If set to TRUE, only name and path are
893      *  attached to the array. If FALSE, the whole entry will be parsed an atached to the result.
894      *  \return array
895      */
896     function getShareList($listboxEntry = false)
897     {
898         $tmp = get_sub_list("(&(objectClass=goShareServer)(goExportEntry=*))","server",get_ou("servgeneric", "serverRDN"),
899                 $this->current['BASE'],array("goExportEntry","cn"), GL_NONE);
900         $return =array();
901         foreach($tmp as $entry){
903             if(isset($entry['goExportEntry']['count'])){
904                 unset($entry['goExportEntry']['count']);
905             }
906             if(isset($entry['goExportEntry'])){
907                 foreach($entry['goExportEntry'] as $export){
908                     $shareAttrs = explode("|",$export);
909                     if($listboxEntry) {
910                         $return[$shareAttrs[0]."|".$entry['cn'][0]] = $shareAttrs[0]." - ".$entry['cn'][0];
911                     }else{
912                         $return[$shareAttrs[0]."|".$entry['cn'][0]]['server']       = $entry['cn'][0];
913                         $return[$shareAttrs[0]."|".$entry['cn'][0]]['name']         = $shareAttrs[0];
914                         $return[$shareAttrs[0]."|".$entry['cn'][0]]['description']  = $shareAttrs[1];
915                         $return[$shareAttrs[0]."|".$entry['cn'][0]]['type']         = $shareAttrs[2];
916                         $return[$shareAttrs[0]."|".$entry['cn'][0]]['charset']      = $shareAttrs[3];
917                         $return[$shareAttrs[0]."|".$entry['cn'][0]]['path']         = $shareAttrs[4];
918                         $return[$shareAttrs[0]."|".$entry['cn'][0]]['option']       = $shareAttrs[5];
919                     }
920                 }
921             }
922         }
923         return($return);
924     }
927     /*! \brief Return al available share servers
928      *
929      * This function returns all available ShareServers.
930      *
931      * \return array
932      * */
933     function getShareServerList()
934     {
935         global $config;
936         $return = array();
937         $ui = get_userinfo();
938         $base = $config->current['BASE'];
939         $res= get_sub_list("(&(objectClass=goShareServer)(goExportEntry=*))", "server",
940                 get_ou("servgeneric", "serverRDN"), $base,array("goExportEntry","cn"),GL_NONE | GL_NO_ACL_CHECK);
942         foreach($res as $entry){
944             $acl = $ui->get_permissions($entry['dn'],"server","");
945             if(isset($entry['goExportEntry']['count'])){
946                 unset($entry['goExportEntry']['count']);
947             }
948             foreach($entry['goExportEntry'] as $share){
949                 $a_share = explode("|",$share);
950                 $sharename = $a_share[0];
951                 $data= array();
952                 $data['NAME']   = $sharename;
953                 $data['ACL']    = $acl;
954                 $data['SERVER'] = $entry['cn']['0'];
955                 $data['SHARE']  = $sharename;
956                 $data['DISPLAY']= $entry['cn'][0]." [".$sharename."]";
957                 $return[$entry['cn'][0]."|".$sharename] = $data;
958             }
959         }
960         return($return);
961     }
964     /*! \brief Checks if there's a bool property set in the configuration.
965      *
966      *  The function checks, weither the specified bool value is set to a true
967      *  value in the configuration file. 
968      *
969      *  Example usage:
970      *  \code
971      *  if ($this->config->boolValueIsTrue("core", "copyPaste")) {
972      *    echo "Copy Paste Handling is enabled";
973      *  }
974      *  \endcode
975      *
976      *  \param string 'class' The properties class. e.g. 'core','user','sudo',...
977      *  \param string 'value' Key in the given section, which is subject to check
978      *
979      *
980      * */
981     function boolValueIsTrue($class, $name)
982     {
983         return(preg_match("/true/i", $this->get_cfg_value($class,$name)));
984     }
987     function __search(&$arr, $name, $return)
988     {
989         $return= strtoupper($return);
990         if (is_array($arr)){
991             foreach ($arr as &$a){
992                 if (isset($a['CLASS']) && strcasecmp($name, $a['CLASS']) == 0){
993                     return(isset($a[$return])?$a[$return]:"");
994                 } else {
995                     $res= $this->__search ($a, $name, $return);
996                     if ($res != ""){
997                         return $res;
998                     }
999                 }
1000             }
1001         }
1002         return ("");
1003     }
1006     /*! Outdated - try to use pluginEnabled, boolValueIsTrue or get_cfg_value instead. 
1007      *
1008      *  (Search for a configuration setting in different categories
1009      *
1010      *  Searches for the value of a given key in the configuration data.
1011      *  Optionally the list of categories to search (tabs, main, locations) can
1012      *  be specified. The first value that matches is returned.
1013      *
1014      *  Example usage:
1015      *  \code
1016      *  $postcmd = $this->config->search(get_class($this), "POSTCOMMAND", array("menu", "tabs"));
1017      *  \endcode
1018      *  ) 
1019      *
1020      * */
1021     function search($class, $value, $categories= "")
1022     {
1023         if (is_array($categories)){
1024             foreach ($categories as $category){
1025                 $res= $this->__search($this->data[strtoupper($category)], $class, $value);
1026                 if ($res != ""){
1027                     return $res;
1028                 }
1029             }
1030         } else {
1031             if ($categories == "") {
1032                 return $this->__search($this->data, $class, $value);
1033             } else {
1034                 return $this->__search($this->data[strtoupper($categories)], $class, $value);
1035             }
1036         } 
1038         return ("");
1039     }
1042     /*! \brief          Check whether a plugin is activated or not 
1043      */ 
1044     function pluginEnabled($class){
1045         $tmp = $this->search($class, "CLASS",array('menu','tabs'));
1046         return(!empty($tmp));
1047     }
1050     /*! \brief Get a configuration value from the config
1051      *
1052      *  This returns a configuration value from the config. It either
1053      *  uses the data of the current location ($this->current),
1054      *  if it contains the value (e.g. current['BASE']) or otherwise
1055      *  uses the data from the main configuration section.
1056      *
1057      *  If no value is found and an optional default has been specified,
1058      *  then the default is returned.
1059      *
1060      *  \param string 'name' the configuration key (case-insensitive)
1061      *  \param string 'default' a default that is returned, if no value is found
1062      *
1063      *
1064      */
1065     function get_cfg_value($class,$name, $default= NULL) 
1066     {
1067         // The default parameter is deprecated 
1068         if($default != NULL){
1069 #        trigger_error("Third parameter 'default' is deprecated for function 'get_cfg_value'!");
1070         }
1072         // Return the matching property value if it exists.
1073         if($this->configRegistry->propertyExists($class,$name)){
1074             return($this->configRegistry->getPropertyValue($class,$name));
1075         }
1077         // Show a warning in the syslog if there is an undefined property requested.
1078         if($this->configRegistry->propertyInitializationComplete() && 
1079                 "{$class}::{$name}" != 'core::config' &&  // <--- This on is never set, only in gosa.conf. 
1080                 "{$class}::{$name}" != 'core::logging'){  // <--- This one may cause endless recursions in class_log.inc
1081             new log("debug","","Unconfigured property: '{$class}::{$name}'",array(),'');
1082         }
1084         // Try to find the property in the config file directly.
1085         $name= strtoupper($name);
1086         if (isset($this->current[$name])) return ($this->current[$name]);
1087         if (isset($this->data["MAIN"][$name])) return ($this->data["MAIN"][$name]);
1088         return ("");
1089     }
1092     /*! \brief Check if current configuration version matches the GOsa version
1093      *
1094      *  This function checks if the configuration file version matches the
1095      *  version of the gosa version, by comparing it with the configuration
1096      *  file version of the example gosa.conf that comes with GOsa.
1097      *  If a version mismatch occurs an error is triggered.
1098      * */
1099     function check_config_version()
1100     {
1101         /* Skip check, if we've already mentioned the mismatch 
1102          */
1103         if(session::global_is_set("LastChecked") && session::global_get("LastChecked") == $this->config_version) return;
1105         /* Remember last checked version 
1106          */
1107         session::global_set("LastChecked",$this->config_version);
1109         $current = md5(file_get_contents(CONFIG_TEMPLATE_DIR."/gosa.conf"));
1111         /* Check contributed config version and current config version.
1112          */
1113         if(($this->config_version == "NOT SET") || ($this->config_version != $current && !empty($this->config_version))){
1114             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."));
1115         }
1116     }
1119     /*! \brief Check if session lifetime matches session.gc_maxlifetime 
1120      *
1121      *  On debian systems the session files are deleted with
1122      *  a cronjob, which detects all files older than specified 
1123      *  in php.ini:'session.gc_maxlifetime' and removes them.
1124      *  This function checks if the gosa.conf value matches the range
1125      *  defined by session.gc_maxlifetime.
1126      *
1127      *  \return boolean TRUE or FALSE depending on weither the settings match
1128      *  or not. If SESSIONLIFETIME is not configured in GOsa it always returns
1129      *  TRUE.
1130      */
1131     function check_session_lifetime()
1132     {
1133         if(isset($this->data['MAIN']['SESSIONLIFETIME'])){
1134             $cfg_lifetime = $this->data['MAIN']['SESSIONLIFETIME'];
1135             $ini_lifetime = ini_get('session.gc_maxlifetime');
1136             $deb_system   = file_exists('/etc/debian_version');
1137             return(!($deb_system && ($ini_lifetime < $cfg_lifetime)));  
1138         }else{
1139             return(TRUE);
1140         }
1141     }
1143     /* Returns true if snapshots are enabled, and false if it is disalbed
1144        There will also be some errors psoted, if the configuration failed */
1145     function snapshotEnabled()
1146     {
1147         if($this->get_cfg_value("core","enableSnapshots") == "true"){
1149             /* Check if the snapshot_base is defined */
1150             if ($this->get_cfg_value("core","snapshotBase") == ""){
1152                 /* Send message if not done already */
1153                 if(!session::is_set("snapshotFailMessageSend")){
1154                     session::set("snapshotFailMessageSend",TRUE);
1155                     msg_dialog::display(_("Configuration error"),
1156                             sprintf(_("The snapshot functionality is enabled, but the required variable %s is not set."),
1157                                 bold("snapshotBase")), ERROR_DIALOG);
1158                 }
1159                 return(FALSE);
1160             }
1162             /* Check if the snapshot_base is defined */
1163             if (!is_callable("gzcompress")){
1165                 /* Send message if not done already */
1166                 if(!session::is_set("snapshotFailMessageSend")){
1167                     session::set("snapshotFailMessageSend",TRUE);
1168                     msg_dialog::display(_("Configuration error"),
1169                             sprintf(_("The snapshot functionality is enabled, but the required compression module is missing. Please install %s."), bold("php5-zip / php5-gzip")), ERROR_DIALOG);
1170                 }
1171                 return(FALSE);
1172             }
1174             /* check if there are special server configurations for snapshots */
1175             if ($this->get_cfg_value("core","snapshotURI") != ""){
1177                 /* check if all required vars are available to create a new ldap connection */
1178                 $missing = "";
1179                 foreach(array("snapshotURI","snapshotAdminDn","snapshotAdminPassword","snapshotBase") as $var){
1180                     if($this->get_cfg_value("core",$var) == ""){
1181                         $missing .= $var." ";
1183                         /* Send message if not done already */
1184                         if(!session::is_set("snapshotFailMessageSend")){
1185                             session::set("snapshotFailMessageSend",TRUE);
1186                             msg_dialog::display(_("Configuration error"),
1187                                     sprintf(_("The snapshot functionality is enabled, but the required variable %s is not set."),
1188                                         bold($missing)), ERROR_DIALOG);
1189                         }
1190                         return(FALSE);
1191                     }
1192                 }
1193             }
1194             return(TRUE);
1195         }
1196         return(FALSE);
1197     }
1201 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1202 ?>