Code

Correct schema naming
[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   {
107     $this->data = array(
108         "TABS"      => array(), 
109         "LOCATIONS" => array(), 
110         "MAIN"      => array(), 
111         "MENU"      => array(), 
112         "SERVICE"   => array());
114     $this->last_modified = filemtime($filename);
115     $this->filename = $filename;
116     $fh= fopen($filename, "r"); 
117     $xmldata= fread($fh, 100000);
118     fclose($fh);
119     if(!xml_parse($this->parser, chop($xmldata))){
120       $msg = sprintf(_("XML error in gosa.conf: %s at line %d"),
121             xml_error_string(xml_get_error_code($this->parser)),
122             xml_get_current_line_number($this->parser));
123       msg_dialog::display(_("Configuration error"), $msg, FATAL_ERROR_DIALOG);
124       exit;
125     }
127     // Default schemacheck to "true"
128     if(!isset($this->data['MAIN']['SCHEMACHECK'])){
129       $this->data['MAIN']['SCHEMACHECK'] = "true";
130     }
131   }
133   function tag_open($parser, $tag, $attrs)
134   {
135     /* Save last and current tag for reference */
136     $this->tags[$this->level]= $tag;
137     $this->level++;
139     /* Trigger on CONF section */
140     if ($tag == 'CONF'){
141       $this->config_found= TRUE;
142       if(isset($attrs['CONFIGVERSION'])){
143         $this->config_version = $attrs['CONFIGVERSION'];
144       }
145     }
147     /* Return if we're not in config section */
148     if (!$this->config_found){
149       return;
150     }
152     /* yes/no to true/false and upper case TRUE to true and so on*/
153     foreach($attrs as $name => $value){
154       if(preg_match("/^(true|yes)$/i",$value)){
155         $attrs[$name] = "true";
156       }elseif(preg_match("/^(false|no)$/i",$value)){
157         $attrs[$name] = "false";
158       } 
159     }
161     /* Look through attributes */
162     switch ($this->tags[$this->level-1]){
165       /* Handle tab section */
166       case 'TAB':       $name= $this->tags[$this->level-2];
168                   /* Create new array? */
169                   if (!isset($this->data['TABS'][$name])){
170                     $this->data['TABS'][$name]= array();
171                   }
173                   /* Add elements */
174                   $this->data['TABS'][$name][]= $attrs;
175                   break;
177                   /* Handle location */
178       case 'LOCATION':
179                   if ($this->tags[$this->level-2] == 'MAIN'){
180                     $name= $attrs['NAME'];
181                     $name = preg_replace("/[<>\"']/","",$name);
182                     $attrs['NAME'] = $name;
183                     $this->currentLocation= $name;
185                     /* Add location elements */
186                     $this->data['LOCATIONS'][$name]= $attrs;
187                   }
188                   break;
190                   /* Handle referral tags */
191       case 'REFERRAL':
192                   if ($this->tags[$this->level-2] == 'LOCATION'){
193                     $url= $attrs['URI'];
194                     $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
196                     /* Add location elements */
197                     if (!isset($this->data['LOCATIONS'][$this->currentLocation]['REFERRAL'])){
198                       $this->data['LOCATIONS'][$this->currentLocation]['REFERRAL']= array();
199                     }
201                     $this->data['LOCATIONS'][$this->currentLocation]['REFERRAL'][$server]= $attrs;
202                   }
203                   break;
205                   /* Load main parameters */
206       case 'MAIN':
207                   $this->data['MAIN']= array_merge ($this->data['MAIN'], $attrs);
208                   break;
210                   /* Load menu */
211       case 'SECTION':
212                   if ($this->tags[$this->level-2] == 'MENU'){
213                     $this->section= $attrs['NAME'];
214                     $this->data['MENU'][$this->section]= array(); ;
215                   }
216                   break;
218                   /* Inser plugins */
219       case 'PLUGIN':
220                   if ($this->tags[$this->level-3] == 'MENU' &&
221                       $this->tags[$this->level-2] == 'SECTION'){
223                     $this->data['MENU'][$this->section][$this->gpc++]= $attrs;
224                   }
225                   if ($this->tags[$this->level-2] == 'SERVICEMENU'){
226                     $this->data['SERVICE'][$attrs['CLASS']]= $attrs;
227                   }
228                   break;
229     }
230   }
232   function tag_close($parser, $tag)
233   {
234     /* Close config section */
235     if ($tag == 'CONF'){
236       $this->config_found= FALSE;
237     }
238     $this->level--;
239   }
242   function get_credentials($creds)
243   {
244     if (isset($_SERVER['HTTP_GOSA_KEY'])){
245       if (!session::global_is_set('HTTP_GOSA_KEY_CACHE')){
246         session::global_set('HTTP_GOSA_KEY_CACHE',array());
247       }
248       $cache = session::global_get('HTTP_GOSA_KEY_CACHE');
249       if(!isset($cache[$creds])){
250         $cache[$creds] = cred_decrypt($creds, $_SERVER['HTTP_GOSA_KEY']);
251         session::global_set('HTTP_GOSA_KEY_CACHE',$cache);
252       }
253       return ($cache[$creds]);
254     }
255     return ($creds);
256   }
259   function get_ldap_link($sizelimit= FALSE)
260   {
261     if($this->ldap === NULL || !is_resource($this->ldap->cid)){
263       /* Build new connection */
264       $this->ldap= ldap_init ($this->current['SERVER'], $this->current['BASE'],
265           $this->current['ADMINDN'], $this->get_credentials($this->current['ADMINPASSWORD']));
267       /* Check for connection */
268       if (is_null($this->ldap) || (is_int($this->ldap) && $this->ldap == 0)){
269         $smarty= get_smarty();
270         msg_dialog::display(_("LDAP error"), _("Cannot bind to LDAP. Please contact the system administrator."), FATAL_ERROR_DIALOG);
271         exit();
272       }
274       /* Move referrals */
275       if (!isset($this->current['REFERRAL'])){
276         $this->ldap->referrals= array();
277       } else {
278         $this->ldap->referrals= $this->current['REFERRAL'];
279       }
281       if (!session::global_is_set('size_limit')){
282         session::global_set('size_limit',$this->current['LDAPSIZELIMIT']);
283         session::global_set('size_ignore',$this->current['LDAPSIZEIGNORE']);
284       }
285     }
287     $obj  = new ldapMultiplexer($this->ldap);
288     if ($sizelimit){
289       $obj->set_size_limit(session::global_get('size_limit'));
290     } else {
291       $obj->set_size_limit(0);
292     }
293     return($obj);
294   }
296   function set_current($name)
297   {
298     $this->current= $this->data['LOCATIONS'][$name];
300     if (!isset($this->current['SAMBAVERSION'])){
301       $this->current['SAMBAVERSION']= 3;
302     }
303     if (!isset($this->current['USERRDN'])){
304       $this->current['USERRDN']= "ou=people";
305     }
306     if (!isset($this->current['GROUPRDN'])){
307       $this->current['GROUPS']= "ou=groups";
308     }
310     if (isset($this->current['INITIAL_BASE'])){
311       session::global_set('CurrentMainBase',$this->current['INITIAL_BASE']);
312     }
313   
314     /* Remove possibly added ',' from end of group and people ou */
315     $this->current['GROUPS'] = preg_replace("/,*$/","",$this->current['GROUPRDN']);
316     $this->current['USERRDN'] = preg_replace("/,*$/","",$this->current['USERRDN']);
318     if (!isset($this->current['SAMBAMACHINEACCOUNTRDN'])){
319       $this->current['SAMBAMACHINEACCOUNTRDN']= "ou=winstations,ou=systems";
320     }
321     if (!isset($this->current['ACCOUNTPRIMARYATTRIBUTE'])){
322       $this->current['ACCOUNTPRIMARYATTRIBUTE']= "cn";
323     }
324     if (!isset($this->current['MINID'])){
325       $this->current['MINID']= 100;
326     }
327     if (!isset($this->current['LDAPSIZELIMIT'])){
328       $this->current['LDAPSIZELIMIT']= 200;
329     }
330     if (!isset($this->current['SIZEINGORE'])){
331       $this->current['LDAPSIZEIGNORE']= TRUE;
332     } else {
333       if (preg_match("/true/i", $this->current['LDAPSIZEIGNORE'])){
334         $this->current['LDAPSIZEIGNORE']= TRUE;
335       } else {
336         $this->current['LDAPSIZEIGNORE']= FALSE;
337       }
338     }
340     /* Sort referrals, if present */
341     if (isset ($this->current['REFERRAL'])){
342       $bases= array();
343       $servers= array();
344       foreach ($this->current['REFERRAL'] as $ref){
345         $server= preg_replace('%^(.*)/[^/]+$%', '\\1', $ref['URI']);
346         $base= preg_replace('%^.*/([^/]+)$%', '\\1', $ref['URI']);
347         $bases[$base]= strlen($base);
348         $servers[$base]= $server;
349       }
350       asort($bases);
351       reset($bases);
352     }
354     /* SERVER not defined? Load the one with the shortest base */
355     if (!isset($this->current['SERVER'])){
356       $this->current['SERVER']= $servers[key($bases)];
357     }
359     /* BASE not defined? Load the one with the shortest base */
360     if (!isset($this->current['BASE'])){
361       $this->current['BASE']= key($bases);
362     }
364     /* Convert BASE to have escaped special characters */
365     $this->current['BASE']= @LDAP::convert($this->current['BASE']);
367     /* Parse LDAP referral informations */
368     if (!isset($this->current['ADMINDN']) || !isset($this->current['ADMINPASSWORD'])){
369       $url= $this->current['SERVER'];
370       $referral= $this->current['REFERRAL'][$url];
371       $this->current['ADMINDN']= $referral['ADMINDN'];
372       $this->current['ADMINPASSWORD']= $referral['ADMINPASSWORD'];
373     }
375     /* Load server informations */
376     $this->load_servers();
377   }
379   function load_servers ()
380   {
381     /* Only perform actions if current is set */
382     if ($this->current === NULL){
383       return;
384     }
386     /* Fill imap servers */
387     $ldap= $this->get_ldap_link();
388     $ldap->cd ($this->current['BASE']);
390     /* Search mailMethod konfiguration in main section too 
391      */
392     $this->current['MAILMETHOD'] = $this->get_cfg_value("mailMethod","");
393     if (!isset($this->current['MAILMETHOD'])){
394       $this->current['MAILMETHOD']= "";
395     }
396     if ($this->current['MAILMETHOD'] == ""){
397       $ldap->search ("(objectClass=goMailServer)", array('cn'));
398       $this->data['SERVERS']['IMAP']= array();
399       while ($attrs= $ldap->fetch()){
400         $name= $attrs['cn'][0];
401         $this->data['SERVERS']['IMAP'][$name]= 
402           array( 
403               "server_dn"   => $attrs['dn'],
404               "connect"     => "",
405               "admin"       => "",
406               "password"    => "",
407               "sieve_server"=> "",
408               "sieve_option"=> "",
409               "sieve_port"  => "");
410       }
411     } else {
412       $ldap->search ("(&(objectClass=goImapServer)(goImapSieveServer=*))", 
413                     array('goImapName', 'goImapConnect', 'goImapAdmin', 'goImapPassword',
414             'goImapSieveServer', 'goImapSievePort'));
416       $this->data['SERVERS']['IMAP']= array();
418       while ($attrs= $ldap->fetch()){
420         /* Check if the given goImapSieveServer is in the new style "{cn:port/option}"
421            or the old style just "cn".
422          */
423         if(preg_match("/\{/",$attrs['goImapSieveServer'][0])){
424           $sieve_server = preg_replace("/^\{([^:]*).*$/","\\1",$attrs['goImapSieveServer'][0]);
425           $sieve_option = preg_replace("/^[^:]*[^\/]*+\/(.*)\}$/","\\1",$attrs['goImapSieveServer'][0]);
426         }else{
427           $sieve_server = $attrs['goImapSieveServer'][0];
428           $sieve_option = "";
429         }
431         $pwd            = $attrs['goImapPassword'][0];
432         $imap_admin     = $attrs['goImapAdmin'][0];
433         $imap_connect   = $attrs['goImapConnect'][0];
434         $imap_server    = $attrs['goImapName'][0];
435         $sieve_port     = $attrs['goImapSievePort'][0];
436         
437         $this->data['SERVERS']['IMAP'][$imap_server]= 
438             array( 
439             "server_dn"   => $attrs['dn'],
440             "connect"     => $imap_connect,
441             "admin"       => $imap_admin,
442             "password"    => $pwd,
443             "sieve_server"=> $sieve_server,
444             "sieve_option"=> $sieve_option,
445             "sieve_port"  => $sieve_port);
446       }
447     }
449     /* Get kerberos server. FIXME: only one is supported currently */
450     $ldap->cd ($this->current['BASE']);
451     $ldap->search ("(&(goKrbRealm=*)(goKrbAdmin=*)(objectClass=goKrbServer))");
452     if ($ldap->count()){
453       $attrs= $ldap->fetch();
454       $this->data['SERVERS']['KERBEROS']= array( 'SERVER' => $attrs['cn'][0],
455           'REALM' => $attrs['goKrbRealm'][0],
456           'ADMIN' => $attrs['goKrbAdmin'][0]);
457     }
459     /* Get cups server. FIXME: only one is supported currently */
460     $ldap->cd ($this->current['BASE']);
461     $ldap->search ("(objectClass=goCupsServer)");
462     if ($ldap->count()){
463       $attrs= $ldap->fetch();
464       $this->data['SERVERS']['CUPS']= $attrs['cn'][0];  
465     }
467     /* Get fax server. FIXME: only one is supported currently */
468     $ldap->cd ($this->current['BASE']);
469     $ldap->search ("(objectClass=goFaxServer)");
470     if ($ldap->count()){
471       $attrs= $ldap->fetch();
472       $this->data['SERVERS']['FAX']= array( 'SERVER' => $attrs['cn'][0],
473           'LOGIN' => $attrs['goFaxAdmin'][0],
474           'PASSWORD' => $attrs['goFaxPassword'][0]);
475     }
478     /* Get asterisk servers */
479     $ldap->cd ($this->current['BASE']);
480     $ldap->search ("(objectClass=goFonServer)");
481     $this->data['SERVERS']['FON']= array();
482     if ($ldap->count()){
483       while ($attrs= $ldap->fetch()){
485         /* Add 0 entry for development */
486         if(count($this->data['SERVERS']['FON']) == 0){
487           $this->data['SERVERS']['FON'][0]= array(
488               'DN'      => $attrs['dn'],
489               'SERVER'  => $attrs['cn'][0],
490               'LOGIN'   => $attrs['goFonAdmin'][0],
491               'PASSWORD'  => $attrs['goFonPassword'][0],
492               'DB'    => "gophone",
493               'SIP_TABLE'   => "sip_users",
494               'EXT_TABLE'   => "extensions",
495               'VOICE_TABLE' => "voicemail_users",
496               'QUEUE_TABLE' => "queues",
497               'QUEUE_MEMBER_TABLE'  => "queue_members");
498         }
500         /* Add entry with 'dn' as index */
501         $this->data['SERVERS']['FON'][$attrs['dn']]= array(
502             'DN'      => $attrs['dn'],
503             'SERVER'  => $attrs['cn'][0],
504             'LOGIN'   => $attrs['goFonAdmin'][0],
505             'PASSWORD'  => $attrs['goFonPassword'][0],
506             'DB'    => "gophone",
507             'SIP_TABLE'   => "sip_users",
508             'EXT_TABLE'   => "extensions",
509             'VOICE_TABLE' => "voicemail_users",
510             'QUEUE_TABLE' => "queues",
511             'QUEUE_MEMBER_TABLE'  => "queue_members");
512       }
513     }
516     /* Get glpi server */
517     $ldap->cd ($this->current['BASE']);
518     $ldap->search ("(&(objectClass=goGlpiServer)(cn=*)(goGlpiAdmin=*)(goGlpiDatabase=*))",array("cn","goGlpiPassword","goGlpiAdmin","goGlpiDatabase"));
519     if ($ldap->count()){
520       $attrs= $ldap->fetch();
521       if(!isset($attrs['goGlpiPassword'])){
522         $attrs['goGlpiPassword'][0] ="";
523       }
524       $this->data['SERVERS']['GLPI']= array( 
525           'SERVER'      => $attrs['cn'][0],
526           'LOGIN'       => $attrs['goGlpiAdmin'][0],
527           'PASSWORD'    => $attrs['goGlpiPassword'][0],
528           'DB'          => $attrs['goGlpiDatabase'][0]);
529     }
532     /* Get logdb server */
533     $ldap->cd ($this->current['BASE']);
534     $ldap->search ("(objectClass=goLogDBServer)");
535     if ($ldap->count()){
536       $attrs= $ldap->fetch();
537       if(!isset($attrs['gosaLogDB'][0])){
538         $attrs['gosaLogDB'][0] = "gomon";
539       }
540       $this->data['SERVERS']['LOG']= array( 'SERVER' => $attrs['cn'][0],
541           'LOGIN' => $attrs['goLogAdmin'][0],
542           'DB' => $attrs['gosaLogDB'][0],
543           'PASSWORD' => $attrs['goLogPassword'][0]);
544     }
547     /* GOsa logging databases */
548     $ldap->cd ($this->current['BASE']);
549     $ldap->search ("(objectClass=gosaLogServer)");
550     if ($ldap->count()){
551       while($attrs= $ldap->fetch()){
552       $this->data['SERVERS']['LOGGING'][$attrs['cn'][0]]= 
553           array(
554           'DN'    => $attrs['dn'],
555           'USER'  => $attrs['goLogDBUser'][0],
556           'DB'    => $attrs['goLogDB'][0],
557           'PWD'   => $attrs['goLogDBPassword'][0]);
558       }
559     }
562     /* Get NFS server lists */
563     $tmp= array("default");
564     $tmp2= array("default");
565     $ldap->cd ($this->current['BASE']);
566     $ldap->search ("(&(objectClass=goShareServer)(goExportEntry=*))");
567     while ($attrs= $ldap->fetch()){
568       for ($i= 0; $i<$attrs["goExportEntry"]["count"]; $i++){
569         if(preg_match('/^[^|]+\|[^|]+\|NFS\|.*$/', $attrs["goExportEntry"][$i])){
570           $path= preg_replace ("/^[^|]+\|[^|]+\|[^|]+\|[^|]+\|([^|]+).*$/", '\1', $attrs["goExportEntry"][$i]);
571           $tmp[]= $attrs["cn"][0].":$path";
572         }
573         if(preg_match('/^[^|]+\|[^|]+\|NBD\|.*$/', $attrs["goExportEntry"][$i])){
574           $path= preg_replace ("/^[^|]+\|[^|]+\|[^|]+\|[^|]+\|([^|]+).*$/", '\1', $attrs["goExportEntry"][$i]);
575           $tmp2[]= $attrs["cn"][0].":$path";
576         }
577       }
578     }
579     $this->data['SERVERS']['NFS']= $tmp;
580     $this->data['SERVERS']['NBD']= $tmp2;
582     /* Load Terminalservers */
583     $ldap->cd ($this->current['BASE']);
584     $ldap->search ("(objectClass=goTerminalServer)",array("cn","gotoSessionType"));
585     $this->data['SERVERS']['TERMINAL']= array();
586     $this->data['SERVERS']['TERMINAL'][]= "default";
587     $this->data['SERVERS']['TERMINAL_SESSION_TYPES'] = array();
590     while ($attrs= $ldap->fetch()){
591       $this->data['SERVERS']['TERMINAL'][]= $attrs["cn"][0];
592       if(isset( $attrs["gotoSessionType"]['count'])){
593         for($i =0 ; $i < $attrs["gotoSessionType"]['count'] ; $i++){
594           $this->data['SERVERS']['TERMINAL_SESSION_TYPES'][$attrs["cn"][0]][] = $attrs["gotoSessionType"][$i]; 
595         }
596       }
597     }
599     /* Ldap Server 
600      */
601     $this->data['SERVERS']['LDAP']= array();
602     $ldap->cd ($this->current['BASE']);
603     $ldap->search ("(&(objectClass=goLdapServer)(goLdapBase=*))");
604     while ($attrs= $ldap->fetch()){
605       $this->data['SERVERS']['LDAP'][$attrs['dn']] = $attrs;
606     }
608     /* Get misc server lists */
609     $this->data['SERVERS']['SYSLOG']= array("default");
610     $this->data['SERVERS']['NTP']= array("default");
611     $ldap->cd ($this->current['BASE']);
612     $ldap->search ("(objectClass=goNtpServer)");
613     while ($attrs= $ldap->fetch()){
614       $this->data['SERVERS']['NTP'][]= $attrs["cn"][0];
615     }
616     $ldap->cd ($this->current['BASE']);
617     $ldap->search ("(objectClass=goSyslogServer)");
618     while ($attrs= $ldap->fetch()){
619       $this->data['SERVERS']['SYSLOG'][]= $attrs["cn"][0];
620     }
622     /* Get samba servers from LDAP, in case of samba3 */
623     if ($this->current['SAMBAVERSION'] == 3){
624       $this->data['SERVERS']['SAMBA']= array();
625       $ldap->cd ($this->current['BASE']);
626       $ldap->search ("(objectClass=sambaDomain)");
627       while ($attrs= $ldap->fetch()){
628         $this->data['SERVERS']['SAMBA'][$attrs['sambaDomainName'][0]]= array( "SID" =>"","RIDBASE" =>"");
629         if(isset($attrs["sambaSID"][0])){
630           $this->data['SERVERS']['SAMBA'][$attrs['sambaDomainName'][0]]["SID"]  = $attrs["sambaSID"][0];
631         }
632         if(isset($attrs["sambaAlgorithmicRidBase"][0])){
633           $this->data['SERVERS']['SAMBA'][$attrs['sambaDomainName'][0]]["RIDBASE"] = $attrs["sambaAlgorithmicRidBase"][0];
634         }
635       }
637       /* If no samba servers are found, look for configured sid/ridbase */
638       if (count($this->data['SERVERS']['SAMBA']) == 0){
639         if (!isset($this->current["SAMBASID"]) || !isset($this->current["SAMBARIDBASE"])){
640           msg_dialog::display(_("Configuration error"), _("sambaSID and/or sambaRidBase missing in the configuration!"), ERROR_DIALOG);
641         } else {
642           $this->data['SERVERS']['SAMBA']['DEFAULT']= array(
643               "SID" => $this->current["SAMBASID"],
644               "RIDBASE" => $this->current["SAMBARIDBASE"]);
645         }
646       }
647     }
648   }
651   function get_departments($ignore_dn= "")
652   {
653     global $config;
655     /* Initialize result hash */
656     $result= array();
657     $administrative= array();
658     $result['/']= $this->current['BASE'];
659     $this->tdepartments= array();
661     /* Get all department types from department Management, to be able detect the department type.
662         -It is possible that differnty department types have the same name, 
663          in this case we have to mark the department name to be able to differentiate.
664           (e.g l=Name  or   o=Name)
665      */    
666     $types = departmentManagement::get_support_departments();
667     
668     /* Create a list of attributes to fetch */
669     $ldap_values = array("objectClass","gosaUnitTag");
670     $filter = "";
671     foreach($types as $type){
672       $ldap_values[] = $type['ATTR'];
673       $filter .= "(objectClass=".$type['OC'].")";
674     }
675     $filter = "(&(objectClass=gosaDepartment)(|".$filter."))";
677     /* Get list of department objects */
678     $ldap= $this->get_ldap_link();
679     $ldap->cd ($this->current['BASE']);
680     $ldap->search ($filter, $ldap_values);
681     while ($attrs= $ldap->fetch()){
683       /* Detect department type */
684       $type_data = array();
685       foreach($types as $t => $data){
686         if(in_array($data['OC'],$attrs['objectClass'])){
687           $type_data = $data;
688           break;    
689         }
690       }
692       /* Unknown department type -> skip 
693        */
694       if(!count($type_data)) continue;
696       $dn= $ldap->getDN();
697       $this->tdepartments[$dn]= "";
699       /* Save administrative departments */
700       if (in_array_ics("gosaAdministrativeUnit", $attrs['objectClass']) &&
701           isset($attrs['gosaUnitTag'][0])){
702         $administrative[$dn]= $attrs['gosaUnitTag'][0];
703         $this->tdepartments[$dn]= $attrs['gosaUnitTag'][0];
704       }
705     
706       if (in_array_ics("gosaAdministrativeUnitTag", $attrs['objectClass']) &&
707           isset($attrs['gosaUnitTag'][0])){
708         $this->tdepartments[$dn]= $attrs['gosaUnitTag'][0];
709       }
710     
711       if ($dn == $ignore_dn){
712         continue;
713       }
715       $c_dn = convert_department_dn($dn)." (".$type_data['ATTR'].")";
717       /* Only assign non-root departments */
718       if ($dn != $result['/']){
719         $result[$c_dn]= $dn;
720       }
721     }
723     $this->adepartments= $administrative;
724     $this->departments= $result;
725   }
728   function make_idepartments($max_size= 28)
729   {
730     global $config;
731     $base = $config->current['BASE'];
732                 $qbase = preg_quote($base, '/');
733     $utags= isset($config->current['HONOURUNITTAGS']) && preg_match('/true/i', $config->current['HONOURUNITTAGS']);
735     $arr = array();
736     $ui= get_userinfo();
738     $this->idepartments= array();
740     /* Create multidimensional array, with all departments. */
741     foreach ($this->departments as $key => $val){
743       /* When using strict_units, filter non relevant parts */
744       if ($utags){
745         if ($ui->gosaUnitTag != '' && isset($this->tdepartments[$val]) &&
746             $this->tdepartments[$val] != $ui->gosaUnitTag){
748                                                 #TODO: link with strict*
749                                                 #continue;
750         }
751       }
753       /* Split dn into single department pieces */
754       $elements = array_reverse(split(',',preg_replace("/$qbase$/",'',$val)));          
756       /* Add last ou element of current dn to our array */
757       $last = &$arr;
758       foreach($elements as $key => $ele){
760         /* skip empty */
761         if(empty($ele)) continue;
763         /* Extract department name */           
764         $elestr = trim(preg_replace('/^[^=]*+=/','', $ele),',');
765         $nameA  = trim(preg_replace('/=.*$/','', $ele),',');
766         if($nameA != 'ou'){
767           $nameA = " ($nameA)";
768         }else{
769           $nameA = '';
770         }
771     
772         /* Add to array */      
773         if($key == (count($elements)-1)){
774           $last[$elestr.$nameA]['ENTRY'] = $val;
775         }
777         /* Set next array appending position */
778         $last = &$last[$elestr.$nameA]['SUB'];
779       }
780     }
783     /* Add base entry */
784     $ret['/']['ENTRY']  = $base;
785     $ret['/']['SUB']    = $arr;
786     $this->idepartments= $this->generateDepartmentArray($ret,-1,$max_size);
787   }
790   /* Creates display friendly output from make_idepartments */
791   function generateDepartmentArray($arr,$depth = -1,$max_size = 256)
792   {
793     $ret = array();
794     $depth ++;
796     /* Walk through array */    
797     ksort($arr);
798     foreach($arr as $name => $entries){
800       /* If this department is the last in the current tree position 
801        * remove it, to avoid generating output for it */
802       if(count($entries['SUB'])==0){
803         unset($entries['SUB']);
804       }
806       /* Fix name, if it contains a replace tag */
807       $name= preg_replace('/\\\\,/', ',', LDAP::fix($name));
809       /* Check if current name is too long, then cut it */
810       if(mb_strlen($name, 'UTF-8')> $max_size){
811         $name = mb_substr($name,0,($max_size-3), 'UTF-8')." ...";
812       }
814       /* Append the name to the list */ 
815       if(isset($entries['ENTRY'])){
816         $a = "";
817         for($i = 0 ; $i < $depth ; $i ++){
818           $a.=".";
819         }
820         $ret[$entries['ENTRY']]=$a."&nbsp;".$name;
821       } 
823       /* recursive add of subdepartments */
824       if(isset($entries['SUB'])){
825         $ret = array_merge($ret,$this->generateDepartmentArray($entries['SUB'],$depth,$max_size));
826       }
827     }
829     return($ret);
830   }
832   /* This function returns all available Shares defined in this ldap
833    * There are two ways to call this function, if listboxEntry is true
834    *  only name and path are attached to the array, in it is false, the whole
835    *  entry will be parsed an atached to the result.
836    */
837   function getShareList($listboxEntry = false)
838   {
839     $tmp = get_sub_list("(&(objectClass=goShareServer)(goExportEntry=*))","server",get_ou("serverRDN"),
840         $this->current['BASE'],array("goExportEntry","cn"), GL_NONE);
841     $return =array();
842     foreach($tmp as $entry){
844       if(isset($entry['goExportEntry']['count'])){
845         unset($entry['goExportEntry']['count']);
846       }
847       if(isset($entry['goExportEntry'])){
848         foreach($entry['goExportEntry'] as $export){
849           $shareAttrs = split("\|",$export);
850           if($listboxEntry) {
851             $return[$shareAttrs[0]."|".$entry['cn'][0]] = $shareAttrs[0]." - ".$entry['cn'][0];
852           }else{
853             $return[$shareAttrs[0]."|".$entry['cn'][0]]['server']       = $entry['cn'][0];
854             $return[$shareAttrs[0]."|".$entry['cn'][0]]['name']         = $shareAttrs[0];
855             $return[$shareAttrs[0]."|".$entry['cn'][0]]['description']  = $shareAttrs[1];
856             $return[$shareAttrs[0]."|".$entry['cn'][0]]['type']         = $shareAttrs[2];
857             $return[$shareAttrs[0]."|".$entry['cn'][0]]['charset']      = $shareAttrs[3];
858             $return[$shareAttrs[0]."|".$entry['cn'][0]]['path']         = $shareAttrs[4];
859             $return[$shareAttrs[0]."|".$entry['cn'][0]]['option']       = $shareAttrs[5];
860           }
861         }
862       }
863     }
864     return($return);
865   }
868   /* This function returns all available ShareServer */
869   function getShareServerList()
870   {
871     global $config;
872     $return = array();
873     $ui = get_userinfo();
874     $base = $config->current['BASE'];
875     $res= get_sub_list("(&(objectClass=goShareServer)(goExportEntry=*))", "server",
876           get_ou("serverRDN"), $base,array("goExportEntry","cn"),GL_NONE | GL_NO_ACL_CHECK);
878     foreach($res as $entry){
879         
880         $acl = $ui->get_permissions($entry['dn'],"server","");
881         if(isset($entry['goExportEntry']['count'])){
882           unset($entry['goExportEntry']['count']);
883         }
884         foreach($entry['goExportEntry'] as $share){
885           $a_share = split("\|",$share);
886           $sharename = $a_share[0];
887           $data= array();
888           $data['NAME']   = $sharename;
889           $data['ACL']    = $acl;
890           $data['SERVER'] = $entry['cn']['0'];
891           $data['SHARE']  = $sharename;
892           $data['DISPLAY']= $entry['cn'][0]." [".$sharename."]";
893           $return[$entry['cn'][0]."|".$sharename] = $data;
894         }
895     }
896     return($return);
897   }
900   /* Check if there's the specified bool value set in the configuration */
901   function boolValueIsTrue($section, $value)
902   {
903     $section= strtoupper($section);
904     $value= strtoupper($value);
905     if (isset($this->data[$section][$value])){
906     
907       $data= $this->data[$section][$value];
908       if (preg_match("/^true$/i", $data) || preg_match("/yes/i", $data)){
909         return TRUE;
910       }
912     }
914     return FALSE;
915   }
918   function __search(&$arr, $name, $return)
919   {
920     $return= strtoupper($return);
921     if (is_array($arr)){
922       foreach ($arr as &$a){
923         if (isset($a['CLASS']) && strcasecmp($name, $a['CLASS']) == 0){
924           return(isset($a[$return])?$a[$return]:"");
925         } else {
926           $res= $this->__search ($a, $name, $return);
927           if ($res != ""){
928             return $res;
929           }
930         }
931       }
932     }
933     return ("");
934   }
937   function search($class, $value, $categories= "")
938   {
939     if (is_array($categories)){
940       foreach ($categories as $category){
941         $res= $this->__search($this->data[strtoupper($category)], $class, $value);
942         if ($res != ""){
943           return $res;
944         }
945       }
946     } else {
947       if ($categories == "") {
948         return $this->__search($this->data, $class, $value);
949       } else {
950         return $this->__search($this->data[strtoupper($categories)], $class, $value);
951       }
952     } 
954     return ("");
955   }
958   function get_cfg_value($name, $default= "") {
959     $name= strtoupper($name);
961     /* Check if we have a current value for $name */
962     if (isset($this->current[$name])){
963       return ($this->current[$name]);
964     }
966     /* Check if we have a global value for $name */
967     if (isset($this->data["MAIN"][$name])){
968       return ($this->data["MAIN"][$name]);
969     }
971     return ($default);
972   }
975   function check_config_version()
976   {
977     /* Skip check, if we've already mentioned the mismatch 
978      */
979     if(session::global_is_set("LastChecked") && session::global_get("LastChecked") == $this->config_version) return;
980   
981     /* Remember last checked version 
982      */
983     session::global_set("LastChecked",$this->config_version);
985     $current = md5(file_get_contents(CONFIG_TEMPLATE_DIR."/gosa.conf"));
987     /* Check contributed config version and current config version.
988      */
989     if(($this->config_version == "NOT SET") || ($this->config_version != $current && !empty($this->config_version))){
990       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."));
991     }
992   }
995   /* On debian systems the session files are deleted with
996    *  a cronjob, which detects all files older than specified 
997    *  in php.ini:'session.gc_maxlifetime' and removes them.
998    * This function checks if the gosa.conf value matches the range
999    *  defined by session.gc_maxlifetime.
1000    */
1001   function check_session_lifetime()
1002   {
1003     if(isset($this->data['MAIN']['SESSIONLIFETIME'])){
1004       $cfg_lifetime = $this->data['MAIN']['SESSIONLIFETIME'];
1005       $ini_lifetime = ini_get('session.gc_maxlifetime');
1006       $deb_system   = file_exists('/etc/debian_version');
1007       return(!($deb_system && ($ini_lifetime < $cfg_lifetime)));  
1008     }else{
1009       return(TRUE);
1010     }
1011   }
1013   /* Returns true if snapshots are enabled, and false if it is disalbed
1014      There will also be some errors psoted, if the configuration failed */
1015   function snapshotEnabled()
1016   {
1017     if($this->get_cfg_value("enableSnapshots") == "true"){
1019       /* Check if the snapshot_base is defined */
1020       if ($this->get_cfg_value("snapshotBase") == ""){
1022         /* Send message if not done already */
1023         if(!session::is_set("snapshotFailMessageSend")){
1024           session::set("snapshotFailMessageSend",TRUE);
1025           msg_dialog::display(_("Configuration error"),
1026               sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."),
1027                       "snapshotBase"), ERROR_DIALOG);
1028         }
1029         return(FALSE);
1030       }
1032       /* Check if the snapshot_base is defined */
1033       if (!is_callable("gzcompress")){
1035         /* Send message if not done already */
1036         if(!session::is_set("snapshotFailMessageSend")){
1037           session::set("snapshotFailMessageSend",TRUE);
1038           msg_dialog::display(_("Configuration error"),
1039               sprintf(_("The snapshot functionality is enabled, but the required compression module is missing. Please install '%s'."),"php5-zip / php5-gzip"), ERROR_DIALOG);
1040         }
1041         return(FALSE);
1042       }
1044       /* check if there are special server configurations for snapshots */
1045       if ($this->get_cfg_value("snapshotURI") != ""){
1047         /* check if all required vars are available to create a new ldap connection */
1048         $missing = "";
1049         foreach(array("snapshotURI","snapshotAdminDn","snapshotAdminPassword","snapshotBase") as $var){
1050           if($this->get_cfg_value($var) == ""){
1051             $missing .= $var." ";
1053             /* Send message if not done already */
1054             if(!session::is_set("snapshotFailMessageSend")){
1055               session::set("snapshotFailMessageSend",TRUE);
1056               msg_dialog::display(_("Configuration error"),
1057                   sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."),
1058                     $missing), ERROR_DIALOG);
1059             }
1060             return(FALSE);
1061           }
1062                     }
1063             }
1064             return(TRUE);
1065     }
1066     return(FALSE);
1067   }
1071 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1072 ?>