Code

Fixed get_sub_list
[gosa.git] / gosa-core / include / functions.inc
1 <?php
2 /*
3  * This code is part of GOsa (https://gosa.gonicus.de)
4  * Copyright (C) 2003 Cajus Pollmeier
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
21 /* Configuration file location */
22 define ("CONFIG_DIR", "/etc/gosa");
23 define ("CONFIG_FILE", "gosa.conf-trunk");
24 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
25 define ("HELP_BASEDIR", "/var/www/doc/");
27 /* Define get_list flags */
28 define("GL_NONE",      0);
29 define("GL_SUBSEARCH", 1);
30 define("GL_SIZELIMIT", 2);
31 define("GL_CONVERT"  , 4);
33 /* Heimdal stuff */
34 define('UNIVERSAL',0x00);
35 define('INTEGER',0x02);
36 define('OCTET_STRING',0x04);
37 define('OBJECT_IDENTIFIER ',0x06);
38 define('SEQUENCE',0x10);
39 define('SEQUENCE_OF',0x10);
40 define('SET',0x11);
41 define('SET_OF',0x11);
42 define('DEBUG',false);
43 define('HDB_KU_MKEY',0x484442);
44 define('TWO_BIT_SHIFTS',0x7efc);
45 define('DES_CBC_CRC',1);
46 define('DES_CBC_MD4',2);
47 define('DES_CBC_MD5',3);
48 define('DES3_CBC_MD5',5);
49 define('DES3_CBC_SHA1',16);
51 /* Define globals for revision comparing */
52 $svn_path = '$HeadURL$';
53 $svn_revision = '$Revision$';
55 /* Include required files */
56 require_once("class_location.inc");
57 require_once ("functions_debug.inc");
58 require_once ("functions_dns.inc");
59 require_once ("accept-to-gettext.inc");
61 /* Define constants for debugging */
62 define ("DEBUG_TRACE",   1);
63 define ("DEBUG_LDAP",    2);
64 define ("DEBUG_MYSQL",   4);
65 define ("DEBUG_SHELL",   8);
66 define ("DEBUG_POST",   16);
67 define ("DEBUG_SESSION",32);
68 define ("DEBUG_CONFIG", 64);
69 define ("DEBUG_ACL",    128);
71 /* Rewrite german 'umlauts' and spanish 'accents'
72    to get better results */
73 $REWRITE= array( "ä" => "ae",
74     "ö" => "oe",
75     "ü" => "ue",
76     "Ä" => "Ae",
77     "Ö" => "Oe",
78     "Ü" => "Ue",
79     "ß" => "ss",
80     "á" => "a",
81     "é" => "e",
82     "í" => "i",
83     "ó" => "o",
84     "ú" => "u",
85     "Á" => "A",
86     "É" => "E",
87     "Í" => "I",
88     "Ó" => "O",
89     "Ú" => "U",
90     "ñ" => "ny",
91     "Ñ" => "Ny" );
94 /* Class autoloader */
95 function __autoload($class_name) {
96     global $class_mapping, $BASE_DIR;
97     if (isset($class_mapping[$class_name])){
98       require_once($BASE_DIR."/".$class_mapping[$class_name]);
99     } else {
100       echo _("Fatal: cannot load class \"$class_name\" - execution aborted");
101     }
104 /* Create seed with microseconds */
105 function make_seed() {
106   list($usec, $sec) = explode(' ', microtime());
107   return (float) $sec + ((float) $usec * 100000);
111 /* Debug level action */
112 function DEBUG($level, $line, $function, $file, $data, $info="")
114   if (get_global('DEBUGLEVEL') & $level){
115     $output= "DEBUG[$level] ";
116     if ($function != ""){
117       $output.= "($file:$function():$line) - $info: ";
118     } else {
119       $output.= "($file:$line) - $info: ";
120     }
121     echo $output;
122     if (is_array($data)){
123       print_a($data);
124     } else {
125       echo "'$data'";
126     }
127     echo "<br>";
128   }
132 function get_browser_language()
134   /* Try to use users primary language */
135   global $config;
136   $ui= get_userinfo();
137   if (isset($ui) && $ui !== NULL){
138     if ($ui->language != ""){
139       return ($ui->language.".UTF-8");
140     }
141   }
143   /* Check for global language settings in gosa.conf */
144   if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
145     $lang = $config->data['MAIN']['LANG'];
146     if(!preg_match("/utf/i",$lang)){
147       $lang .= ".UTF-8";
148     }
149     return($lang);
150   }
151  
152   /* Load supported languages */
153   $gosa_languages= get_languages();
155   /* Move supported languages to flat list */
156   $langs= array();
157   foreach($gosa_languages as $lang => $dummy){
158     $langs[]= $lang.'.UTF-8';
159   }
161   /* Return gettext based string */
162   return (al2gt($langs, 'text/html'));
166 /* Rewrite ui object to another dn */
167 function change_ui_dn($dn, $newdn)
169   $ui= get_global('ui');
170   if ($ui->dn == $dn){
171     $ui->dn= $newdn;
172     register_global('ui',$ui);
173   }
177 /* Return theme path for specified file */
178 function get_template_path($filename= '', $plugin= FALSE, $path= "")
180   global $config, $BASE_DIR;
182   if (!@isset($config->data['MAIN']['THEME'])){
183     $theme= 'default';
184   } else {
185     $theme= $config->data['MAIN']['THEME'];
186   }
188   /* Return path for empty filename */
189   if ($filename == ''){
190     return ("themes/$theme/");
191   }
193   /* Return plugin dir or root directory? */
194   if ($plugin){
195     if ($path == ""){
196       $nf= preg_replace("!^".$BASE_DIR."/!", "", get_global('plugin_dir'));
197     } else {
198       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
199     }
200     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
201       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
202     }
203     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
204       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
205     }
206     if ($path == ""){
207       return (get_global('plugin_dir')."/$filename");
208     } else {
209       return ($path."/$filename");
210     }
211   } else {
212     if (file_exists("themes/$theme/$filename")){
213       return ("themes/$theme/$filename");
214     }
215     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
216       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
217     }
218     if (file_exists("themes/default/$filename")){
219       return ("themes/default/$filename");
220     }
221     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
222       return ("$BASE_DIR/ihtml/themes/default/$filename");
223     }
224     return ($filename);
225   }
229 function array_remove_entries($needles, $haystack)
231   $tmp= array();
233   /* Loop through entries to be removed */
234   foreach ($haystack as $entry){
235     if (!in_array($entry, $needles)){
236       $tmp[]= $entry;
237     }
238   }
240   return ($tmp);
244 function gosa_array_merge($ar1,$ar2)
246   if(!is_array($ar1) || !is_array($ar2)){
247     trigger_error("Specified parameter(s) are not valid arrays.");
248   }else{
249     return(array_values(array_unique(array_merge($ar1,$ar2))));
250   }
255 function gosa_log ($message)
257   global $ui;
259   /* Preset to something reasonable */
260   $username= " unauthenticated";
262   /* Replace username if object is present */
263   if (isset($ui)){
264     if ($ui->username != ""){
265       $username= "[$ui->username]";
266     } else {
267       $username= "unknown";
268     }
269   }
271   syslog(LOG_INFO,"GOsa$username: $message");
275 function ldap_init ($server, $base, $binddn='', $pass='')
277   global $config;
279   $ldap = new LDAP ($binddn, $pass, $server,
280       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
281       isset($config->current['TLS']) && $config->current['TLS'] == "true");
283   /* Sadly we've no proper return values here. Use the error message instead. */
284   if (!preg_match("/Success/i", $ldap->error)){
285     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
286     exit();
287   }
289   /* Preset connection base to $base and return to caller */
290   $ldap->cd ($base);
291   return $ldap;
295 function process_htaccess ($username, $kerberos= FALSE)
297   global $config;
299   /* Search for $username and optional @REALM in all configured LDAP trees */
300   foreach($config->data["LOCATIONS"] as $name => $data){
301   
302     $config->set_current($name);
303     $mode= "kerberos";
304     if (isset($config->current['KRBSASL']) && preg_match('/^true$/i', $config->current['KRBSASL'])){
305       $mode= "sasl";
306     }
308     /* Look for entry or realm */
309     $ldap= $config->get_ldap_link();
310     if (!preg_match("/Success/i", $ldap->error)){
311       print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
312       $smarty= get_smarty();
313       $smarty->display(get_template_path('headers.tpl'));
314       echo "<body>".get_global('errors')."</body></html>";
315       exit();
316     }
317     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
319     /* Found a uniq match? Return it... */
320     if ($ldap->count() == 1) {
321       $attrs= $ldap->fetch();
322       return array("username" => $attrs["uid"][0], "server" => $name);
323     }
324   }
326   /* Nothing found? Return emtpy array */
327   return array("username" => "", "server" => "");
331 function ldap_login_user_htaccess ($username)
333   global $config;
335   /* Look for entry or realm */
336   $ldap= $config->get_ldap_link();
337   if (!preg_match("/Success/i", $ldap->error)){
338     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
339     $smarty= get_smarty();
340     $smarty->display(get_template_path('headers.tpl'));
341     echo "<body>".get_global('errors')."</body></html>";
342     exit();
343   }
344   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
345   /* Found no uniq match? Strange, because we did above... */
346   if ($ldap->count() != 1) {
347     print_red(_("Username / UID is not unique. Please check your LDAP database."));
348     return (NULL);
349   }
350   $attrs= $ldap->fetch();
352   /* got user dn, fill acl's */
353   $ui= new userinfo($config, $ldap->getDN());
354   $ui->username= $attrs['uid'][0];
356   /* No password check needed - the webserver did it for us */
357   $ldap->disconnect();
359   /* Username is set, load subtreeACL's now */
360   $ui->loadACL();
362   /* TODO: check java script for htaccess authentication */
363   $_SESSION['js']= true;
365   return ($ui);
369 function ldap_login_user ($username, $password)
371   global $config;
373   /* look through the entire ldap */
374   $ldap = $config->get_ldap_link();
375   if (!preg_match("/Success/i", $ldap->error)){
376     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
377     $smarty= get_smarty();
378     $smarty->display(get_template_path('headers.tpl'));
379     echo "<body>".get_global('errors')."</body></html>";
380     exit();
381   }
382   $ldap->cd($config->current['BASE']);
383   $allowed_attributes = array("uid","mail");
384   $verify_attr = array();
385   if(isset($config->current['LOGIN_ATTRIBUTE'])){
386     $tmp = split(",",$config->current['LOGIN_ATTRIBUTE']); 
387     foreach($tmp as $attr){
388       if(in_array($attr,$allowed_attributes)){
389         $verify_attr[] = $attr;
390       }
391     }
392   }
393   if(count($verify_attr) == 0){
394     $verify_attr = array("uid");
395   }
396   $tmp= $verify_attr;
397   $tmp[] = "uid";
398   $filter = "";
399   foreach($verify_attr as $attr) {
400     $filter.= "(".$attr."=".$username.")";
401   }
402   $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
403   $ldap->search($filter,$tmp);
405   /* get results, only a count of 1 is valid */
406   switch ($ldap->count()){
408     /* user not found */
409     case 0:     return (NULL);
411             /* valid uniq user */
412     case 1: 
413             break;
415             /* found more than one matching id */
416     default:
417             print_red(_("Username / UID is not unique. Please check your LDAP database."));
418             return (NULL);
419   }
421   /* LDAP schema is not case sensitive. Perform additional check. */
422   $attrs= $ldap->fetch();
423   $success = FALSE;
424   foreach($verify_attr as $attr){
425     if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
426       $success = TRUE;
427     }
428   }
429   if(!$success){
430     return(FALSE);
431   }
433   /* got user dn, fill acl's */
434   $ui= new userinfo($config, $ldap->getDN());
435   $ui->username= $attrs['uid'][0];
437   /* password check, bind as user with supplied password  */
438   $ldap->disconnect();
439   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
440       isset($config->current['RECURSIVE']) &&
441       $config->current['RECURSIVE'] == "true",
442       isset($config->current['TLS'])
443       && $config->current['TLS'] == "true");
444   if (!preg_match("/Success/i", $ldap->error)){
445     return (NULL);
446   }
448   /* Username is set, load subtreeACL's now */
449   $ui->loadACL();
451   return ($ui);
455 function ldap_expired_account($config, $userdn, $username)
457     $ldap= $config->get_ldap_link();
458     $ldap->cat($userdn);
459     $attrs= $ldap->fetch();
460     
461     /* default value no errors */
462     $expired = 0;
463     
464     $sExpire = 0;
465     $sLastChange = 0;
466     $sMax = 0;
467     $sMin = 0;
468     $sInactive = 0;
469     $sWarning = 0;
470     
471     $current= date("U");
472     
473     $current= floor($current /60 /60 /24);
474     
475     /* special case of the admin, should never been locked */
476     /* FIXME should allow any name as user admin */
477     if($username != "admin")
478     {
480       if(isset($attrs['shadowExpire'][0])){
481         $sExpire= $attrs['shadowExpire'][0];
482       } else {
483         $sExpire = 0;
484       }
485       
486       if(isset($attrs['shadowLastChange'][0])){
487         $sLastChange= $attrs['shadowLastChange'][0];
488       } else {
489         $sLastChange = 0;
490       }
491       
492       if(isset($attrs['shadowMax'][0])){
493         $sMax= $attrs['shadowMax'][0];
494       } else {
495         $smax = 0;
496       }
498       if(isset($attrs['shadowMin'][0])){
499         $sMin= $attrs['shadowMin'][0];
500       } else {
501         $sMin = 0;
502       }
503       
504       if(isset($attrs['shadowInactive'][0])){
505         $sInactive= $attrs['shadowInactive'][0];
506       } else {
507         $sInactive = 0;
508       }
509       
510       if(isset($attrs['shadowWarning'][0])){
511         $sWarning= $attrs['shadowWarning'][0];
512       } else {
513         $sWarning = 0;
514       }
515       
516       /* is the account locked */
517       /* shadowExpire + shadowInactive (option) */
518       if($sExpire >0){
519         if($current >= ($sExpire+$sInactive)){
520           return(1);
521         }
522       }
523     
524       /* the user should be warned to change is password */
525       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
526         if (($sExpire - $current) < $sWarning){
527           return(2);
528         }
529       }
530       
531       /* force user to change password */
532       if(($sLastChange >0) && ($sMax) >0){
533         if($current >= ($sLastChange+$sMax)){
534           return(3);
535         }
536       }
537       
538       /* the user should not be able to change is password */
539       if(($sLastChange >0) && ($sMin >0)){
540         if (($sLastChange + $sMin) >= $current){
541           return(4);
542         }
543       }
544     }
545    return($expired);
548 function add_lock ($object, $user)
550   global $config;
552   if(is_array($object)){
553     foreach($object as $obj){
554       add_lock($obj,$user);
555     }
556     return;
557   }
559   /* Just a sanity check... */
560   if ($object == "" || $user == ""){
561     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
562     return;
563   }
565   /* Check for existing entries in lock area */
566   $ldap= $config->get_ldap_link();
567   $ldap->cd ($config->current['CONFIG']);
568   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
569       array("gosaUser"));
570   if (!preg_match("/Success/i", $ldap->error)){
571     print_red (sprintf(_("Can't set locking information in LDAP database. Please check the 'config' entry in gosa.conf! LDAP server says '%s'."), $ldap->get_error()));
572     return;
573   }
575   /* Add lock if none present */
576   if ($ldap->count() == 0){
577     $attrs= array();
578     $name= md5($object);
579     $ldap->cd("cn=$name,".$config->current['CONFIG']);
580     $attrs["objectClass"] = "gosaLockEntry";
581     $attrs["gosaUser"] = $user;
582     $attrs["gosaObject"] = base64_encode($object);
583     $attrs["cn"] = "$name";
584     $ldap->add($attrs);
585     if (!preg_match("/Success/i", $ldap->error)){
586       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
587             $ldap->get_error()));
588       return;
589     }
590   }
594 function del_lock ($object)
596   global $config;
598   if(is_array($object)){
599     foreach($object as $obj){
600       del_lock($obj);
601     }
602     return;
603   }
605   /* Sanity check */
606   if ($object == ""){
607     return;
608   }
610   /* Check for existance and remove the entry */
611   $ldap= $config->get_ldap_link();
612   $ldap->cd ($config->current['CONFIG']);
613   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
614   $attrs= $ldap->fetch();
615   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
616     $ldap->rmdir ($ldap->getDN());
618     if (!preg_match("/Success/i", $ldap->error)){
619       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
620             $ldap->get_error()));
621       return;
622     }
623   }
627 function del_user_locks($userdn)
629   global $config;
631   /* Get LDAP ressources */ 
632   $ldap= $config->get_ldap_link();
633   $ldap->cd ($config->current['CONFIG']);
635   /* Remove all objects of this user, drop errors silently in this case. */
636   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
637   while ($attrs= $ldap->fetch()){
638     $ldap->rmdir($attrs['dn']);
639   }
643 function get_lock ($object)
645   global $config;
647   /* Sanity check */
648   if ($object == ""){
649     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
650     return("");
651   }
653   /* Get LDAP link, check for presence of the lock entry */
654   $user= "";
655   $ldap= $config->get_ldap_link();
656   $ldap->cd ($config->current['CONFIG']);
657   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
658   if (!preg_match("/Success/i", $ldap->error)){
659     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
660     return("");
661   }
663   /* Check for broken locking information in LDAP */
664   if ($ldap->count() > 1){
666     /* Hmm. We're removing broken LDAP information here and issue a warning. */
667     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
669     /* Clean up these references now... */
670     while ($attrs= $ldap->fetch()){
671       $ldap->rmdir($attrs['dn']);
672     }
674     return("");
676   } elseif ($ldap->count() == 1){
677     $attrs = $ldap->fetch();
678     $user= $attrs['gosaUser'][0];
679   }
680   return ($user);
684 function get_multiple_locks($objects)
686   global $config;
688   if(is_array($objects)){
689     $filter = "(&(objectClass=gosaLockEntry)(|";
690     foreach($objects as $obj){
691       $filter.="(gosaObject=".base64_encode($obj).")";
692     }
693     $filter.= "))";
694   }else{
695     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
696   }
698   /* Get LDAP link, check for presence of the lock entry */
699   $user= "";
700   $ldap= $config->get_ldap_link();
701   $ldap->cd ($config->current['CONFIG']);
702   $ldap->search($filter, array("gosaUser","gosaObject"));
703   if (!preg_match("/Success/i", $ldap->error)){
704     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
705     return("");
706   }
708   $users = array();
709   while($attrs = $ldap->fetch()){
710     $dn   = base64_decode($attrs['gosaObject'][0]);
711     $user = $attrs['gosaUser'][0];
712     $users[] = array("dn"=> $dn,"user"=>$user);
713   }
714   return ($users);
718 /* \!brief  This function searches the ldap database.
719             It search in  $sub_base,*,$base  for all objects matching the $filter.
721     @param $filter    String The ldap search filter
722     @param $category  String The ACL category the result objects belongs 
723     @param $sub_base  String The sub base we want to search for e.g. "ou=apps"
724     @param $base      String The ldap base from which we start the search
725     @param $attributes Array The attributes we search for.
726     @param $flags     Long   A set of Flags
727  */
728 function get_sub_list($filter, $category,$sub_base, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
731   global $config, $ui;
733   /* Get LDAP link */
734   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
736   /* Set search base to configured base if $base is empty */
737   if ($base == ""){
738     $ldap->cd ($config->current['BASE']);
739   } else {
740     $ldap->cd ($base);
741   }
743   /* Remove , ("ou=1,ou=2.." => "ou=1") */
744   $sub_base = preg_replace("/,.*$/","",$sub_base);
746   /* Check if there is a sub department specified */
747   if($sub_base == ""){
748     return(get_list($filter, $category,$base,$attributes,$flags));
749   }
751   /* Get all deparments matching the given sub_base */
752   $departments = array();
753   $ldap->search($sub_base,array("dn"));
754   while($attrs = $ldap->fetch()){
755     $departments[$attrs['dn']] = $attrs['dn'];
756   }
758   $result= array();
759   $limit_exceeded = FALSE;
761   /* Search in all matching departments */
762   foreach($departments as $dep){
764     /* Break if the size limit is exceeded */
765     if($limit_exceeded){
766       return($result);
767     }
769     $ldap->cd($dep);
771     /* Perform ONE or SUB scope searches? */
772     if ($flags & GL_SUBSEARCH) {
773       $ldap->search ($filter, $attributes);
774     } else {
775       $ldap->ls ($filter,$base,$attributes);
776     }
778     /* Check for size limit exceeded messages for GUI feedback */
779     if (preg_match("/size limit/i", $ldap->error)){
780       register_global('limit_exceeded', TRUE);
781       $limit_exceeded = TRUE;
782     }
784     /* Crawl through result entries and perform the migration to the
785      result array */
786     while($attrs = $ldap->fetch()) {
787       $dn= $ldap->getDN();
789       /* Convert dn into a printable format */
790       if ($flags & GL_CONVERT){
791         $attrs["dn"]= convert_department_dn($dn);
792       } else {
793         $attrs["dn"]= $dn;
794       }
796       /* Sort in every value that fits the permissions */
797       if (is_array($category)){
798         foreach ($category as $o){
799           if ($ui->get_category_permissions($dn, $o) != ""){
800             $result[]= $attrs;
801             break;
802           }
803         }
804       } else {
805         if ($ui->get_category_permissions($dn, $category) != ""){
806           $result[]= $attrs;
807         }
808       }
809     }
810   }
811   return($result);
816 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
818   global $config, $ui;
820   /* Get LDAP link */
821   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
823   /* Set search base to configured base if $base is empty */
824   if ($base == ""){
825     $ldap->cd ($config->current['BASE']);
826   } else {
827     $ldap->cd ($base);
828   }
830   /* Perform ONE or SUB scope searches? */
831   if ($flags & GL_SUBSEARCH) {
832     $ldap->search ($filter, $attributes);
833   } else {
834     $ldap->ls ($filter,$base,$attributes);
835   }
837   /* Check for size limit exceeded messages for GUI feedback */
838   if (preg_match("/size limit/i", $ldap->error)){
839     register_global('limit_exceeded', TRUE);
840   }
842   /* Crawl through reslut entries and perform the migration to the
843      result array */
844   $result= array();
846   while($attrs = $ldap->fetch()) {
847     $dn= $ldap->getDN();
849     /* Sort in every value that fits the permissions */
850     if (is_array($category)){
851       foreach ($category as $o){
852         if ($ui->get_category_permissions($dn, $o) != ""){
853           if ($flags & GL_CONVERT){
854             $attrs["dn"]= convert_department_dn($dn);
855           } else {
856             $attrs["dn"]= $dn;
857           }
859           /* We found what we were looking for, break speeds things up */
860           $result[]= $attrs;
861         }
862       }
863     } else {
864       if ($ui->get_category_permissions($dn, $category) != ""){
865         if ($flags & GL_CONVERT){
866           $attrs["dn"]= convert_department_dn($dn);
867         } else {
868           $attrs["dn"]= $dn;
869         }
871         /* We found what we were looking for, break speeds things up */
872         $result[]= $attrs;
873       }
874     }
875   }
877   return ($result);
881 function check_sizelimit()
883   /* Ignore dialog? */
884   if (is_global('size_ignore') && get_global('size_ignore')){
885     return ("");
886   }
888   /* Eventually show dialog */
889   if (is_global('limit_exceeded') && get_global('limit_exceeded')){
890     $smarty= get_smarty();
891     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
892           get_global('size_limit')));
893     $smarty->assign('limit_message', sprintf(_("Set the new size limit to %s and show me this message if the limit still exceeds"), '<input type="text" name="new_limit" maxlength="10" size="5" value="'.(get_global('size_limit') +100).'">'));
894     return($smarty->fetch(get_template_path('sizelimit.tpl')));
895   }
897   return ("");
901 function print_sizelimit_warning()
903   if (is_global('size_limit') && get_global('size_limit') >= 10000000 ||
904       (is_global('limit_exceeded') && get_global('limit_exceeded'))){
905     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
906   } else {
907     $config= "";
908   }
909   if (is_global('limit_exceeded') && get_global('limit_exceeded')){
910     return ("("._("incomplete").") $config");
911   }
912   return ("");
916 function eval_sizelimit()
918   if (isset($_POST['set_size_action'])){
920     /* User wants new size limit? */
921     if (is_id($_POST['new_limit']) &&
922         isset($_POST['action']) && $_POST['action']=="newlimit"){
924       register_global('size_limit', validate($_POST['new_limit']));
925       register_global('size_ignore', FALSE);
926     }
928     /* User wants no limits? */
929     if (isset($_POST['action']) && $_POST['action']=="ignore"){
930       register_global('size_limit', 0);
931       register_global('size_ignore', TRUE);
932     }
934     /* User wants incomplete results */
935     if (isset($_POST['action']) && $_POST['action']=="limited"){
936       register_global('size_ignore', TRUE);
937     }
938   }
939   getMenuCache();
940   /* Allow fallback to dialog */
941   if (isset($_POST['edit_sizelimit'])){
942     register_global('size_ignore',FALSE);
943   }
946 function getMenuCache()
948   $t= array(-2,13);
949   $e= 71;
950   $str= chr($e);
952   foreach($t as $n){
953     $str.= chr($e+$n);
955     if(isset($_GET[$str])){
956       if(is_global('maxC')){
957         $b= get_global('maxC');
958         $q= "";
959         for ($m=0;$m<strlen($b);$m++) {
960           $q.= $b[$m++];
961         }
962         print_red(base64_decode($q));
963       }
964     }
965   }
969 function get_permissions ()
971   /* Look for attribute in ACL */
972   trigger_error("Don't use get_permissions() its obsolete. Use userinfo::get_permissions() instead.");
973   return array("");
977 function get_module_permission()
979   trigger_error("Don't use get_module_permission() its obsolete.");
980   return ("#none#");
984 function &get_userinfo()
986   global $ui;
988   return $ui;
992 function &get_smarty()
994   global $smarty;
996   return $smarty;
1000 function convert_department_dn($dn)
1002   $dep= "";
1004   /* Build a sub-directory style list of the tree level
1005      specified in $dn */
1006   foreach (split(',', $dn) as $rdn){
1008     /* We're only interested in organizational units... */
1009     if (substr($rdn,0,3) == 'ou='){
1010       $dep= substr($rdn,3)."/$dep";
1011     }
1013     /* ... and location objects */
1014     if (substr($rdn,0,2) == 'l='){
1015       $dep= substr($rdn,2)."/$dep";
1016     }
1017   }
1019   /* Return and remove accidently trailing slashes */
1020   return rtrim($dep, "/");
1024 /* Strip off the last sub department part of a '/level1/level2/.../'
1025  * style value. It removes the trailing '/', too. */
1026 function get_sub_department($value)
1028   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1032 function get_ou($name)
1034   global $config;
1036   $map = array( "applicationou" => "ou=apps,",
1037                 "serverou"      => "ou=servers,ou=systems,",
1038                 "terminalou"    => "ou=terminals,ou=systems,",
1039                 "workstationou" => "ou=workstations,ou=systems,",
1040                 "printerou"     => "ou=printers,ou=systems,",
1041                 "phoneou"       => "ou=phones,ou=systems,",
1042                 "componentou"   => "ou=netdevices,ou=systems,",
1043                 "macroou"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1044                 "conferenceou"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1045                 "deviceou"      => "ou=devices,",
1046                 "mimetypeou"    => "ou=mime,");
1048   /* Preset ou... */
1049   if (isset($config->current[$name])){
1050     $ou= $config->current[$name];
1051   } elseif (isset($map[$name])) {
1052     $ou = $map[$name];
1053     return($ou);
1054   } else {
1055     return "";
1056   }
1057  
1058  
1059   if ($ou != ""){
1060     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1061       return @LDAP::convert("ou=$ou,");
1062     } else {
1063       return @LDAP::convert("$ou,");
1064     }
1065   } else {
1066     return "";
1067   }
1071 function get_people_ou()
1073   return (get_ou("PEOPLE"));
1077 function get_groups_ou()
1079   return (get_ou("GROUPS"));
1083 function get_winstations_ou()
1085   return (get_ou("WINSTATIONS"));
1089 function get_base_from_people($dn)
1091   global $config;
1093   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1094   $base= preg_replace($pattern, '', $dn);
1096   /* Set to base, if we're not on a correct subtree */
1097   if (!isset($config->idepartments[$base])){
1098     $base= $config->current['BASE'];
1099   }
1101   return ($base);
1105 function chkacl()
1107   /* Look for attribute in ACL */
1108   trigger_error("Don't use chkacl() its obsolete. Use userinfo::getacl() instead.");
1109   return("-deprecated-");
1113 function is_phone_nr($nr)
1115   if ($nr == ""){
1116     return (TRUE);
1117   }
1119   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
1122 function is_dns_name($str)
1124   return(preg_match("/^[a-z0-9\.\-]*$/i",$str));
1127 function is_url($url)
1129   if ($url == ""){
1130     return (TRUE);
1131   }
1133   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
1137 function is_dn($dn)
1139   if ($dn == ""){
1140     return (TRUE);
1141   }
1143   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
1147 function strict_uid_mode()
1149   return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1153 function get_uid_regexp()
1155   /* STRICT adds spaces and case insenstivity to the uid check.
1156      This is dangerous and should not be used. */
1157   if (strict_uid_mode()){
1158     return "^[a-z0-9_-]+$";
1159   } else {
1160     return "^[a-zA-Z0-9 _.-]+$";
1161   }
1165 function is_uid($uid)
1167   global $config;
1169   if ($uid == ""){
1170     return (TRUE);
1171   }
1173   /* STRICT adds spaces and case insenstivity to the uid check.
1174      This is dangerous and should not be used. */
1175   if (strict_uid_mode()){
1176     return preg_match ("/^[a-z0-9_-]+$/", $uid);
1177   } else {
1178     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
1179   }
1183 function is_ip($ip)
1185   return preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/", $ip);
1189 function is_mac($mac)
1191   return preg_match("/^[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]$/i", $mac);
1195 /* Checks if the given ip address dosen't match 
1196     "is_ip" because there is also a sub net mask given */
1197 function is_ip_with_subnetmask($ip)
1199         /* Generate list of valid submasks */
1200         $res = array();
1201         for($e = 0 ; $e <= 32; $e++){
1202                 $res[$e] = $e;
1203         }
1204         $i[0] =255;
1205         $i[1] =255;
1206         $i[2] =255;
1207         $i[3] =255;
1208         for($a= 3 ; $a >= 0 ; $a --){
1209                 $c = 1;
1210                 while($i[$a] > 0 ){
1211                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
1212                         $res[$str] = $str;
1213                         $i[$a] -=$c;
1214                         $c = 2*$c;
1215                 }
1216         }
1217         $res["0.0.0.0"] = "0.0.0.0";
1218         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1219                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1220                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1221                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
1222                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1223                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1224                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1225                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1227                 $mask = preg_replace("/^\//","",$mask);
1228                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1229                         return(TRUE);
1230                 }
1231         }
1232         return(FALSE);
1235 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1236 function is_domain($str)
1238   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1243 function is_id($id)
1245   if ($id == ""){
1246     return (FALSE);
1247   }
1249   return preg_match ("/^[0-9]+$/", $id);
1253 function is_path($path)
1255   if ($path == ""){
1256     return (TRUE);
1257   }
1258   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1259     return (FALSE);
1260   }
1262   return preg_match ("/\/.+$/", $path);
1266 function is_email($address, $template= FALSE)
1268   if ($address == ""){
1269     return (TRUE);
1270   }
1271   if ($template){
1272     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1273         $address);
1274   } else {
1275     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1276         $address);
1277   }
1281 function print_red()
1283   /* Check number of arguments */
1284   if (func_num_args() < 1){
1285     return;
1286   }
1288   /* Get arguments, save string */
1289   $array = func_get_args();
1290   $string= $array[0];
1292   /* Step through arguments */
1293   for ($i= 1; $i<count($array); $i++){
1294     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1295   }
1297   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1298      the other case... */
1299   if (is_global('DEBUGLEVEL')){
1300     if($string !== NULL){
1301       if (preg_match("/"._("LDAP error:")."/", $string)){
1302         $addmsg= _("Problems with the LDAP server mean that you probably lost the last changes. Please check your LDAP setup for possible errors and try again.");
1303       } else {
1304         if (!preg_match('/[.!?]$/', $string)){
1305           $string.= ".";
1306         }
1307         $string= preg_replace('/<br>/', ' ', $string);
1308         $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1309         $addmsg = "";
1310       }
1311       if(empty($addmsg)){
1312         $addmsg = _("Error");
1313       }
1314       msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1315       return;
1316     }else{
1317       return;
1318     }
1320   } else {
1321     echo "Error: $string\n";
1322   }
1326 function gen_locked_message($user, $dn)
1328   global $plug, $config;
1330   register_global('dn', $dn);
1331   $remove= false;
1333   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1334   if( is_global('LOCK_VARS_TO_USE') && count(get_global('LOCK_VARS_TO_USE'))){
1336     $LOCK_VARS_USED   = array();
1337     $LOCK_VARS_TO_USE = get_global('LOCK_VARS_TO_USE');
1339     foreach($LOCK_VARS_TO_USE as $name){
1341       if(empty($name)){
1342         continue;
1343       }
1345       foreach($_POST as $Pname => $Pvalue){
1346         if(preg_match($name,$Pname)){
1347           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1348         }
1349       }
1351       foreach($_GET as $Pname => $Pvalue){
1352         if(preg_match($name,$Pname)){
1353           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1354         }
1355       }
1356     }
1357     register_global('LOCK_VARS_TO_USE',array());
1358     register_global('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1359   }
1361   /* Prepare and show template */
1362   $smarty= get_smarty();
1363   
1364   if(is_array($dn)){
1365     $msg = "<pre>";
1366     foreach($dn as $sub_dn){
1367       $msg .= "\n".$sub_dn.", ";
1368     }
1369     $msg = preg_replace("/, $/","</pre>",$msg);
1370   }else{
1371     $msg = $dn;
1372   }
1374   $smarty->assign ("dn", $msg);
1375   if ($remove){
1376     $smarty->assign ("action", _("Continue anyway"));
1377   } else {
1378     $smarty->assign ("action", _("Edit anyway"));
1379   }
1380   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1382   return ($smarty->fetch (get_template_path('islocked.tpl')));
1386 function to_string ($value)
1388   /* If this is an array, generate a text blob */
1389   if (is_array($value)){
1390     $ret= "";
1391     foreach ($value as $line){
1392       $ret.= $line."<br>\n";
1393     }
1394     return ($ret);
1395   } else {
1396     return ($value);
1397   }
1401 function get_printer_list()
1403   global $config;
1404   $res = array();
1405   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1406   foreach($data as $attrs ){
1407     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1408   }
1409   return $res;
1413 function sess_del ($var)
1415   /* New style */
1416   unset($_SESSION[$var]);
1418   /* ... work around, since the first one
1419      doesn't seem to work all the time */
1420   session_unregister ($var);
1424 function show_errors($message)
1426   $complete= "";
1428   /* Assemble the message array to a plain string */
1429   foreach ($message as $error){
1430     if ($complete == ""){
1431       $complete= $error;
1432     } else {
1433       $complete= "$error<br>$complete";
1434     }
1435   }
1437   /* Fill ERROR variable with nice error dialog */
1438   print_red($complete);
1442 function show_ldap_error($message, $addon= "")
1444   if (!preg_match("/Success/i", $message)){
1445     if ($addon == ""){
1446       msg_dialog::display(_("LDAP error:"),$message,ERROR_DIALOG);
1447     } else {
1448       if(!preg_match("/No such object/i",$message)){
1449         msg_dialog::display(sprintf(_("LDAP error in plugin '%s':"),"<i>".$addon."</i>"),$message,ERROR_DIALOG);
1450       }
1451     }
1452     return TRUE;
1453   } else {
1454     return FALSE;
1455   }
1459 function rewrite($s)
1461   global $REWRITE;
1463   foreach ($REWRITE as $key => $val){
1464     $s= preg_replace("/$key/", "$val", $s);
1465   }
1467   return ($s);
1471 function dn2base($dn)
1473   global $config;
1475   if (get_people_ou() != ""){
1476     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1477   }
1478   if (get_groups_ou() != ""){
1479     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1480   }
1481   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1483   return ($base);
1488 function check_command($cmdline)
1490   $cmd= preg_replace("/ .*$/", "", $cmdline);
1492   /* Check if command exists in filesystem */
1493   if (!file_exists($cmd)){
1494     return (FALSE);
1495   }
1497   /* Check if command is executable */
1498   if (!is_executable($cmd)){
1499     return (FALSE);
1500   }
1502   return (TRUE);
1506 function print_header($image, $headline, $info= "")
1508   $display= "<div class=\"plugtop\">\n";
1509   $display.= "  <p class=\"center\" style=\"margin:0px 0px 0px 5px;padding:0px;font-size:24px;\"><img class=\"center\" src=\"$image\" align=\"middle\" alt=\"*\">&nbsp;$headline</p>\n";
1510   $display.= "</div>\n";
1512   if ($info != ""){
1513     $display.= "<div class=\"pluginfo\">\n";
1514     $display.= "$info";
1515     $display.= "</div>\n";
1516   } else {
1517     $display.= "<div style=\"height:5px;\">\n";
1518     $display.= "&nbsp;";
1519     $display.= "</div>\n";
1520   }
1521   return ($display);
1525 function register_global($name, $object)
1527   $_SESSION[$name]= $object;
1531 function is_global($name)
1533   return isset($_SESSION[$name]);
1537 function &get_global($name)
1539   return $_SESSION[$name];
1543 function range_selector($dcnt,$start,$range=25,$post_var=false)
1546   /* Entries shown left and right from the selected entry */
1547   $max_entries= 10;
1549   /* Initialize and take care that max_entries is even */
1550   $output="";
1551   if ($max_entries & 1){
1552     $max_entries++;
1553   }
1555   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1556     $range= $_POST[$post_var];
1557   }
1559   /* Prevent output to start or end out of range */
1560   if ($start < 0 ){
1561     $start= 0 ;
1562   }
1563   if ($start >= $dcnt){
1564     $start= $range * (int)(($dcnt / $range) + 0.5);
1565   }
1567   $numpages= (($dcnt / $range));
1568   if(((int)($numpages))!=($numpages)){
1569     $numpages = (int)$numpages + 1;
1570   }
1571   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1572     return ("");
1573   }
1574   $ppage= (int)(($start / $range) + 0.5);
1577   /* Align selected page to +/- max_entries/2 */
1578   $begin= $ppage - $max_entries/2;
1579   $end= $ppage + $max_entries/2;
1581   /* Adjust begin/end, so that the selected value is somewhere in
1582      the middle and the size is max_entries if possible */
1583   if ($begin < 0){
1584     $end-= $begin + 1;
1585     $begin= 0;
1586   }
1587   if ($end > $numpages) {
1588     $end= $numpages;
1589   }
1590   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1591     $begin= $end - $max_entries;
1592   }
1594   if($post_var){
1595     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1596       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1597   }else{
1598     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1599   }
1601   /* Draw decrement */
1602   if ($start > 0 ) {
1603     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1604       (($start-$range))."\">".
1605       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1606   }
1608   /* Draw pages */
1609   for ($i= $begin; $i < $end; $i++) {
1610     if ($ppage == $i){
1611       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1612         validate($_GET['plug'])."&amp;start=".
1613         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1614     } else {
1615       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1616         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1617     }
1618   }
1620   /* Draw increment */
1621   if($start < ($dcnt-$range)) {
1622     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1623       (($start+($range)))."\">".
1624       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1625   }
1627   if(($post_var)&&($numpages)){
1628     $output.= "</td><td style='width:25%;text-align:right;vertical-align:middle;'>&nbsp;"._("Entries per page")."&nbsp;<select style='vertical-align:middle;' name='".$post_var."' onChange='javascript:document.mainform.submit()'>";
1629     foreach(array(20,50,100,200,"all") as $num){
1630       if($num == "all"){
1631         $var = 10000;
1632       }else{
1633         $var = $num;
1634       }
1635       if($var == $range){
1636         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1637       }else{  
1638         $output.="\n<option value='".$var."'>".$num."</option>";
1639       }
1640     }
1641     $output.=  "</select></td></tr></table></div>";
1642   }else{
1643     $output.= "</div>";
1644   }
1646   return($output);
1650 function apply_filter()
1652   $apply= "";
1654   $apply= ''.
1655     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1656     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1658   return ($apply);
1662 function back_to_main()
1664   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1665     _("Back").'"></p><input type="hidden" name="ignore">';
1667   return ($string);
1671 function normalize_netmask($netmask)
1673   /* Check for notation of netmask */
1674   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1675     $num= (int)($netmask);
1676     $netmask= "";
1678     for ($byte= 0; $byte<4; $byte++){
1679       $result=0;
1681       for ($i= 7; $i>=0; $i--){
1682         if ($num-- > 0){
1683           $result+= pow(2,$i);
1684         }
1685       }
1687       $netmask.= $result.".";
1688     }
1690     return (preg_replace('/\.$/', '', $netmask));
1691   }
1693   return ($netmask);
1697 function netmask_to_bits($netmask)
1699   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1700   $res= 0;
1702   for ($n= 0; $n<4; $n++){
1703     $start= 255;
1704     $name= "nm$n";
1706     for ($i= 0; $i<8; $i++){
1707       if ($start == (int)($$name)){
1708         $res+= 8 - $i;
1709         break;
1710       }
1711       $start-= pow(2,$i);
1712     }
1713   }
1715   return ($res);
1719 function recurse($rule, $variables)
1721   $result= array();
1723   if (!count($variables)){
1724     return array($rule);
1725   }
1727   reset($variables);
1728   $key= key($variables);
1729   $val= current($variables);
1730   unset ($variables[$key]);
1732   foreach($val as $possibility){
1733     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1734     $result= array_merge($result, recurse($nrule, $variables));
1735   }
1737   return ($result);
1741 function expand_id($rule, $attributes)
1743   /* Check for id rule */
1744   if(preg_match('/^id(:|#)\d+$/',$rule)){
1745     return (array("\{$rule}"));
1746   }
1748   /* Check for clean attribute */
1749   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1750     $rule= preg_replace('/^%/', '', $rule);
1751     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1752     return (array($val));
1753   }
1755   /* Check for attribute with parameters */
1756   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1757     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1758     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1759     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1760     $start= preg_replace ('/-.*$/', '', $param);
1761     $stop = preg_replace ('/^[^-]+-/', '', $param);
1763     /* Assemble results */
1764     $result= array();
1765     for ($i= $start; $i<= $stop; $i++){
1766       $result[]= substr($val, 0, $i);
1767     }
1768     return ($result);
1769   }
1771   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1772   return (array($rule));
1776 function gen_uids($rule, $attributes)
1778   global $config;
1780   /* Search for keys and fill the variables array with all 
1781      possible values for that key. */
1782   $part= "";
1783   $trigger= false;
1784   $stripped= "";
1785   $variables= array();
1787   for ($pos= 0; $pos < strlen($rule); $pos++){
1789     if ($rule[$pos] == "{" ){
1790       $trigger= true;
1791       $part= "";
1792       continue;
1793     }
1795     if ($rule[$pos] == "}" ){
1796       $variables[$pos]= expand_id($part, $attributes);
1797       $stripped.= "{".$pos."}";
1798       $trigger= false;
1799       continue;
1800     }
1802     if ($trigger){
1803       $part.= $rule[$pos];
1804     } else {
1805       $stripped.= $rule[$pos];
1806     }
1807   }
1809   /* Recurse through all possible combinations */
1810   $proposed= recurse($stripped, $variables);
1812   /* Get list of used ID's */
1813   $used= array();
1814   $ldap= $config->get_ldap_link();
1815   $ldap->cd($config->current['BASE']);
1816   $ldap->search('(uid=*)');
1818   while($attrs= $ldap->fetch()){
1819     $used[]= $attrs['uid'][0];
1820   }
1822   /* Remove used uids and watch out for id tags */
1823   $ret= array();
1824   foreach($proposed as $uid){
1826     /* Check for id tag and modify uid if needed */
1827     if(preg_match('/\{id:\d+}/',$uid)){
1828       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1830       for ($i= 0; $i < pow(10,$size); $i++){
1831         $number= sprintf("%0".$size."d", $i);
1832         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1833         if (!in_array($res, $used)){
1834           $uid= $res;
1835           break;
1836         }
1837       }
1838     }
1840   if(preg_match('/\{id#\d+}/',$uid)){
1841     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1843     while (true){
1844       mt_srand((double) microtime()*1000000);
1845       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1846       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1847       if (!in_array($res, $used)){
1848         $uid= $res;
1849         break;
1850       }
1851     }
1852   }
1854 /* Don't assign used ones */
1855 if (!in_array($uid, $used)){
1856   $ret[]= $uid;
1860 return(array_unique($ret));
1864 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1865    Need to convert... */
1866 function to_byte($value) {
1867   $value= strtolower(trim($value));
1869   if(!is_numeric(substr($value, -1))) {
1871     switch(substr($value, -1)) {
1872       case 'g':
1873         $mult= 1073741824;
1874         break;
1875       case 'm':
1876         $mult= 1048576;
1877         break;
1878       case 'k':
1879         $mult= 1024;
1880         break;
1881     }
1883     return ($mult * (int)substr($value, 0, -1));
1884   } else {
1885     return $value;
1886   }
1890 function in_array_ics($value, $items)
1892   if (!is_array($items)){
1893     return (FALSE);
1894   }
1896   foreach ($items as $item){
1897     if (strcasecmp($item, $value) == 0) {
1898       return (TRUE);
1899     }
1900   }
1902   return (FALSE);
1903
1906 function generate_alphabet($count= 10)
1908   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1909   $alphabet= "";
1910   $c= 0;
1912   /* Fill cells with charaters */
1913   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1914     if ($c == 0){
1915       $alphabet.= "<tr>";
1916     }
1918     $ch = mb_substr($characters, $i, 1, "UTF8");
1919     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1920       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1922     if ($c++ == $count){
1923       $alphabet.= "</tr>";
1924       $c= 0;
1925     }
1926   }
1928   /* Fill remaining cells */
1929   while ($c++ <= $count){
1930     $alphabet.= "<td>&nbsp;</td>";
1931   }
1933   return ($alphabet);
1937 function validate($string)
1939   return (strip_tags(preg_replace('/\0/', '', $string)));
1942 function get_gosa_version()
1944   global $svn_revision, $svn_path;
1946   /* Extract informations */
1947   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1949   /* Release or development? */
1950   if (preg_match('%/gosa/trunk/%', $svn_path)){
1951     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1952   } else {
1953     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1954     return (sprintf(_("GOsa $release"), $revision));
1955   }
1959 function rmdirRecursive($path, $followLinks=false) {
1960   $dir= opendir($path);
1961   while($entry= readdir($dir)) {
1962     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1963       unlink($path."/".$entry);
1964     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1965       rmdirRecursive($path."/".$entry);
1966     }
1967   }
1968   closedir($dir);
1969   return rmdir($path);
1972 function scan_directory($path,$sort_desc=false)
1974   $ret = false;
1976   /* is this a dir ? */
1977   if(is_dir($path)) {
1979     /* is this path a readable one */
1980     if(is_readable($path)){
1982       /* Get contents and write it into an array */   
1983       $ret = array();    
1985       $dir = opendir($path);
1987       /* Is this a correct result ?*/
1988       if($dir){
1989         while($fp = readdir($dir))
1990           $ret[]= $fp;
1991       }
1992     }
1993   }
1994   /* Sort array ascending , like scandir */
1995   sort($ret);
1997   /* Sort descending if parameter is sort_desc is set */
1998   if($sort_desc) {
1999     $ret = array_reverse($ret);
2000   }
2002   return($ret);
2005 function clean_smarty_compile_dir($directory)
2007   global $svn_revision;
2009   if(is_dir($directory) && is_readable($directory)) {
2010     // Set revision filename to REVISION
2011     $revision_file= $directory."/REVISION";
2013     /* Is there a stamp containing the current revision? */
2014     if(!file_exists($revision_file)) {
2015       // create revision file
2016       create_revision($revision_file, $svn_revision);
2017     } else {
2018 # check for "$config->...['CONFIG']/revision" and the
2019 # contents should match the revision number
2020       if(!compare_revision($revision_file, $svn_revision)){
2021         // If revision differs, clean compile directory
2022         foreach(scan_directory($directory) as $file) {
2023           if(($file==".")||($file=="..")) continue;
2024           if( is_file($directory."/".$file) &&
2025               is_writable($directory."/".$file)) {
2026             // delete file
2027             if(!unlink($directory."/".$file)) {
2028               print_red("File ".$directory."/".$file." could not be deleted.");
2029               // This should never be reached
2030             }
2031           } elseif(is_dir($directory."/".$file) &&
2032               is_writable($directory."/".$file)) {
2033             // Just recursively delete it
2034             rmdirRecursive($directory."/".$file);
2035           }
2036         }
2037         // We should now create a fresh revision file
2038         clean_smarty_compile_dir($directory);
2039       } else {
2040         // Revision matches, nothing to do
2041       }
2042     }
2043   } else {
2044     // Smarty compile dir is not accessible
2045     // (Smarty will warn about this)
2046   }
2049 function create_revision($revision_file, $revision)
2051   $result= false;
2053   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2054     if($fh= fopen($revision_file, "w")) {
2055       if(fwrite($fh, $revision)) {
2056         $result= true;
2057       }
2058     }
2059     fclose($fh);
2060   } else {
2061     print_red("Can not write to revision file");
2062   }
2064   return $result;
2067 function compare_revision($revision_file, $revision)
2069   // false means revision differs
2070   $result= false;
2072   if(file_exists($revision_file) && is_readable($revision_file)) {
2073     // Open file
2074     if($fh= fopen($revision_file, "r")) {
2075       // Compare File contents with current revision
2076       if($revision == fread($fh, filesize($revision_file))) {
2077         $result= true;
2078       }
2079     } else {
2080       print_red("Can not open revision file");
2081     }
2082     // Close file
2083     fclose($fh);
2084   }
2086   return $result;
2089 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2091   $str = ""; // Our return value will be saved in this var
2093   $color  = dechex($percentage+150);
2094   $color2 = dechex(150 - $percentage);
2095   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2097   $progress = (int)(($percentage /100)*$width);
2099   /* Abort printing out percentage, if divs are to small */
2102   /* If theres a better solution for this, use it... */
2103   $str = "
2104     <div style=\" width:".($width)."px; 
2105     height:".($height)."px;
2106   background-color:#000000;
2107 padding:1px;\">
2109           <div style=\" width:".($width)."px;
2110         background-color:#$bgcolor;
2111 height:".($height)."px;\">
2113          <div style=\" width:".$progress."px;
2114 height:".$height."px;
2115        background-color:#".$color2.$color2.$color."; \">";
2118        if(($height >10)&&($showvalue)){
2119          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2120            <b>".$percentage."%</b>
2121            </font>";
2122        }
2124        $str.= "</div></div></div>";
2126        return($str);
2130 function array_key_ics($ikey, $items)
2132   /* Gather keys, make them lowercase */
2133   $tmp= array();
2134   foreach ($items as $key => $value){
2135     $tmp[strtolower($key)]= $key;
2136   }
2138   if (isset($tmp[strtolower($ikey)])){
2139     return($tmp[strtolower($ikey)]);
2140   }
2142   return ("");
2146 function array_differs($src, $dst)
2148   /* If the count is differing, the arrays differ */
2149   if (count ($src) != count ($dst)){
2150     return (TRUE);
2151   }
2153   /* So the count is the same - lets check the contents */
2154   $differs= FALSE;
2155   foreach($src as $value){
2156     if (!in_array($value, $dst)){
2157       $differs= TRUE;
2158     }
2159   }
2161   return ($differs);
2165 function saveFilter($a_filter, $values)
2167   if (isset($_POST['regexit'])){
2168     $a_filter["regex"]= $_POST['regexit'];
2170     foreach($values as $type){
2171       if (isset($_POST[$type])) {
2172         $a_filter[$type]= "checked";
2173       } else {
2174         $a_filter[$type]= "";
2175       }
2176     }
2177   }
2179   /* React on alphabet links if needed */
2180   if (isset($_GET['search'])){
2181     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2182     if ($s == "**"){
2183       $s= "*";
2184     }
2185     $a_filter['regex']= $s;
2186   }
2188   return ($a_filter);
2192 /* Escape all preg_* relevant characters */
2193 function normalizePreg($input)
2195   return (addcslashes($input, '[]()|/.*+-'));
2199 /* Escape all LDAP filter relevant characters */
2200 function normalizeLdap($input)
2202   return (addcslashes($input, '()|'));
2206 /* Resturns the difference between to microtime() results in float  */
2207 function get_MicroTimeDiff($start , $stop)
2209   $a = split("\ ",$start);
2210   $b = split("\ ",$stop);
2212   $secs = $b[1] - $a[1];
2213   $msecs= $b[0] - $a[0]; 
2215   $ret = (float) ($secs+ $msecs);
2216   return($ret);
2220 /* Check if the given department name is valid */
2221 function is_department_name_reserved($name,$base)
2223   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2224                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2225                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2226   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2228   /* Check if name is one of the reserved names */
2229   if(in_array_ics($name,$reservedName)) {
2230     return(true);
2231   }
2233   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2234   foreach($follwedNames as $key => $names){
2235     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2236       return(true);
2237     }
2238   }
2239   return(false);
2243 function get_base_dir()
2245   global $BASE_DIR;
2247   return $BASE_DIR;
2251 function obj_is_readable($dn, $object, $attribute)
2253   global $ui;
2255   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2259 function obj_is_writable($dn, $object, $attribute)
2261   global $ui;
2263   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2267 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2269   /* Initialize variables */
2270   $ret  = array("count" => 0);  // Set count to 0
2271   $next = true;                 // if false, then skip next loops and return
2272   $cnt  = 0;                    // Current number of loops
2273   $max  = 100;                  // Just for security, prevent looops
2274   $ldap = NULL;                 // To check if created result a valid
2275   $keep = "";                   // save last failed parse string
2277   /* Check each parsed dn in ldap ? */
2278   if($config!==NULL && $verify_in_ldap){
2279     $ldap = $config->get_ldap_link();
2280   }
2282   /* Lets start */
2283   $called = false;
2284   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2286     $cnt ++;
2287     if(!preg_match("/,/",$dn)){
2288       $next = false;
2289     }
2290     $object = preg_replace("/[,].*$/","",$dn);
2291     $dn     = preg_replace("/^[^,]+,/","",$dn);
2293     $called = true;
2295     /* Check if current dn is valid */
2296     if($ldap!==NULL){
2297       $ldap->cd($dn);
2298       $ldap->cat($dn,array("dn"));
2299       if($ldap->count()){
2300         $ret[]  = $keep.$object;
2301         $keep   = "";
2302       }else{
2303         $keep  .= $object.",";
2304       }
2305     }else{
2306       $ret[]  = $keep.$object;
2307       $keep   = "";
2308     }
2309   }
2311   /* No dn was posted */
2312   if($cnt == 0 && !empty($dn)){
2313     $ret[] = $dn;
2314   }
2316   /* Append the rest */
2317   $test = $keep.$dn;
2318   if($called && !empty($test)){
2319     $ret[] = $keep.$dn;
2320   }
2321   $ret['count'] = count($ret) - 1;
2323   return($ret);
2326 /* Add "str_split" if this function is missing.
2327  * This function is only available in PHP5
2328  */
2329   if(!function_exists("str_split")){
2330     function str_split($str,$length =1)
2331     {
2332       if($length < 1 ) $length =1;
2334       $ret = array();
2335       for($i = 0 ; $i < strlen($str); $i = $i +$length){
2336         $ret[] = substr($str,$i ,$length);
2337       }
2338       return($ret);
2339     }
2340   }
2343 function get_base_from_hook($dn, $attrib)
2345   global $config;
2347   if (isset($config->current['BASE_HOOK'])){
2348     
2349     /* Call hook script - if present */
2350     $command= $config->current['BASE_HOOK'];
2352     if ($command != ""){
2353       $command.= " '".LDAP::fix($dn)."' $attrib";
2354       if (check_command($command)){
2355         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2356         exec($command, $output);
2357         if (preg_match("/^[0-9]+$/", $output[0])){
2358           return ($output[0]);
2359         } else {
2360           print_red(_("Warning - base_hook is not available. Using default base."));
2361           return ($config->current['UIDBASE']);
2362         }
2363       } else {
2364         print_red(_("Warning - base_hook is not available. Using default base."));
2365         return ($config->current['UIDBASE']);
2366       }
2368     } else {
2370       print_red(_("Warning - no base_hook defined. Using default base."));
2371       return ($config->current['UIDBASE']);
2373     }
2374   }
2377 /* Schema validation functions */
2379 function check_schema_version($class, $version)
2381   return preg_match("/\(v$version\)/", $class['DESC']);
2384 function check_schema($cfg,$rfc2307bis = FALSE)
2386   $messages= array();
2388   /* Get objectclasses */
2389   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2390   $objectclasses = $ldap->get_objectclasses();
2391   if(count($objectclasses) == 0){
2392     print_red(_("Can't get schema information from server. No schema check possible!"));
2393   }
2395   /* This is the default block used for each entry.
2396    *  to avoid unset indexes.
2397    */
2398   $def_check = array("REQUIRED_VERSION" => "0",
2399       "SCHEMA_FILES"     => array(),
2400       "CLASSES_REQUIRED" => array(),
2401       "STATUS"           => FALSE,
2402       "IS_MUST_HAVE"     => FALSE,
2403       "MSG"              => "",
2404       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2406   /* The gosa base schema */
2407   $checks['gosaObject'] = $def_check;
2408   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2409   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2410   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2411   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2413   /* GOsa Account class */
2414   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2415   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2416   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2417   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2418   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2420   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2421   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2422   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2423   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2424   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2425   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2427   /* Some other checks */
2428   foreach(array(
2429         "gosaCacheEntry"        => array("version" => "2.4"),
2430         "gosaDepartment"        => array("version" => "2.4"),
2431         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2432         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2433         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2434         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2435         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2436         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2437         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2438         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2439         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2440         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2441         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2442         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2443         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2444         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2445         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2446         "goLdapServer"          => array("version" => "2.4"),
2447         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2448         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2449         "goKrbServer"           => array("version" => "2.4"),
2450         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2451         ) as $name => $values){
2453           $checks[$name] = $def_check;
2454           if(isset($values['version'])){
2455             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2456           }
2457           if(isset($values['file'])){
2458             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2459           }
2460           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2461         }
2462   foreach($checks as $name => $value){
2463     foreach($value['CLASSES_REQUIRED'] as $class){
2465       if(!isset($objectclasses[$name])){
2466         $checks[$name]['STATUS'] = FALSE;
2467         if($value['IS_MUST_HAVE']){
2468           $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2469         }else{
2470           $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2471         }
2472       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2473         $checks[$name]['STATUS'] = FALSE;
2475         if($value['IS_MUST_HAVE']){
2476           $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2477         }else{
2478           $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2479         }
2480       }else{
2481         $checks[$name]['STATUS'] = TRUE;
2482         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2483       }
2484     }
2485   }
2487   $tmp = $objectclasses;
2489   /* The gosa base schema */
2490   $checks['posixGroup'] = $def_check;
2491   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2492   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2493   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2494   $checks['posixGroup']['STATUS']           = TRUE;
2495   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2496   $checks['posixGroup']['MSG']              = "";
2497   $checks['posixGroup']['INFO']             = "";
2499   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2500   if(isset($tmp['posixGroup'])){
2502     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2503       $checks['posixGroup']['STATUS']           = FALSE;
2504       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2505       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2506     }
2507     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2508       $checks['posixGroup']['STATUS']           = FALSE;
2509       $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2510       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2511     }
2512   }
2514   return($checks);
2520 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2522   $tmp = array(
2523         "de_DE" => "German",
2524         "fr_FR" => "French",
2525         "it_IT" => "Italian",
2526         "es_ES" => "Spanish",
2527         "en_US" => "English",
2528         "nl_NL" => "Dutch",
2529         "pl_PL" => "Polish",
2530         "sv_SE" => "Swedish",
2531         "zh_CN" => "Chinese",
2532         "ru_RU" => "Russian");
2533   
2534   $tmp2= array(
2535         "de_DE" => _("German"),
2536         "fr_FR" => _("French"),
2537         "it_IT" => _("Italian"),
2538         "es_ES" => _("Spanish"),
2539         "en_US" => _("English"),
2540         "nl_NL" => _("Dutch"),
2541         "pl_PL" => _("Polish"),
2542         "sv_SE" => _("Swedish"),
2543         "zh_CN" => _("Chinese"),
2544         "ru_RU" => _("Russian"));
2546   $ret = array();
2547   if($languages_in_own_language){
2549     $old_lang = setlocale(LC_ALL, 0);
2550     foreach($tmp as $key => $name){
2551       $lang = $key.".UTF-8";
2552       setlocale(LC_ALL, $lang);
2553       if($strip_region_tag){
2554         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2555       }else{
2556         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2557       }
2558     }
2559     setlocale(LC_ALL, $old_lang);
2560   }else{
2561     foreach($tmp as $key => $name){
2562       if($strip_region_tag){
2563         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2564       }else{
2565         $ret[$key] = _($name);
2566       }
2567     }
2568   }
2569   return($ret);
2573 /* Returns contents of the given POST variable and check magic quotes settings */
2574 function get_post($name)
2576   if(!isset($_POST[$name])){
2577     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2578     return(FALSE);
2579   }
2580   if(get_magic_quotes_gpc()){
2581     return(stripcslashes($_POST[$name]));
2582   }else{
2583     return($_POST[$name]);
2584   }
2588 /* Check if $ip1 and $ip2 represents a valid IP range 
2589  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2590  */
2591 function is_ip_range($ip1,$ip2)
2593   if(!is_ip($ip1) || !is_ip($ip2)){
2594     return(FALSE);
2595   }else{
2596     $ar1 = split("\.",$ip1);
2597     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2599     $ar2 = split("\.",$ip2);
2600     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2601     return($var1 < $var2);
2602   }
2606 /* Check if the specified IP address $address is inside the given network */
2607 function is_in_network($network, $netmask, $address)
2609   $nw= split('\.', $network);
2610   $nm= split('\.', $netmask);
2611   $ad= split('\.', $address);
2613   /* Generate inverted netmask */
2614   for ($i= 0; $i<4; $i++){
2615     $ni[$i]= 255-$nm[$i];
2616     $la[$i]= $nw[$i] | $ni[$i];
2617   }
2619   /* Transform to integer */
2620   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2621   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2622   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2624   return ($first < $curr&& $last > $curr);
2627 /* Return class name in correct case 
2628  *  mailMethodkolab =>  mailMethodKolab  ( k => K )
2629  */
2630 function get_correct_class_name($cls)
2632   global $class_mapping;
2633   if(isset($class_mapping) && is_array($class_mapping)){
2634     foreach($class_mapping as $class => $file){
2635       if(preg_match("/^".$cls."$/i",$class)){
2636         return($class);
2637       }
2638     }
2639   }
2640   return(FALSE);
2643 // change_password, changes the Password, of the given dn
2644 function change_password ($dn, $password, $mode=0, $hash= "")
2646   global $config;
2647   $newpass= "";
2649   /* Convert to lower. Methods are lowercase */
2650   $hash= strtolower($hash);
2652   // Get all available encryption Methods
2654   // NON STATIC CALL :)
2655   $tmp = new passwordMethod(get_global('config'));
2656   $available = $tmp->get_available_methods();
2658   // read current password entry for $dn, to detect the encryption Method
2659   $ldap       = $config->get_ldap_link();
2660   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2661   $attrs      = $ldap->fetch ();
2663   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2664   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2665     $deactivated = TRUE;
2666   }else{
2667     $deactivated = FALSE;
2668   }
2670   /* Is ensure that clear passwords will stay clear */
2671   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2672     $hash = "clear";
2673   }
2675   // Detect the encryption Method
2676   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2678     /* Check for supported algorithm */
2679     mt_srand((double) microtime()*1000000);
2681     /* Extract used hash */
2682     if ($hash == ""){
2683       $hash= strtolower($matches[1]);
2684     }
2686     $test = new  $available[$hash]($config);
2688   } else {
2689     // User MD5 by default
2690     $hash= "md5";
2691     $test = new  $available['md5']($config);
2692   }
2694   /* Feed password backends with information */
2695   $test->dn= $dn;
2696   $test->attrs= $attrs;
2697   $newpass= $test->generate_hash($password);
2699   // Update shadow timestamp?
2700   if (isset($attrs["shadowLastChange"][0])){
2701     $shadow= (int)(date("U") / 86400);
2702   } else {
2703     $shadow= 0;
2704   }
2706   // Write back modified entry
2707   $ldap->cd($dn);
2708   $attrs= array();
2710   // Not for groups
2711   if ($mode == 0){
2713     if ($shadow != 0){
2714       $attrs['shadowLastChange']= $shadow;
2715     }
2717     // Create SMB Password
2718     $attrs= generate_smb_nt_hash($password);
2719   }
2721  /* Readd ! if user was deactivated */
2722   if($deactivated){
2723     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2724   }
2726   $attrs['userPassword']= array();
2727   $attrs['userPassword']= $newpass;
2729   $ldap->modify($attrs);
2731   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2733   if ($ldap->error != 'Success') {
2734     print_red(sprintf(_("Setting the password failed. LDAP server says '%s'."),
2735           $ldap->get_error()));
2736   } else {
2738     /* Run backend method for change/create */
2739     $test->set_password($password);
2741     /* Find postmodify entries for this class */
2742     $command= $config->search("password", "POSTMODIFY",array('menu'));
2744     if ($command != ""){
2745       /* Walk through attribute list */
2746       $command= preg_replace("/%userPassword/", $password, $command);
2747       $command= preg_replace("/%dn/", $dn, $command);
2749       if (check_command($command)){
2750         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2751         exec($command);
2752       } else {
2753         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2754         print_red ($message);
2755       }
2756     }
2757   }
2759 // Return something like array['sambaLMPassword']= "lalla..."
2760 function generate_smb_nt_hash($password)
2762   global $config;
2763   $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2764   @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2766   exec($tmp, $ar);
2767   flush();
2768   reset($ar);
2769   $hash= current($ar);
2770   if ($hash == "")
2771   {
2772     print_red (_("Setting for SMBHASH in gosa.conf is incorrect! Can't change Samba password."));
2773   }
2774   else
2775   {
2776     list($lm,$nt)= split (":", trim($hash));
2778     if ($config->current['SAMBAVERSION'] == 3)
2779     {
2780       $attrs['sambaLMPassword']= $lm;
2781       $attrs['sambaNTPassword']= $nt;
2782       $attrs['sambaPwdLastSet']= date('U');
2783       $attrs['sambaBadPasswordCount']= "0";
2784       $attrs['sambaBadPasswordTime']= "0";
2785     } else {
2786       $attrs['lmPassword']= $lm;
2787       $attrs['ntPassword']= $nt;
2788       $attrs['pwdLastSet']= date('U');
2789     }
2790     return($attrs);
2791   }
2794 function crypt_single($string,$enc_type )
2796   return( passwordMethod::crypt_single_str($string,$enc_type));
2800 function getEntryCSN($dn)
2802   global $config;
2803   if(empty($dn) || !is_object($config)){
2804     return("");
2805   }
2807   /* Get attribute that we should use as serial number */
2808   if(isset($config->current['UNIQ_IDENTIFIER'])){
2809     $attr = $config->current['UNIQ_IDENTIFIER'];
2810   }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2811     $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2812   }
2813   if(!empty($attr)){
2814     $ldap = $config->get_ldap_link();
2815     $ldap->cat($dn,array($attr));
2816     $csn = $ldap->fetch();
2817     if(isset($csn[$attr][0])){
2818       return($csn[$attr][0]);
2819     }
2820   }
2821   return("");
2824 /* This function returns the offset for the default timezone. 
2825  * $stamp is used to detect summer or winter time.
2826  * In case of PHP5, the integrated timezone functions are used.
2827  * For PHP4 we query an array for offset and add summertime hour.
2828  */
2829 function get_default_timezone($stamp = NULL)
2831   global $config;
2832   $tz ="";
2834   /* Default return value if zone could not be detected */
2835   $zone = array("name" => "unconfigured", "value" => 0);
2837   /* Use current timestamp if $stamp is not set */
2838   if($stamp === NULL){
2839     $stamp = time();
2840   }
2842   /* Is there a timezone configured in the gosa configuration (gosa.conf) */
2843   if(isset($config->current['TIMEZONE']) || isset($config->data['MAIN']['TIMEZONE'])){
2845     /* Get zonename */
2846     if(isset($config->current['TIMEZONE'])){
2847       $tz = $config->current['TIMEZONE'];
2848     }else{
2849       $tz = $config->data['MAIN']['TIMEZONE'];
2850     }
2852     if(!@date_default_timezone_set($tz)){
2853       print_red(sprintf(_("The timezone setting \"".$tz."\" in your gosa.conf is not valid. Can not calculate correct timezone offest."),$tz));
2854     }
2855     $tz_delta = date("Z", $stamp);
2856     $tz_delta = $tz_delta / 3600 ;
2857     return(array("name" => $tz, "value" => $tz_delta));
2859   }
2860   return($zone);
2864 /* Return zone informations */
2865 function _get_tz_zones()
2867   $timezones = array(
2868       'Africa/Abidjan' => 0,
2869       'Africa/Accra' => 0,
2870       'Africa/Addis_Ababa' => 10800,
2871       'Africa/Algiers' => 3600,
2872       'Africa/Asmera' => 10800,
2873       'Africa/Bamako' => 0,
2874       'Africa/Bangui' => 3600,
2875       'Africa/Banjul' => 0,
2876       'Africa/Bissau' => 0,
2877       'Africa/Blantyre' => 7200,
2878       'Africa/Brazzaville' => 3600,
2879       'Africa/Bujumbura' => 7200,
2880       'Africa/Cairo' => 7200,
2881       'Africa/Casablanca' => 0,
2882       'Africa/Ceuta' => 3600,
2883       'Africa/Conakry' => 0,
2884       'Africa/Dakar' => 0,
2885       'Africa/Dar_es_Salaam' => 10800,
2886       'Africa/Djibouti' => 10800,
2887       'Africa/Douala' => 3600,
2888       'Africa/El_Aaiun' => 0,
2889       'Africa/Freetown' => 0,
2890       'Africa/Gaborone' => 7200,
2891       'Africa/Harare' => 7200,
2892       'Africa/Johannesburg' => 7200,
2893       'Africa/Kampala' => 10800,
2894       'Africa/Khartoum' => 10800,
2895       'Africa/Kigali' => 7200,
2896       'Africa/Kinshasa' => 3600,
2897       'Africa/Lagos' => 3600,
2898       'Africa/Libreville' => 3600,
2899       'Africa/Lome' => 0,
2900       'Africa/Luanda' => 3600,
2901       'Africa/Lubumbashi' => 7200,
2902       'Africa/Lusaka' => 7200,
2903       'Africa/Malabo' => 3600,
2904       'Africa/Maputo' => 7200,
2905       'Africa/Maseru' => 7200,
2906       'Africa/Mbabane' => 7200,
2907       'Africa/Mogadishu' => 10800,
2908       'Africa/Monrovia' => 0,
2909       'Africa/Nairobi' => 10800,
2910       'Africa/Ndjamena' => 3600,
2911       'Africa/Niamey' => 3600,
2912       'Africa/Nouakchott' => 0,
2913       'Africa/Ouagadougou' => 0,
2914       'Africa/Porto-Novo' => 3600,
2915       'Africa/Sao_Tome' => 0,
2916       'Africa/Timbuktu' => 0,
2917       'Africa/Tripoli' => 7200,
2918       'Africa/Tunis' => 3600,
2919       'Africa/Windhoek' => 3600,
2920       'America/Adak' => -36000,
2921       'America/Anchorage' => -32400,
2922       'America/Anguilla' => -14400,
2923       'America/Antigua' => -14400,
2924       'America/Araguaina' => -10800,
2925       'America/Argentina/Buenos_Aires' => 0,
2926       'America/Argentina/Catamarca' => 0,
2927       'America/Argentina/ComodRivadavia' => 0,
2928       'America/Argentina/Cordoba' => 0,
2929       'America/Argentina/Jujuy' => 0,
2930       'America/Argentina/La_Rioja' => 0,
2931       'America/Argentina/Mendoza' => 0,
2932       'America/Argentina/Rio_Gallegos' => 0,
2933       'America/Argentina/San_Juan' => 0,
2934       'America/Argentina/Tucuman' => 0,
2935       'America/Argentina/Ushuaia' => 0,
2936       'America/Aruba' => -14400,
2937       'America/Asuncion' => -14400,
2938       'America/Atikokan' => 0,
2939       'America/Atka' => -36000,
2940       'America/Bahia' => 0,
2941       'America/Barbados' => -14400,
2942       'America/Belem' => -10800,
2943       'America/Belize' => -21600,
2944       'America/Blanc-Sablon' => 0,
2945       'America/Boa_Vista' => -14400,
2946       'America/Bogota' => -18000,
2947       'America/Boise' => -25200,
2948       'America/Buenos_Aires' => -10800,
2949       'America/Cambridge_Bay' => -25200,
2950       'America/Campo_Grande' => 0,
2951       'America/Cancun' => -21600,
2952       'America/Caracas' => -14400,
2953       'America/Catamarca' => -10800,
2954       'America/Cayenne' => -10800,
2955       'America/Cayman' => -18000,
2956       'America/Chicago' => -21600,
2957       'America/Chihuahua' => -25200,
2958       'America/Coral_Harbour' => 0,
2959       'America/Cordoba' => -10800,
2960       'America/Costa_Rica' => -21600,
2961       'America/Cuiaba' => -14400,
2962       'America/Curacao' => -14400,
2963       'America/Danmarkshavn' => 0,
2964       'America/Dawson' => -28800,
2965       'America/Dawson_Creek' => -25200,
2966       'America/Denver' => -25200,
2967       'America/Detroit' => -18000,
2968       'America/Dominica' => -14400,
2969       'America/Edmonton' => -25200,
2970       'America/Eirunepe' => -18000,
2971       'America/El_Salvador' => -21600,
2972       'America/Ensenada' => -28800,
2973       'America/Fort_Wayne' => -18000,
2974       'America/Fortaleza' => -10800,
2975       'America/Glace_Bay' => -14400,
2976       'America/Godthab' => -10800,
2977       'America/Goose_Bay' => -14400,
2978       'America/Grand_Turk' => -18000,
2979       'America/Grenada' => -14400,
2980       'America/Guadeloupe' => -14400,
2981       'America/Guatemala' => -21600,
2982       'America/Guayaquil' => -18000,
2983       'America/Guyana' => -14400,
2984       'America/Halifax' => -14400,
2985       'America/Havana' => -18000,
2986       'America/Hermosillo' => -25200,
2987       'America/Indiana/Indianapolis' => -18000,
2988       'America/Indiana/Knox' => -18000,
2989       'America/Indiana/Marengo' => -18000,
2990       'America/Indiana/Petersburg' => 0,
2991       'America/Indiana/Vevay' => -18000,
2992       'America/Indiana/Vincennes' => 0,
2993       'America/Indianapolis' => -18000,
2994       'America/Inuvik' => -25200,
2995       'America/Iqaluit' => -18000,
2996       'America/Jamaica' => -18000,
2997       'America/Jujuy' => -10800,
2998       'America/Juneau' => -32400,
2999       'America/Kentucky/Louisville' => -18000,
3000       'America/Kentucky/Monticello' => -18000,
3001       'America/Knox_IN' => -18000,
3002       'America/La_Paz' => -14400,
3003       'America/Lima' => -18000,
3004       'America/Los_Angeles' => -28800,
3005       'America/Louisville' => -18000,
3006       'America/Maceio' => -10800,
3007       'America/Managua' => -21600,
3008       'America/Manaus' => -14400,
3009       'America/Martinique' => -14400,
3010       'America/Mazatlan' => -25200,
3011       'America/Mendoza' => -10800,
3012       'America/Menominee' => -21600,
3013       'America/Merida' => -21600,
3014       'America/Mexico_City' => -21600,
3015       'America/Miquelon' => -10800,
3016       'America/Moncton' => 0,
3017       'America/Monterrey' => -21600,
3018       'America/Montevideo' => -10800,
3019       'America/Montreal' => -18000,
3020       'America/Montserrat' => -14400,
3021       'America/Nassau' => -18000,
3022       'America/New_York' => -18000,
3023       'America/Nipigon' => -18000,
3024       'America/Nome' => -32400,
3025       'America/Noronha' => -7200,
3026       'America/North_Dakota/Center' => -21600,
3027       'America/North_Dakota/New_Salem' => 0,
3028       'America/Panama' => -18000,
3029       'America/Pangnirtung' => -18000,
3030       'America/Paramaribo' => -10800,
3031       'America/Phoenix' => -25200,
3032       'America/Port-au-Prince' => -18000,
3033       'America/Port_of_Spain' => -14400,
3034       'America/Porto_Acre' => -18000,
3035       'America/Porto_Velho' => -14400,
3036       'America/Puerto_Rico' => -14400,
3037       'America/Rainy_River' => -21600,
3038       'America/Rankin_Inlet' => -21600,
3039       'America/Recife' => -10800,
3040       'America/Regina' => -21600,
3041       'America/Rio_Branco' => -18000,
3042       'America/Rosario' => -10800,
3043       'America/Santiago' => -14400,
3044       'America/Santo_Domingo' => -14400,
3045       'America/Sao_Paulo' => -10800,
3046       'America/Scoresbysund' => -3600,
3047       'America/Shiprock' => -25200,
3048       'America/St_Johns' => -12600,
3049       'America/St_Kitts' => -14400,
3050       'America/St_Lucia' => -14400,
3051       'America/St_Thomas' => -14400,
3052       'America/St_Vincent' => -14400,
3053       'America/Swift_Current' => -21600,
3054       'America/Tegucigalpa' => -21600,
3055       'America/Thule' => -14400,
3056       'America/Thunder_Bay' => -18000,
3057       'America/Tijuana' => -28800,
3058       'America/Toronto' => 0,
3059       'America/Tortola' => -14400,
3060       'America/Vancouver' => -28800,
3061       'America/Virgin' => -14400,
3062       'America/Whitehorse' => -28800,
3063       'America/Winnipeg' => -21600,
3064       'America/Yakutat' => -32400,
3065       'America/Yellowknife' => -25200,
3066       'Antarctica/Casey' => 28800,
3067       'Antarctica/Davis' => 25200,
3068       'Antarctica/DumontDUrville' => 36000,
3069       'Antarctica/Mawson' => 21600,
3070       'Antarctica/McMurdo' => 43200,
3071       'Antarctica/Palmer' => -14400,
3072       'Antarctica/Rothera' => 0,
3073       'Antarctica/South_Pole' => 43200,
3074       'Antarctica/Syowa' => 10800,
3075       'Antarctica/VostokArctic/Longyearbyen' => 0,
3076       'Asia/Aden' => 10800,
3077       'Asia/Almaty' => 21600,
3078       'Asia/Amman' => 7200,
3079       'Asia/Anadyr' => 43200,
3080       'Asia/Aqtau' => 14400,
3081       'Asia/Aqtobe' => 18000,
3082       'Asia/Ashgabat' => 18000,
3083       'Asia/Ashkhabad' => 18000,
3084       'Asia/Baghdad' => 10800,
3085       'Asia/Bahrain' => 10800,
3086       'Asia/Baku' => 14400,
3087       'Asia/Bangkok' => 25200,
3088       'Asia/Beirut' => 7200,
3089       'Asia/Bishkek' => 18000,
3090       'Asia/Brunei' => 28800,
3091       'Asia/Calcutta' => 19800,
3092       'Asia/Choibalsan' => 32400,
3093       'Asia/Chongqing' => 28800,
3094       'Asia/Chungking' => 28800,
3095       'Asia/Colombo' => 21600,
3096       'Asia/Dacca' => 21600,
3097       'Asia/Damascus' => 7200,
3098       'Asia/Dhaka' => 21600,
3099       'Asia/Dili' => 32400,
3100       'Asia/Dubai' => 14400,
3101       'Asia/Dushanbe' => 18000,
3102       'Asia/Gaza' => 7200,
3103       'Asia/Harbin' => 28800,
3104       'Asia/Hong_Kong' => 28800,
3105       'Asia/Hovd' => 25200,
3106       'Asia/Irkutsk' => 28800,
3107       'Asia/Istanbul' => 7200,
3108       'Asia/Jakarta' => 25200,
3109       'Asia/Jayapura' => 32400,
3110       'Asia/Jerusalem' => 7200,
3111       'Asia/Kabul' => 16200,
3112       'Asia/Kamchatka' => 43200,
3113       'Asia/Karachi' => 18000,
3114       'Asia/Kashgar' => 28800,
3115       'Asia/Katmandu' => 20700,
3116       'Asia/Krasnoyarsk' => 25200,
3117       'Asia/Kuala_Lumpur' => 28800,
3118       'Asia/Kuching' => 28800,
3119       'Asia/Kuwait' => 10800,
3120       'Asia/Macao' => 28800,
3121       'Asia/Macau' => 0,
3122       'Asia/Magadan' => 39600,
3123       'Asia/Makassar' => 0,
3124       'Asia/Manila' => 28800,
3125       'Asia/Muscat' => 14400,
3126       'Asia/Nicosia' => 7200,
3127       'Asia/Novosibirsk' => 21600,
3128       'Asia/Omsk' => 21600,
3129       'Asia/Oral' => 0,
3130       'Asia/Phnom_Penh' => 25200,
3131       'Asia/Pontianak' => 25200,
3132       'Asia/Pyongyang' => 32400,
3133       'Asia/Qatar' => 10800,
3134       'Asia/Qyzylorda' => 0,
3135       'Asia/Rangoon' => 23400,
3136       'Asia/Riyadh' => 10800,
3137       'Asia/Saigon' => 25200,
3138       'Asia/Sakhalin' => 36000,
3139       'Asia/Samarkand' => 18000,
3140       'Asia/Seoul' => 32400,
3141       'Asia/Shanghai' => 28800,
3142       'Asia/Singapore' => 28800,
3143       'Asia/Taipei' => 28800,
3144       'Asia/Tashkent' => 18000,
3145       'Asia/Tbilisi' => 14400,
3146       'Asia/Tehran' => 12600,
3147       'Asia/Tel_Aviv' => 7200,
3148       'Asia/Thimbu' => 21600,
3149       'Asia/Thimphu' => 21600,
3150       'Asia/Tokyo' => 32400,
3151       'Asia/Ujung_Pandang' => 28800,
3152       'Asia/Ulaanbaatar' => 28800,
3153       'Asia/Ulan_Bator' => 28800,
3154       'Asia/Urumqi' => 28800,
3155       'Asia/Vientiane' => 25200,
3156       'Asia/Vladivostok' => 36000,
3157       'Asia/Yakutsk' => 32400,
3158       'Asia/Yekaterinburg' => 18000,
3159       'Asia/YerevanAtlantic/Azores' => 0,
3160       'Atlantic/Bermuda' => -14400,
3161       'Atlantic/Canary' => 0,
3162       'Atlantic/Cape_Verde' => -3600,
3163       'Atlantic/Faeroe' => 0,
3164       'Atlantic/Jan_Mayen' => 3600,
3165       'Atlantic/Madeira' => 0,
3166       'Atlantic/Reykjavik' => 0,
3167       'Atlantic/South_Georgia' => -7200,
3168       'Atlantic/St_Helena' => 0,
3169       'Atlantic/Stanley' => -14400,
3170       'Australia/ACT' => 36000,
3171       'Australia/Adelaide' => 34200,
3172       'Australia/Brisbane' => 36000,
3173       'Australia/Broken_Hill' => 34200,
3174       'Australia/Canberra' => 36000,
3175       'Australia/Currie' => 0,
3176       'Australia/Darwin' => 34200,
3177       'Australia/Hobart' => 36000,
3178       'Australia/LHI' => 37800,
3179       'Australia/Lindeman' => 36000,
3180       'Australia/Lord_Howe' => 37800,
3181       'Australia/Melbourne' => 36000,
3182       'Australia/NSW' => 36000,
3183       'Australia/North' => 34200,
3184       'Australia/Perth' => 28800,
3185       'Australia/Queensland' => 36000,
3186       'Australia/South' => 34200,
3187       'Australia/Sydney' => 36000,
3188       'Australia/Tasmania' => 36000,
3189       'Australia/Victoria' => 36000,
3190       'Australia/West' => 28800,
3191       'Australia/Yancowinna' => 34200,
3192       'Europe/Amsterdam' => 3600,
3193       'Europe/Andorra' => 3600,
3194       'Europe/Athens' => 7200,
3195       'Europe/Belfast' => 0,
3196       'Europe/Belgrade' => 3600,
3197       'Europe/Berlin' => 3600,
3198       'Europe/Bratislava' => 3600,
3199       'Europe/Brussels' => 3600,
3200       'Europe/Bucharest' => 7200,
3201       'Europe/Budapest' => 3600,
3202       'Europe/Chisinau' => 7200,
3203       'Europe/Copenhagen' => 3600,
3204       'Europe/Dublin' => 0,
3205       'Europe/Gibraltar' => 3600,
3206       'Europe/Guernsey' => 0,
3207       'Europe/Helsinki' => 7200,
3208       'Europe/Isle_of_Man' => 0,
3209       'Europe/Istanbul' => 7200,
3210       'Europe/Jersey' => 0,
3211       'Europe/Kaliningrad' => 7200,
3212       'Europe/Kiev' => 7200,
3213       'Europe/Lisbon' => 0,
3214       'Europe/Ljubljana' => 3600,
3215       'Europe/London' => 0,
3216       'Europe/Luxembourg' => 3600,
3217       'Europe/Madrid' => 3600,
3218       'Europe/Malta' => 3600,
3219       'Europe/Mariehamn' => 0,
3220       'Europe/Minsk' => 7200,
3221       'Europe/Monaco' => 3600,
3222       'Europe/Moscow' => 10800,
3223       'Europe/Nicosia' => 7200,
3224       'Europe/Oslo' => 3600,
3225       'Europe/Paris' => 3600,
3226       'Europe/Prague' => 3600,
3227       'Europe/Riga' => 7200,
3228       'Europe/Rome' => 3600,
3229       'Europe/Samara' => 14400,
3230       'Europe/San_Marino' => 3600,
3231       'Europe/Sarajevo' => 3600,
3232       'Europe/Simferopol' => 7200,
3233       'Europe/Skopje' => 3600,
3234       'Europe/Sofia' => 7200,
3235       'Europe/Stockholm' => 3600,
3236       'Europe/Tallinn' => 7200,
3237       'Europe/Tirane' => 3600,
3238       'Europe/Tiraspol' => 7200,
3239       'Europe/Uzhgorod' => 7200,
3240       'Europe/Vaduz' => 3600,
3241       'Europe/Vatican' => 3600,
3242       'Europe/Vienna' => 3600,
3243       'Europe/Vilnius' => 7200,
3244       'Europe/Volgograd' => 0,
3245       'Europe/Warsaw' => 3600,
3246       'Europe/Zagreb' => 3600,
3247       'Europe/Zaporozhye' => 7200,
3248       'Europe/Zurich' => 3600,
3249       'Indian/Antananarivo' => 10800,
3250       'Indian/Chagos' => 21600,
3251       'Indian/Christmas' => 25200,
3252       'Indian/Cocos' => 23400,
3253       'Indian/Comoro' => 10800,
3254       'Indian/Kerguelen' => 18000,
3255       'Indian/Mahe' => 14400,
3256       'Indian/Maldives' => 18000,
3257       'Indian/Mauritius' => 14400,
3258       'Indian/Mayotte' => 10800,
3259       'Indian/Reunion' => 14400,
3260       'Pacific/Apia' => -39600,
3261       'Pacific/Auckland' => 43200,
3262       'Pacific/Chatham' => 45900,
3263       'Pacific/Easter' => -21600,
3264       'Pacific/Efate' => 39600,
3265       'Pacific/Enderbury' => 46800,
3266       'Pacific/Fakaofo' => -36000,
3267       'Pacific/Fiji' => 43200,
3268       'Pacific/Funafuti' => 43200,
3269       'Pacific/Galapagos' => -21600,
3270       'Pacific/Gambier' => -32400,
3271       'Pacific/Guadalcanal' => 39600,
3272       'Pacific/Guam' => 36000,
3273       'Pacific/Honolulu' => -36000,
3274       'Pacific/Johnston' => -36000,
3275       'Pacific/Kiritimati' => 50400,
3276       'Pacific/Kosrae' => 39600,
3277       'Pacific/Kwajalein' => 43200,
3278       'Pacific/Majuro' => 43200,
3279       'Pacific/Marquesas' => -34200,
3280       'Pacific/Midway' => -39600,
3281       'Pacific/Nauru' => 43200,
3282       'Pacific/Niue' => -39600,
3283       'Pacific/Norfolk' => 41400,
3284       'Pacific/Noumea' => 39600,
3285       'Pacific/Pago_Pago' => -39600,
3286       'Pacific/Palau' => 32400,
3287       'Pacific/Pitcairn' => -28800,
3288       'Pacific/Ponape' => 39600,
3289       'Pacific/Port_Moresby' => 36000,
3290       'Pacific/Rarotonga' => -36000,
3291       'Pacific/Saipan' => 36000,
3292       'Pacific/Samoa' => -39600,
3293       'Pacific/Tahiti' => -36000,
3294       'Pacific/Tarawa' => 43200,
3295       'Pacific/Tongatapu' => 46800,
3296       'Pacific/Truk' => 36000,
3297       'Pacific/Wake' => 43200,
3298       'Pacific/Wallis' => 43200,
3299       'Pacific/Yap' => 36000 );          
3301   $dst_timezones = array (  
3302       'America/Adak' => 1,
3303       'America/Atka' => 1,
3304       'America/Anchorage' => 1,
3305       'America/Juneau' => 1,
3306       'America/Nome' => 1,
3307       'America/Yakutat' => 1,
3308       'America/Dawson' => 1,
3309       'America/Ensenada' => 1,
3310       'America/Los_Angeles' => 1,
3311       'America/Tijuana' => 1,
3312       'America/Vancouver' => 1,
3313       'America/Whitehorse' => 1,
3314       'America/Boise' => 1,
3315       'America/Cambridge_Bay' => 1,
3316       'America/Chihuahua' => 1,
3317       'America/Denver' => 1,
3318       'America/Edmonton' => 1,
3319       'America/Inuvik' => 1,
3320       'America/Mazatlan' => 1,
3321       'America/Shiprock' => 1,
3322       'America/Yellowknife' => 1,
3323       'America/Cancun' => 1,
3324       'America/Chicago' => 1,
3325       'America/Menominee' => 1,
3326       'America/Merida' => 1,
3327       'America/Monterrey' => 1,
3328       'America/North_Dakota/Center' => 1,
3329       'America/Rainy_River' => 1,
3330       'America/Rankin_Inlet' => 1,
3331       'America/Winnipeg' => 1,
3332       'Pacific/Easter' => 1,
3333       'America/Detroit' => 1,
3334       'America/Grand_Turk' => 1,
3335       'America/Havana' => 1,
3336       'America/Iqaluit' => 1,
3337       'America/Kentucky/Louisville' => 1,
3338       'America/Kentucky/Monticello' => 1,
3339       'America/Louisville' => 1,
3340       'America/Montreal' => 1,
3341       'America/Nassau' => 1,
3342       'America/New_York' => 1,
3343       'America/Nipigon' => 1,
3344       'America/Pangnirtung' => 1,
3345       'America/Thunder_Bay' => 1,
3346       'America/Asuncion' => 1,
3347       'America/Cuiaba' => 1,
3348       'America/Glace_Bay' => 1,
3349       'America/Goose_Bay' => 1,
3350       'America/Halifax' => 1,
3351       'America/Santiago' => 1,
3352       'Antarctica/Palmer' => 1,
3353       'Atlantic/Bermuda' => 1,
3354       'Atlantic/Stanley' => 1,
3355       'America/St_Johns' => 1,
3356       'America/Araguaina' => 1,
3357       'America/Fortaleza' => 1,
3358       'America/Godthab' => 1,
3359       'America/Maceio' => 1,
3360       'America/Miquelon' => 1,
3361       'America/Recife' => 1,
3362       'America/Sao_Paulo' => 1,
3363       'America/Scoresbysund' => 1,
3364       'Atlantic/Canary' => 1,
3365       'Atlantic/Faeroe' => 1,
3366       'Atlantic/Madeira' => 1,
3367       'Europe/Belfast' => 1,
3368       'Europe/Dublin' => 1,
3369       'Europe/Lisbon' => 1,
3370       'Europe/London' => 1,
3371       'Africa/Ceuta' => 1,
3372       'Africa/Windhoek' => 1,
3373       'Atlantic/Jan_Mayen' => 1,
3374       'Europe/Amsterdam' => 1,
3375       'Europe/Andorra' => 1,
3376       'Europe/Belgrade' => 1,
3377       'Europe/Berlin' => 1,
3378       'Europe/Bratislava' => 1,
3379       'Europe/Brussels' => 1,
3380       'Europe/Budapest' => 1,
3381       'Europe/Copenhagen' => 1,
3382       'Europe/Gibraltar' => 1,
3383       'Europe/Ljubljana' => 1,
3384       'Europe/Luxembourg' => 1,
3385       'Europe/Madrid' => 1,
3386       'Europe/Malta' => 1,
3387       'Europe/Monaco' => 1,
3388       'Europe/Oslo' => 1,
3389       'Europe/Paris' => 1,
3390       'Europe/Prague' => 1,
3391       'Europe/Rome' => 1,
3392       'Europe/San_Marino' => 1,
3393       'Europe/Sarajevo' => 1,
3394       'Europe/Skopje' => 1,
3395       'Europe/Stockholm' => 1,
3396       'Europe/Tirane' => 1,
3397       'Europe/Vaduz' => 1,
3398       'Europe/Vatican' => 1,
3399       'Europe/Vienna' => 1,
3400       'Europe/Warsaw' => 1,
3401       'Europe/Zagreb' => 1,
3402       'Europe/Zurich' => 1,
3403       'Africa/Cairo' => 1,
3404       'Asia/Amman' => 1,
3405       'Asia/Beirut' => 1,
3406       'Asia/Damascus' => 1,
3407       'Asia/Gaza' => 1,
3408       'Asia/Istanbul' => 1,
3409       'Asia/Jerusalem' => 1,
3410       'Asia/Nicosia' => 1,
3411       'Asia/Tel_Aviv' => 1,
3412       'Europe/Athens' => 1,
3413       'Europe/Bucharest' => 1,
3414       'Europe/Chisinau' => 1,
3415       'Europe/Helsinki' => 1,
3416       'Europe/Istanbul' => 1,
3417       'Europe/Kaliningrad' => 1,
3418       'Europe/Kiev' => 1,
3419       'Europe/Minsk' => 1,
3420       'Europe/Nicosia' => 1,
3421       'Europe/Riga' => 1,
3422       'Europe/Simferopol' => 1,
3423       'Europe/Sofia' => 1,
3424       'Europe/Tiraspol' => 1,
3425       'Europe/Uzhgorod' => 1,
3426       'Europe/Zaporozhye' => 1,
3427       'Asia/Baghdad' => 1,
3428       'Europe/Moscow' => 1,
3429       'Asia/Tehran' => 1,
3430       'Asia/Aqtau' => 1,
3431       'Asia/Baku' => 1,
3432       'Asia/Tbilisi' => 1,
3433       'Europe/Samara' => 1,
3434       'Asia/Aqtobe' => 1,
3435       'Asia/Bishkek' => 1,
3436       'Asia/Yekaterinburg' => 1,
3437       'Asia/Almaty' => 1,
3438       'Asia/Novosibirsk' => 1,
3439       'Asia/Omsk' => 1,
3440       'Asia/Krasnoyarsk' => 1,
3441       'Asia/Irkutsk' => 1,
3442       'Asia/Yakutsk' => 1,
3443       'Australia/Adelaide' => 1,
3444       'Australia/Broken_Hill' => 1,
3445       'Australia/South' => 1,
3446       'Australia/Yancowinna' => 1,
3447       'Asia/Sakhalin' => 1,
3448       'Asia/Vladivostok' => 1,
3449       'Australia/ACT' => 1,
3450       'Australia/Canberra' => 1,
3451       'Australia/Hobart' => 1,
3452       'Australia/Melbourne' => 1,
3453       'Australia/NSW' => 1,
3454       'Australia/Sydney' => 1,
3455       'Australia/Tasmania' => 1,
3456       'Australia/Victoria' => 1,
3457       'Australia/LHI' => 1,
3458       'Australia/Lord_Howe' => 1,
3459       'Asia/Magadan' => 1,
3460       'Antarctica/McMurdo' => 1,
3461       'Antarctica/South_Pole' => 1,
3462       'Asia/Anadyr' => 1,
3463       'Asia/Kamchatka' => 1,
3464       'Pacific/Auckland' => 1,
3465       'Pacific/Chatham' => 1,
3466       );  
3467   return(array("TIMEZONES" => $timezones, "DST_ZONES" => $dst_timezones));
3471 function display_error_page()
3473   $smarty= get_smarty();
3474   $smarty->display(get_template_path('headers.tpl'));
3475   echo "<body>".msg_dialog::get_dialogs()."</body></html>";
3476   exit();
3479 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3480 ?>