Code

Added timeout to GOsa::log mysql connections.
[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 class config  {
25   /* XML parser */
26   var $parser;
27   var $config_found= FALSE;
28   var $tags= array();
29   var $level= 0;
30   var $gpc= 0;
31   var $section= "";
32   var $currentLocation= "";
34   /* Selected connection */
35   var $current= array();
37   /* Link to LDAP-server */
38   var $ldap= NULL;
39   var $referrals= array();
41   /* Configuration data */
42   var $data= array( 'TABS' => array(), 'LOCATIONS' => array(), 'SERVERS' => array(),
43       'MAIN' => array(),
44       'MENU' => array(), 'SERVICE' => array());
45   var $basedir= "";
46   var $config_version ="NOT SET";
48   /* Keep a copy of the current deparment list */
49   var $departments= array();
50   var $idepartments= array();
51   var $adepartments= array();
52   var $tdepartments= array();
53   var $filename = "";
54   var $last_modified = 0;
56   function config($filename, $basedir= "")
57   {
58     $this->parser = xml_parser_create();
59     $this->basedir= $basedir;
61     xml_set_object($this->parser, $this);
62     xml_set_element_handler($this->parser, "tag_open", "tag_close");
64     /* Parse config file directly? */
65     if ($filename != ""){
66       $this->parse($filename);
67     }
68   }
70   
71   function check_and_reload()
72   {
73     global $ui;
75     /* Check if class_location.inc has changed, this is the case 
76         if we have installed or removed plugins. 
77      */
78     if(session::global_is_set("class_location.inc:timestamp")){
79       $tmp = stat("../include/class_location.inc");
80       if($tmp['mtime'] != session::global_get("class_location.inc:timestamp")){
81         session::global_un_set("plist");
82       }
83     }
84     $tmp = stat("../include/class_location.inc");
85     session::global_set("class_location.inc:timestamp",$tmp['mtime']);
87     if($this->filename != "" && filemtime($this->filename) != $this->last_modified){
89       $this->config_found= FALSE;
90       $this->tags= array();
91       $this->level= 0;
92       $this->gpc= 0;
93       $this->section= "";
94       $this->currentLocation= "";
96       $this->parser = xml_parser_create();
97       xml_set_object($this->parser, $this);
98       xml_set_element_handler($this->parser, "tag_open", "tag_close");
99       $this->parse($this->filename);
100       $this->set_current($this->current['NAME']);
101     }
102   }  
105   function parse($filename)
106   {
108     $this->data = array(
109         "TABS"      => array(), 
110         "LOCATIONS" => array(), 
111         "MAIN"      => array(), 
112         "MENU"      => array(), 
113         "SERVICE"   => array());
115     $this->last_modified = filemtime($filename);
116     $this->filename = $filename;
117     $fh= fopen($filename, "r"); 
118     $xmldata= fread($fh, 100000);
119     fclose($fh);
120     if(!xml_parse($this->parser, chop($xmldata))){
121       $msg = sprintf(_("XML error in gosa.conf: %s at line %d"),
122             xml_error_string(xml_get_error_code($this->parser)),
123             xml_get_current_line_number($this->parser));
124       msg_dialog::display(_("Configuration error"), $msg, FATAL_ERROR_DIALOG);
125       exit;
126     }
127   }
129   function tag_open($parser, $tag, $attrs)
130   {
131     /* Save last and current tag for reference */
132     $this->tags[$this->level]= $tag;
133     $this->level++;
135     /* Trigger on CONF section */
136     if ($tag == 'CONF'){
137       $this->config_found= TRUE;
138       if(isset($attrs['CONFIGVERSION'])){
139         $this->config_version = $attrs['CONFIGVERSION'];
140       }
141     }
143     /* Return if we're not in config section */
144     if (!$this->config_found){
145       return;
146     }
148     /* yes/no to true/false and upper case TRUE to true and so on*/
149     foreach($attrs as $name => $value){
150       if(preg_match("/^(true|yes)$/i",$value)){
151         $attrs[$name] = "true";
152       }elseif(preg_match("/^(false|no)$/i",$value)){
153         $attrs[$name] = "false";
154       } 
155     }
157     /* Look through attributes */
158     switch ($this->tags[$this->level-1]){
161       /* Handle tab section */
162       case 'TAB':       $name= $this->tags[$this->level-2];
164                   /* Create new array? */
165                   if (!isset($this->data['TABS'][$name])){
166                     $this->data['TABS'][$name]= array();
167                   }
169                   /* Add elements */
170                   $this->data['TABS'][$name][]= $attrs;
171                   break;
173                   /* Handle location */
174       case 'LOCATION':
175                   if ($this->tags[$this->level-2] == 'MAIN'){
176                     $name= $attrs['NAME'];
177                     $name = preg_replace("/[<>\"']/","",$name);
178                     $attrs['NAME'] = $name;
179                     $this->currentLocation= $name;
181                     /* Add location elements */
182                     $this->data['LOCATIONS'][$name]= $attrs;
183                   }
184                   break;
186                   /* Handle referral tags */
187       case 'REFERRAL':
188                   if ($this->tags[$this->level-2] == 'LOCATION'){
189                     $url= $attrs['URI'];
190                     $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
192                     /* Add location elements */
193                     if (!isset($this->data['LOCATIONS'][$this->currentLocation]['REFERRAL'])){
194                       $this->data['LOCATIONS'][$this->currentLocation]['REFERRAL']= array();
195                     }
197                     $this->data['LOCATIONS'][$this->currentLocation]['REFERRAL'][$server]= $attrs;
198                   }
199                   break;
201                   /* Load main parameters */
202       case 'MAIN':
203                   $this->data['MAIN']= array_merge ($this->data['MAIN'], $attrs);
204                   break;
206                   /* Load menu */
207       case 'SECTION':
208                   if ($this->tags[$this->level-2] == 'MENU'){
209                     $this->section= $attrs['NAME'];
210                     $this->data['MENU'][$this->section]= array(); ;
211                   }
212                   break;
214                   /* Inser plugins */
215       case 'PLUGIN':
216                   if ($this->tags[$this->level-3] == 'MENU' &&
217                       $this->tags[$this->level-2] == 'SECTION'){
219                     $this->data['MENU'][$this->section][$this->gpc++]= $attrs;
220                   }
221                   if ($this->tags[$this->level-2] == 'SERVICEMENU'){
222                     $this->data['SERVICE'][$attrs['CLASS']]= $attrs;
223                   }
224                   break;
225     }
226   }
228   function tag_close($parser, $tag)
229   {
230     /* Close config section */
231     if ($tag == 'CONF'){
232       $this->config_found= FALSE;
233     }
234     $this->level--;
235   }
238   function get_credentials($creds)
239   {
240     if (isset($_SERVER['HTTP_GOSA_KEY'])){
241       if (!session::global_is_set('HTTP_GOSA_KEY_CACHE')){
242         session::global_set('HTTP_GOSA_KEY_CACHE',array());
243       }
244       $cache = session::global_get('HTTP_GOSA_KEY_CACHE');
245       if(!isset($cache[$creds])){
246         $cache[$creds] = cred_decrypt($creds, $_SERVER['HTTP_GOSA_KEY']);
247         session::global_set('HTTP_GOSA_KEY_CACHE',$cache);
248       }
249       return ($cache[$creds]);
250     }
251     return ($creds);
252   }
255   function get_ldap_link($sizelimit= FALSE)
256   {
257     if($this->ldap === NULL || !is_resource($this->ldap->cid)){
259       /* Build new connection */
260       $this->ldap= ldap_init ($this->current['SERVER'], $this->current['BASE'],
261           $this->current['ADMINDN'], $this->get_credentials($this->current['ADMINPASSWORD']));
263       /* Check for connection */
264       if (is_null($this->ldap) || (is_int($this->ldap) && $this->ldap == 0)){
265         $smarty= get_smarty();
266         msg_dialog::display(_("LDAP error"), _("Cannot bind to LDAP. Please contact the system administrator."), FATAL_ERROR_DIALOG);
267         exit();
268       }
270       /* Move referrals */
271       if (!isset($this->current['REFERRAL'])){
272         $this->ldap->referrals= array();
273       } else {
274         $this->ldap->referrals= $this->current['REFERRAL'];
275       }
277       if (!session::global_is_set('size_limit')){
278         session::global_set('size_limit',$this->current['LDAPSIZELIMIT']);
279         session::global_set('size_ignore',$this->current['LDAPSIZEIGNORE']);
280       }
281     }
283     $obj  = new ldapMultiplexer($this->ldap);
284     if ($sizelimit){
285       $obj->set_size_limit(session::global_get('size_limit'));
286     } else {
287       $obj->set_size_limit(0);
288     }
289     return($obj);
290   }
292   function set_current($name)
293   {
294     $this->current= $this->data['LOCATIONS'][$name];
296     if (!isset($this->current['SAMBAVERSION'])){
297       $this->current['SAMBAVERSION']= 3;
298     }
299     if (!isset($this->current['USERRDN'])){
300       $this->current['USERRDN']= "ou=people";
301     }
302     if (!isset($this->current['GROUPRDN'])){
303       $this->current['GROUPS']= "ou=groups";
304     }
306     if (isset($this->current['INITIAL_BASE'])){
307       session::global_set('CurrentMainBase',$this->current['INITIAL_BASE']);
308     }
309   
310     /* Remove possibly added ',' from end of group and people ou */
311     $this->current['GROUPS'] = preg_replace("/,*$/","",$this->current['GROUPRDN']);
312     $this->current['USERRDN'] = preg_replace("/,*$/","",$this->current['USERRDN']);
314     if (!isset($this->current['SAMBAMACHINEACCOUNTRDN'])){
315       $this->current['SAMBAMACHINEACCOUNTRDN']= "ou=winstations,ou=systems";
316     }
317     if (!isset($this->current['ACCOUNTPRIMARYATTRIBUTE'])){
318       $this->current['ACCOUNTPRIMARYATTRIBUTE']= "cn";
319     }
320     if (!isset($this->current['MINID'])){
321       $this->current['MINID']= 100;
322     }
323     if (!isset($this->current['LDAPSIZELIMIT'])){
324       $this->current['LDAPSIZELIMIT']= 200;
325     }
326     if (!isset($this->current['SIZEINGORE'])){
327       $this->current['LDAPSIZEIGNORE']= TRUE;
328     } else {
329       if (preg_match("/true/i", $this->current['LDAPSIZEIGNORE'])){
330         $this->current['LDAPSIZEIGNORE']= TRUE;
331       } else {
332         $this->current['LDAPSIZEIGNORE']= FALSE;
333       }
334     }
336     /* Sort referrals, if present */
337     if (isset ($this->current['REFERRAL'])){
338       $bases= array();
339       $servers= array();
340       foreach ($this->current['REFERRAL'] as $ref){
341         $server= preg_replace('%^(.*)/[^/]+$%', '\\1', $ref['URI']);
342         $base= preg_replace('%^.*/([^/]+)$%', '\\1', $ref['URI']);
343         $bases[$base]= strlen($base);
344         $servers[$base]= $server;
345       }
346       asort($bases);
347       reset($bases);
348     }
350     /* SERVER not defined? Load the one with the shortest base */
351     if (!isset($this->current['SERVER'])){
352       $this->current['SERVER']= $servers[key($bases)];
353     }
355     /* BASE not defined? Load the one with the shortest base */
356     if (!isset($this->current['BASE'])){
357       $this->current['BASE']= key($bases);
358     }
360     /* Convert BASE to have escaped special characters */
361     $this->current['BASE']= @LDAP::convert($this->current['BASE']);
363     /* Parse LDAP referral informations */
364     if (!isset($this->current['ADMINDN']) || !isset($this->current['ADMINPASSWORD'])){
365       $url= $this->current['SERVER'];
366       $referral= $this->current['REFERRAL'][$url];
367       $this->current['ADMINDN']= $referral['ADMINDN'];
368       $this->current['ADMINPASSWORD']= $referral['ADMINPASSWORD'];
369     }
371     /* Load server informations */
372     $this->load_servers();
373   }
375   function load_servers ()
376   {
377     /* Only perform actions if current is set */
378     if ($this->current === NULL){
379       return;
380     }
382     /* Fill imap servers */
383     $ldap= $this->get_ldap_link();
384     $ldap->cd ($this->current['BASE']);
386     /* Search mailMethod konfiguration in main section too 
387      */
388     $this->current['MAILMETHOD'] = $this->get_cfg_value("mailMethod","");
389     if (!isset($this->current['MAILMETHOD'])){
390       $this->current['MAILMETHOD']= "";
391     }
392     if ($this->current['MAILMETHOD'] == ""){
393       $ldap->search ("(objectClass=goMailServer)", array('cn'));
394       $this->data['SERVERS']['IMAP']= array();
395       while ($attrs= $ldap->fetch()){
396         $name= $attrs['cn'][0];
397         $this->data['SERVERS']['IMAP'][$name]= 
398           array( 
399               "server_dn"   => $attrs['dn'],
400               "connect"     => "",
401               "admin"       => "",
402               "password"    => "",
403               "sieve_server"=> "",
404               "sieve_option"=> "",
405               "sieve_port"  => "");
406       }
407     } else {
408       $ldap->search ("(&(objectClass=goImapServer)(goImapSieveServer=*))", 
409                     array('goImapName', 'goImapConnect', 'goImapAdmin', 'goImapPassword',
410             'goImapSieveServer', 'goImapSievePort'));
412       $this->data['SERVERS']['IMAP']= array();
414       while ($attrs= $ldap->fetch()){
416         /* Check if the given goImapSieveServer is in the new style "{cn:port/option}"
417            or the old style just "cn".
418          */
419         if(preg_match("/\{/",$attrs['goImapSieveServer'][0])){
420           $sieve_server = preg_replace("/^\{([^:]*).*$/","\\1",$attrs['goImapSieveServer'][0]);
421           $sieve_option = preg_replace("/^[^:]*[^\/]*+\/(.*)\}$/","\\1",$attrs['goImapSieveServer'][0]);
422         }else{
423           $sieve_server = $attrs['goImapSieveServer'][0];
424           $sieve_option = "";
425         }
427         $pwd            = $attrs['goImapPassword'][0];
428         $imap_admin     = $attrs['goImapAdmin'][0];
429         $imap_connect   = $attrs['goImapConnect'][0];
430         $imap_server    = $attrs['goImapName'][0];
431         $sieve_port     = $attrs['goImapSievePort'][0];
432         
433         $this->data['SERVERS']['IMAP'][$imap_server]= 
434             array( 
435             "server_dn"   => $attrs['dn'],
436             "connect"     => $imap_connect,
437             "admin"       => $imap_admin,
438             "password"    => $pwd,
439             "sieve_server"=> $sieve_server,
440             "sieve_option"=> $sieve_option,
441             "sieve_port"  => $sieve_port);
442       }
443     }
445     /* Get kerberos server. FIXME: only one is supported currently */
446     $ldap->cd ($this->current['BASE']);
447     $ldap->search ("(&(goKrbRealm=*)(goKrbAdmin=*)(objectClass=goKrbServer))");
448     if ($ldap->count()){
449       $attrs= $ldap->fetch();
450       $this->data['SERVERS']['KERBEROS']= array( 'SERVER' => $attrs['cn'][0],
451           'REALM' => $attrs['goKrbRealm'][0],
452           'ADMIN' => $attrs['goKrbAdmin'][0]);
453     }
455     /* Get cups server. FIXME: only one is supported currently */
456     $ldap->cd ($this->current['BASE']);
457     $ldap->search ("(objectClass=goCupsServer)");
458     if ($ldap->count()){
459       $attrs= $ldap->fetch();
460       $this->data['SERVERS']['CUPS']= $attrs['cn'][0];  
461     }
463     /* Get fax server. FIXME: only one is supported currently */
464     $ldap->cd ($this->current['BASE']);
465     $ldap->search ("(objectClass=goFaxServer)");
466     if ($ldap->count()){
467       $attrs= $ldap->fetch();
468       $this->data['SERVERS']['FAX']= array( 'SERVER' => $attrs['cn'][0],
469           'LOGIN' => $attrs['goFaxAdmin'][0],
470           'PASSWORD' => $attrs['goFaxPassword'][0]);
471     }
474     /* Get asterisk servers */
475     $ldap->cd ($this->current['BASE']);
476     $ldap->search ("(objectClass=goFonServer)");
477     $this->data['SERVERS']['FON']= array();
478     if ($ldap->count()){
479       while ($attrs= $ldap->fetch()){
481         /* Add 0 entry for development */
482         if(count($this->data['SERVERS']['FON']) == 0){
483           $this->data['SERVERS']['FON'][0]= array(
484               'DN'      => $attrs['dn'],
485               'SERVER'  => $attrs['cn'][0],
486               'LOGIN'   => $attrs['goFonAdmin'][0],
487               'PASSWORD'  => $attrs['goFonPassword'][0],
488               'DB'    => "gophone",
489               'SIP_TABLE'   => "sip_users",
490               'EXT_TABLE'   => "extensions",
491               'VOICE_TABLE' => "voicemail_users",
492               'QUEUE_TABLE' => "queues",
493               'QUEUE_MEMBER_TABLE'  => "queue_members");
494         }
496         /* Add entry with 'dn' as index */
497         $this->data['SERVERS']['FON'][$attrs['dn']]= array(
498             'DN'      => $attrs['dn'],
499             'SERVER'  => $attrs['cn'][0],
500             'LOGIN'   => $attrs['goFonAdmin'][0],
501             'PASSWORD'  => $attrs['goFonPassword'][0],
502             'DB'    => "gophone",
503             'SIP_TABLE'   => "sip_users",
504             'EXT_TABLE'   => "extensions",
505             'VOICE_TABLE' => "voicemail_users",
506             'QUEUE_TABLE' => "queues",
507             'QUEUE_MEMBER_TABLE'  => "queue_members");
508       }
509     }
512     /* Get glpi server */
513     $ldap->cd ($this->current['BASE']);
514     $ldap->search ("(&(objectClass=goGlpiServer)(cn=*)(goGlpiAdmin=*)(goGlpiDatabase=*))",array("cn","goGlpiPassword","goGlpiAdmin","goGlpiDatabase"));
515     if ($ldap->count()){
516       $attrs= $ldap->fetch();
517       if(!isset($attrs['goGlpiPassword'])){
518         $attrs['goGlpiPassword'][0] ="";
519       }
520       $this->data['SERVERS']['GLPI']= array( 
521           'SERVER'      => $attrs['cn'][0],
522           'LOGIN'       => $attrs['goGlpiAdmin'][0],
523           'PASSWORD'    => $attrs['goGlpiPassword'][0],
524           'DB'          => $attrs['goGlpiDatabase'][0]);
525     }
528     /* Get logdb server */
529     $ldap->cd ($this->current['BASE']);
530     $ldap->search ("(objectClass=goLogDBServer)");
531     if ($ldap->count()){
532       $attrs= $ldap->fetch();
533       if(!isset($attrs['gosaLogDB'][0])){
534         $attrs['gosaLogDB'][0] = "gomon";
535       }
536       $this->data['SERVERS']['LOG']= array( 'SERVER' => $attrs['cn'][0],
537           'LOGIN' => $attrs['goLogAdmin'][0],
538           'DB' => $attrs['gosaLogDB'][0],
539           'PASSWORD' => $attrs['goLogPassword'][0]);
540     }
543     /* GOsa logging databases */
544     $ldap->cd ($this->current['BASE']);
545     $ldap->search ("(objectClass=gosaLogServer)");
546     if ($ldap->count()){
547       while($attrs= $ldap->fetch()){
548       $this->data['SERVERS']['LOGGING'][$attrs['cn'][0]]= 
549           array(
550           'DN'    => $attrs['dn'],
551           'USER'  => $attrs['goLogDBUser'][0],
552           'DB'    => $attrs['goLogDB'][0],
553           'PWD'   => $attrs['goLogDBPassword'][0]);
554       }
555     }
558     /* Get NFS server lists */
559     $tmp= array("default");
560     $tmp2= array("default");
561     $ldap->cd ($this->current['BASE']);
562     $ldap->search ("(&(objectClass=goShareServer)(goExportEntry=*))");
563     while ($attrs= $ldap->fetch()){
564       for ($i= 0; $i<$attrs["goExportEntry"]["count"]; $i++){
565         if(preg_match('/^[^|]+\|[^|]+\|NFS\|.*$/', $attrs["goExportEntry"][$i])){
566           $path= preg_replace ("/^[^|]+\|[^|]+\|[^|]+\|[^|]+\|([^|]+).*$/", '\1', $attrs["goExportEntry"][$i]);
567           $tmp[]= $attrs["cn"][0].":$path";
568         }
569         if(preg_match('/^[^|]+\|[^|]+\|NBD\|.*$/', $attrs["goExportEntry"][$i])){
570           $path= preg_replace ("/^[^|]+\|[^|]+\|[^|]+\|[^|]+\|([^|]+).*$/", '\1', $attrs["goExportEntry"][$i]);
571           $tmp2[]= $attrs["cn"][0].":$path";
572         }
573       }
574     }
575     $this->data['SERVERS']['NFS']= $tmp;
576     $this->data['SERVERS']['NBD']= $tmp2;
578     /* Load Terminalservers */
579     $ldap->cd ($this->current['BASE']);
580     $ldap->search ("(objectClass=goTerminalServer)",array("cn","gotoSessionType"));
581     $this->data['SERVERS']['TERMINAL']= array();
582     $this->data['SERVERS']['TERMINAL'][]= "default";
583     $this->data['SERVERS']['TERMINAL_SESSION_TYPES'] = array();
586     while ($attrs= $ldap->fetch()){
587       $this->data['SERVERS']['TERMINAL'][]= $attrs["cn"][0];
588       if(isset( $attrs["gotoSessionType"]['count'])){
589         for($i =0 ; $i < $attrs["gotoSessionType"]['count'] ; $i++){
590           $this->data['SERVERS']['TERMINAL_SESSION_TYPES'][$attrs["cn"][0]][] = $attrs["gotoSessionType"][$i]; 
591         }
592       }
593     }
595     /* Ldap Server 
596      */
597     $this->data['SERVERS']['LDAP']= array();
598     $ldap->cd ($this->current['BASE']);
599     $ldap->search ("(&(objectClass=goLdapServer)(goLdapBase=*))");
600     while ($attrs= $ldap->fetch()){
601       $this->data['SERVERS']['LDAP'][$attrs['dn']] = $attrs;
602     }
604     /* Get misc server lists */
605     $this->data['SERVERS']['SYSLOG']= array("default");
606     $this->data['SERVERS']['NTP']= array("default");
607     $ldap->cd ($this->current['BASE']);
608     $ldap->search ("(objectClass=goNtpServer)");
609     while ($attrs= $ldap->fetch()){
610       $this->data['SERVERS']['NTP'][]= $attrs["cn"][0];
611     }
612     $ldap->cd ($this->current['BASE']);
613     $ldap->search ("(objectClass=goSyslogServer)");
614     while ($attrs= $ldap->fetch()){
615       $this->data['SERVERS']['SYSLOG'][]= $attrs["cn"][0];
616     }
618     /* Get samba servers from LDAP, in case of samba3 */
619     if ($this->current['SAMBAVERSION'] == 3){
620       $this->data['SERVERS']['SAMBA']= array();
621       $ldap->cd ($this->current['BASE']);
622       $ldap->search ("(objectClass=sambaDomain)");
623       while ($attrs= $ldap->fetch()){
624         $this->data['SERVERS']['SAMBA'][$attrs['sambaDomainName'][0]]= array( "SID" =>"","RIDBASE" =>"");
625         if(isset($attrs["sambaSID"][0])){
626           $this->data['SERVERS']['SAMBA'][$attrs['sambaDomainName'][0]]["SID"]  = $attrs["sambaSID"][0];
627         }
628         if(isset($attrs["sambaAlgorithmicRidBase"][0])){
629           $this->data['SERVERS']['SAMBA'][$attrs['sambaDomainName'][0]]["RIDBASE"] = $attrs["sambaAlgorithmicRidBase"][0];
630         }
631       }
633       /* If no samba servers are found, look for configured sid/ridbase */
634       if (count($this->data['SERVERS']['SAMBA']) == 0){
635         if (!isset($this->current["SAMBASID"]) || !isset($this->current["SAMBARIDBASE"])){
636           msg_dialog::display(_("Configuration error"), _("sambaSID and/or sambaRidBase missing in the configuration!"), ERROR_DIALOG);
637         } else {
638           $this->data['SERVERS']['SAMBA']['DEFAULT']= array(
639               "SID" => $this->current["SAMBASID"],
640               "RIDBASE" => $this->current["SAMBARIDBASE"]);
641         }
642       }
643     }
644   }
647   function get_departments($ignore_dn= "")
648   {
649     global $config;
651     /* Initialize result hash */
652     $result= array();
653     $administrative= array();
654     $result['/']= $this->current['BASE'];
655     $this->tdepartments= array();
657     /* Get all department types from department Management, to be able detect the department type.
658         -It is possible that differnty department types have the same name, 
659          in this case we have to mark the department name to be able to differentiate.
660           (e.g l=Name  or   o=Name)
661      */    
662     $types = departmentManagement::get_support_departments();
663     
664     /* Create a list of attributes to fetch */
665     $ldap_values = array("objectClass","gosaUnitTag");
666     $filter = "";
667     foreach($types as $type){
668       $ldap_values[] = $type['ATTR'];
669       $filter .= "(objectClass=".$type['OC'].")";
670     }
671     $filter = "(&(objectClass=gosaDepartment)(|".$filter."))";
673     /* Get list of department objects */
674     $ldap= $this->get_ldap_link();
675     $ldap->cd ($this->current['BASE']);
676     $ldap->search ($filter, $ldap_values);
677     while ($attrs= $ldap->fetch()){
679       /* Detect department type */
680       $type_data = array();
681       foreach($types as $t => $data){
682         if(in_array($data['OC'],$attrs['objectClass'])){
683           $type_data = $data;
684           break;    
685         }
686       }
688       /* Unknown department type -> skip 
689        */
690       if(!count($type_data)) continue;
692       $dn= $ldap->getDN();
693       $this->tdepartments[$dn]= "";
695       /* Save administrative departments */
696       if (in_array_ics("gosaAdministrativeUnit", $attrs['objectClass']) &&
697           isset($attrs['gosaUnitTag'][0])){
698         $administrative[$dn]= $attrs['gosaUnitTag'][0];
699         $this->tdepartments[$dn]= $attrs['gosaUnitTag'][0];
700       }
701     
702       if (in_array_ics("gosaAdministrativeUnitTag", $attrs['objectClass']) &&
703           isset($attrs['gosaUnitTag'][0])){
704         $this->tdepartments[$dn]= $attrs['gosaUnitTag'][0];
705       }
706     
707       if ($dn == $ignore_dn){
708         continue;
709       }
711       $c_dn = convert_department_dn($dn)." (".$type_data['ATTR'].")";
713       /* Only assign non-root departments */
714       if ($dn != $result['/']){
715         $result[$c_dn]= $dn;
716       }
717     }
719     $this->adepartments= $administrative;
720     $this->departments= $result;
721   }
724   function make_idepartments($max_size= 28)
725   {
726     global $config;
727     $base = $config->current['BASE'];
728                 $qbase = preg_quote($base, '/');
729     $utags= isset($config->current['HONOURUNITTAGS']) && preg_match('/true/i', $config->current['HONOURUNITTAGS']);
731     $arr = array();
732     $ui= get_userinfo();
734     $this->idepartments= array();
736     /* Create multidimensional array, with all departments. */
737     foreach ($this->departments as $key => $val){
739       /* When using strict_units, filter non relevant parts */
740       if ($utags){
741         if ($ui->gosaUnitTag != '' && isset($this->tdepartments[$val]) &&
742             $this->tdepartments[$val] != $ui->gosaUnitTag){
744                                                 #TODO: link with strict*
745                                                 #continue;
746         }
747       }
749       /* Split dn into single department pieces */
750       $elements = array_reverse(split(',',preg_replace("/$qbase$/",'',$val)));          
752       /* Add last ou element of current dn to our array */
753       $last = &$arr;
754       foreach($elements as $key => $ele){
756         /* skip empty */
757         if(empty($ele)) continue;
759         /* Extract department name */           
760         $elestr = trim(preg_replace('/^[^=]*+=/','', $ele),',');
761         $nameA  = trim(preg_replace('/=.*$/','', $ele),',');
762         if($nameA != 'ou'){
763           $nameA = " ($nameA)";
764         }else{
765           $nameA = '';
766         }
767     
768         /* Add to array */      
769         if($key == (count($elements)-1)){
770           $last[$elestr.$nameA]['ENTRY'] = $val;
771         }
773         /* Set next array appending position */
774         $last = &$last[$elestr.$nameA]['SUB'];
775       }
776     }
779     /* Add base entry */
780     $ret['/']['ENTRY']  = $base;
781     $ret['/']['SUB']    = $arr;
782     $this->idepartments= $this->generateDepartmentArray($ret,-1,$max_size);
783   }
786   /* Creates display friendly output from make_idepartments */
787   function generateDepartmentArray($arr,$depth = -1,$max_size = 256)
788   {
789     $ret = array();
790     $depth ++;
792     /* Walk through array */    
793     ksort($arr);
794     foreach($arr as $name => $entries){
796       /* If this department is the last in the current tree position 
797        * remove it, to avoid generating output for it */
798       if(count($entries['SUB'])==0){
799         unset($entries['SUB']);
800       }
802       /* Fix name, if it contains a replace tag */
803       $name= preg_replace('/\\\\,/', ',', LDAP::fix($name));
805       /* Check if current name is too long, then cut it */
806       if(mb_strlen($name, 'UTF-8')> $max_size){
807         $name = mb_substr($name,0,($max_size-3), 'UTF-8')." ...";
808       }
810       /* Append the name to the list */ 
811       if(isset($entries['ENTRY'])){
812         $a = "";
813         for($i = 0 ; $i < $depth ; $i ++){
814           $a.=".";
815         }
816         $ret[$entries['ENTRY']]=$a."&nbsp;".$name;
817       } 
819       /* recursive add of subdepartments */
820       if(isset($entries['SUB'])){
821         $ret = array_merge($ret,$this->generateDepartmentArray($entries['SUB'],$depth,$max_size));
822       }
823     }
825     return($ret);
826   }
828   /* This function returns all available Shares defined in this ldap
829    * There are two ways to call this function, if listboxEntry is true
830    *  only name and path are attached to the array, in it is false, the whole
831    *  entry will be parsed an atached to the result.
832    */
833   function getShareList($listboxEntry = false)
834   {
835     $tmp = get_sub_list("(&(objectClass=goShareServer)(goExportEntry=*))","server",get_ou("serverRDN"),
836         $this->current['BASE'],array("goExportEntry","cn"), GL_NONE);
837     $return =array();
838     foreach($tmp as $entry){
840       if(isset($entry['goExportEntry']['count'])){
841         unset($entry['goExportEntry']['count']);
842       }
843       if(isset($entry['goExportEntry'])){
844         foreach($entry['goExportEntry'] as $export){
845           $shareAttrs = split("\|",$export);
846           if($listboxEntry) {
847             $return[$shareAttrs[0]."|".$entry['cn'][0]] = $shareAttrs[0]." - ".$entry['cn'][0];
848           }else{
849             $return[$shareAttrs[0]."|".$entry['cn'][0]]['server']       = $entry['cn'][0];
850             $return[$shareAttrs[0]."|".$entry['cn'][0]]['name']         = $shareAttrs[0];
851             $return[$shareAttrs[0]."|".$entry['cn'][0]]['description']  = $shareAttrs[1];
852             $return[$shareAttrs[0]."|".$entry['cn'][0]]['type']         = $shareAttrs[2];
853             $return[$shareAttrs[0]."|".$entry['cn'][0]]['charset']      = $shareAttrs[3];
854             $return[$shareAttrs[0]."|".$entry['cn'][0]]['path']         = $shareAttrs[4];
855             $return[$shareAttrs[0]."|".$entry['cn'][0]]['option']       = $shareAttrs[5];
856           }
857         }
858       }
859     }
860     return($return);
861   }
864   /* This function returns all available ShareServer */
865   function getShareServerList()
866   {
867     global $config;
868     $return = array();
869     $ui = get_userinfo();
870     $base = $config->current['BASE'];
871     $res= get_sub_list("(&(objectClass=goShareServer)(goExportEntry=*))", "server",
872           get_ou("serverRDN"), $base,array("goExportEntry","cn"),GL_NONE | GL_NO_ACL_CHECK);
874     foreach($res as $entry){
875         
876         $acl = $ui->get_permissions($entry['dn'],"server","");
877         if(isset($entry['goExportEntry']['count'])){
878           unset($entry['goExportEntry']['count']);
879         }
880         foreach($entry['goExportEntry'] as $share){
881           $a_share = split("\|",$share);
882           $sharename = $a_share[0];
883           $data= array();
884           $data['NAME']   = $sharename;
885           $data['ACL']    = $acl;
886           $data['SERVER'] = $entry['cn']['0'];
887           $data['SHARE']  = $sharename;
888           $data['DISPLAY']= $entry['cn'][0]." [".$sharename."]";
889           $return[$entry['cn'][0]."|".$sharename] = $data;
890         }
891     }
892     return($return);
893   }
896   /* Check if there's the specified bool value set in the configuration */
897   function boolValueIsTrue($section, $value)
898   {
899     $section= strtoupper($section);
900     $value= strtoupper($value);
901     if (isset($this->data[$section][$value])){
902     
903       $data= $this->data[$section][$value];
904       if (preg_match("/^true$/i", $data) || preg_match("/yes/i", $data)){
905         return TRUE;
906       }
908     }
910     return FALSE;
911   }
914   function __search(&$arr, $name, $return)
915   {
916     $return= strtoupper($return);
917     if (is_array($arr)){
918       foreach ($arr as &$a){
919         if (isset($a['CLASS']) && strcasecmp($name, $a['CLASS']) == 0){
920           return(isset($a[$return])?$a[$return]:"");
921         } else {
922           $res= $this->__search ($a, $name, $return);
923           if ($res != ""){
924             return $res;
925           }
926         }
927       }
928     }
929     return ("");
930   }
933   function search($class, $value, $categories= "")
934   {
935     if (is_array($categories)){
936       foreach ($categories as $category){
937         $res= $this->__search($this->data[strtoupper($category)], $class, $value);
938         if ($res != ""){
939           return $res;
940         }
941       }
942     } else {
943       if ($categories == "") {
944         return $this->__search($this->data, $class, $value);
945       } else {
946         return $this->__search($this->data[strtoupper($categories)], $class, $value);
947       }
948     } 
950     return ("");
951   }
954   function get_cfg_value($name, $default= "") {
955     $name= strtoupper($name);
957     /* Check if we have a current value for $name */
958     if (isset($this->current[$name])){
959       return ($this->current[$name]);
960     }
962     /* Check if we have a global value for $name */
963     if (isset($this->data["MAIN"][$name])){
964       return ($this->data["MAIN"][$name]);
965     }
967     return ($default);
968   }
971   function check_config_version()
972   {
973     /* Skip check, if we've already mentioned the mismatch 
974      */
975     if(session::global_is_set("LastChecked") && session::global_get("LastChecked") == $this->config_version) return;
976   
977     /* Remember last checked version 
978      */
979     session::global_set("LastChecked",$this->config_version);
981     $current = md5(file_get_contents(CONFIG_TEMPLATE_DIR."/gosa.conf"));
983     /* Check contributed config version and current config version.
984      */
985     if(($this->config_version == "NOT SET") || ($this->config_version != $current && !empty($this->config_version))){
986       msg_dialog::display(_("Configuration"),_("The configuration file you are using seems to be outdated. Please move the GOsa configuration file away to run the GOsa setup again."));
987     }
988   }
991   /* On debian systems the session files are deleted with
992    *  a cronjob, which detects all files older than specified 
993    *  in php.ini:'session.gc_maxlifetime' and removes them.
994    * This function checks if the gosa.conf value matches the range
995    *  defined by session.gc_maxlifetime.
996    */
997   function check_session_lifetime()
998   {
999     if(isset($this->data['MAIN']['SESSIONLIFETIME'])){
1000       $cfg_lifetime = $this->data['MAIN']['SESSIONLIFETIME'];
1001       $ini_lifetime = ini_get('session.gc_maxlifetime');
1002       $deb_system   = file_exists('/etc/debian_version');
1003       return(!($deb_system && ($ini_lifetime < $cfg_lifetime)));  
1004     }else{
1005       return(TRUE);
1006     }
1007   }
1009   /* Returns true if snapshots are enabled, and false if it is disalbed
1010      There will also be some errors psoted, if the configuration failed */
1011   function snapshotEnabled()
1012   {
1013     if($this->get_cfg_value("enableSnapshots") == "true"){
1015       /* Check if the snapshot_base is defined */
1016       if ($this->get_cfg_value("snapshotBase") == ""){
1018         /* Send message if not done already */
1019         if(!session::is_set("snapshotFailMessageSend")){
1020           session::set("snapshotFailMessageSend",TRUE);
1021           msg_dialog::display(_("Configuration error"),
1022               sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."),
1023                       "snapshotBase"), ERROR_DIALOG);
1024         }
1025         return(FALSE);
1026       }
1028       /* Check if the snapshot_base is defined */
1029       if (!is_callable("gzcompress")){
1031         /* Send message if not done already */
1032         if(!session::is_set("snapshotFailMessageSend")){
1033           session::set("snapshotFailMessageSend",TRUE);
1034           msg_dialog::display(_("Configuration error"),
1035               sprintf(_("The snapshot functionality is enabled, but the required compression module is missing. Please install '%s'."),"php5-zip / php5-gzip"), ERROR_DIALOG);
1036         }
1037         return(FALSE);
1038       }
1040       /* check if there are special server configurations for snapshots */
1041       if ($this->get_cfg_value("snapshotURI") != ""){
1043         /* check if all required vars are available to create a new ldap connection */
1044         $missing = "";
1045         foreach(array("snapshotURI","snapshotAdminDn","snapshotAdminPassword","snapshotBase") as $var){
1046           if($this->get_cfg_value($var) == ""){
1047             $missing .= $var." ";
1049             /* Send message if not done already */
1050             if(!session::is_set("snapshotFailMessageSend")){
1051               session::set("snapshotFailMessageSend",TRUE);
1052               msg_dialog::display(_("Configuration error"),
1053                   sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."),
1054                     $missing), ERROR_DIALOG);
1055             }
1056             return(FALSE);
1057           }
1058                     }
1059             }
1060             return(TRUE);
1061     }
1062     return(FALSE);
1063   }
1067 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1068 ?>