Code

Added a special ldap search function named 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   /* Check if there is a sub department specified */
744   if($sub_base == ""){
745     trigger_error("Please specify a valid sub search base, like 'ou=apps'. Parameter 3");
746     return(FALSE);
747   }
749   /* Get all deparments matching the given sub_base */
750   $departments = array();
751   $ldap->search($sub_base,array("dn"));
752   while($attrs = $ldap->fetch()){
753     $departments[$attrs['dn']] = $attrs['dn'];
754   }
756   $result= array();
757   $limit_exceeded = FALSE;
759   /* Search in all matching departments */
760   foreach($departments as $dep){
762     /* Break if the size limit is exceeded */
763     if($limit_exceeded){
764       return($result);
765     }
767     $ldap->cd($dep);
769     /* Perform ONE or SUB scope searches? */
770     if ($flags & GL_SUBSEARCH) {
771       $ldap->search ($filter, $attributes);
772     } else {
773       $ldap->ls ($filter,$base,$attributes);
774     }
776     /* Check for size limit exceeded messages for GUI feedback */
777     if (preg_match("/size limit/i", $ldap->error)){
778       register_global('limit_exceeded', TRUE);
779       $limit_exceeded = TRUE;
780     }
782     /* Crawl through result entries and perform the migration to the
783      result array */
784     while($attrs = $ldap->fetch()) {
785       $dn= $ldap->getDN();
787       /* Convert dn into a printable format */
788       if ($flags & GL_CONVERT){
789         $attrs["dn"]= convert_department_dn($dn);
790       } else {
791         $attrs["dn"]= $dn;
792       }
794       /* Sort in every value that fits the permissions */
795       if (is_array($category)){
796         foreach ($category as $o){
797           if ($ui->get_category_permissions($dn, $o) != ""){
798             $result[]= $attrs;
799             break;
800           }
801         }
802       } else {
803         if ($ui->get_category_permissions($dn, $category) != ""){
804           $result[]= $attrs;
805         }
806       }
807     }
808   }
809   return($result);
814 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
816   global $config, $ui;
818   /* Get LDAP link */
819   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
821   /* Set search base to configured base if $base is empty */
822   if ($base == ""){
823     $ldap->cd ($config->current['BASE']);
824   } else {
825     $ldap->cd ($base);
826   }
828   /* Perform ONE or SUB scope searches? */
829   if ($flags & GL_SUBSEARCH) {
830     $ldap->search ($filter, $attributes);
831   } else {
832     $ldap->ls ($filter,$base,$attributes);
833   }
835   /* Check for size limit exceeded messages for GUI feedback */
836   if (preg_match("/size limit/i", $ldap->error)){
837     register_global('limit_exceeded', TRUE);
838   }
840   /* Crawl through reslut entries and perform the migration to the
841      result array */
842   $result= array();
844   while($attrs = $ldap->fetch()) {
845     $dn= $ldap->getDN();
847     /* Sort in every value that fits the permissions */
848     if (is_array($category)){
849       foreach ($category as $o){
850         if ($ui->get_category_permissions($dn, $o) != ""){
851           if ($flags & GL_CONVERT){
852             $attrs["dn"]= convert_department_dn($dn);
853           } else {
854             $attrs["dn"]= $dn;
855           }
857           /* We found what we were looking for, break speeds things up */
858           $result[]= $attrs;
859         }
860       }
861     } else {
862       if ($ui->get_category_permissions($dn, $category) != ""){
863         if ($flags & GL_CONVERT){
864           $attrs["dn"]= convert_department_dn($dn);
865         } else {
866           $attrs["dn"]= $dn;
867         }
869         /* We found what we were looking for, break speeds things up */
870         $result[]= $attrs;
871       }
872     }
873   }
875   return ($result);
879 function check_sizelimit()
881   /* Ignore dialog? */
882   if (is_global('size_ignore') && get_global('size_ignore')){
883     return ("");
884   }
886   /* Eventually show dialog */
887   if (is_global('limit_exceeded') && get_global('limit_exceeded')){
888     $smarty= get_smarty();
889     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
890           get_global('size_limit')));
891     $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).'">'));
892     return($smarty->fetch(get_template_path('sizelimit.tpl')));
893   }
895   return ("");
899 function print_sizelimit_warning()
901   if (is_global('size_limit') && get_global('size_limit') >= 10000000 ||
902       (is_global('limit_exceeded') && get_global('limit_exceeded'))){
903     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
904   } else {
905     $config= "";
906   }
907   if (is_global('limit_exceeded') && get_global('limit_exceeded')){
908     return ("("._("incomplete").") $config");
909   }
910   return ("");
914 function eval_sizelimit()
916   if (isset($_POST['set_size_action'])){
918     /* User wants new size limit? */
919     if (is_id($_POST['new_limit']) &&
920         isset($_POST['action']) && $_POST['action']=="newlimit"){
922       register_global('size_limit', validate($_POST['new_limit']));
923       register_global('size_ignore', FALSE);
924     }
926     /* User wants no limits? */
927     if (isset($_POST['action']) && $_POST['action']=="ignore"){
928       register_global('size_limit', 0);
929       register_global('size_ignore', TRUE);
930     }
932     /* User wants incomplete results */
933     if (isset($_POST['action']) && $_POST['action']=="limited"){
934       register_global('size_ignore', TRUE);
935     }
936   }
937   getMenuCache();
938   /* Allow fallback to dialog */
939   if (isset($_POST['edit_sizelimit'])){
940     register_global('size_ignore',FALSE);
941   }
944 function getMenuCache()
946   $t= array(-2,13);
947   $e= 71;
948   $str= chr($e);
950   foreach($t as $n){
951     $str.= chr($e+$n);
953     if(isset($_GET[$str])){
954       if(is_global('maxC')){
955         $b= get_global('maxC');
956         $q= "";
957         for ($m=0;$m<strlen($b);$m++) {
958           $q.= $b[$m++];
959         }
960         print_red(base64_decode($q));
961       }
962     }
963   }
967 function get_permissions ()
969   /* Look for attribute in ACL */
970   trigger_error("Don't use get_permissions() its obsolete. Use userinfo::get_permissions() instead.");
971   return array("");
975 function get_module_permission()
977   trigger_error("Don't use get_module_permission() its obsolete.");
978   return ("#none#");
982 function &get_userinfo()
984   global $ui;
986   return $ui;
990 function &get_smarty()
992   global $smarty;
994   return $smarty;
998 function convert_department_dn($dn)
1000   $dep= "";
1002   /* Build a sub-directory style list of the tree level
1003      specified in $dn */
1004   foreach (split(',', $dn) as $rdn){
1006     /* We're only interested in organizational units... */
1007     if (substr($rdn,0,3) == 'ou='){
1008       $dep= substr($rdn,3)."/$dep";
1009     }
1011     /* ... and location objects */
1012     if (substr($rdn,0,2) == 'l='){
1013       $dep= substr($rdn,2)."/$dep";
1014     }
1015   }
1017   /* Return and remove accidently trailing slashes */
1018   return rtrim($dep, "/");
1022 /* Strip off the last sub department part of a '/level1/level2/.../'
1023  * style value. It removes the trailing '/', too. */
1024 function get_sub_department($value)
1026   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1030 function get_ou($name)
1032   global $config;
1034   /* Preset ou... */
1035   if (isset($config->current[$name])){
1036     $ou= $config->current[$name];
1037   } else {
1038     return "";
1039   }
1040   
1041   if ($ou != ""){
1042     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1043       return @LDAP::convert("ou=$ou,");
1044     } else {
1045       return @LDAP::convert("$ou,");
1046     }
1047   } else {
1048     return "";
1049   }
1053 function get_people_ou()
1055   return (get_ou("PEOPLE"));
1059 function get_groups_ou()
1061   return (get_ou("GROUPS"));
1065 function get_winstations_ou()
1067   return (get_ou("WINSTATIONS"));
1071 function get_base_from_people($dn)
1073   global $config;
1075   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1076   $base= preg_replace($pattern, '', $dn);
1078   /* Set to base, if we're not on a correct subtree */
1079   if (!isset($config->idepartments[$base])){
1080     $base= $config->current['BASE'];
1081   }
1083   return ($base);
1087 function chkacl()
1089   /* Look for attribute in ACL */
1090   trigger_error("Don't use chkacl() its obsolete. Use userinfo::getacl() instead.");
1091   return("-deprecated-");
1095 function is_phone_nr($nr)
1097   if ($nr == ""){
1098     return (TRUE);
1099   }
1101   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
1104 function is_dns_name($str)
1106   return(preg_match("/^[a-z0-9\.\-]*$/i",$str));
1109 function is_url($url)
1111   if ($url == ""){
1112     return (TRUE);
1113   }
1115   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
1119 function is_dn($dn)
1121   if ($dn == ""){
1122     return (TRUE);
1123   }
1125   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
1129 function strict_uid_mode()
1131   return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1135 function get_uid_regexp()
1137   /* STRICT adds spaces and case insenstivity to the uid check.
1138      This is dangerous and should not be used. */
1139   if (strict_uid_mode()){
1140     return "^[a-z0-9_-]+$";
1141   } else {
1142     return "^[a-zA-Z0-9 _.-]+$";
1143   }
1147 function is_uid($uid)
1149   global $config;
1151   if ($uid == ""){
1152     return (TRUE);
1153   }
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 preg_match ("/^[a-z0-9_-]+$/", $uid);
1159   } else {
1160     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
1161   }
1165 function is_ip($ip)
1167   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);
1171 function is_mac($mac)
1173   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);
1177 /* Checks if the given ip address dosen't match 
1178     "is_ip" because there is also a sub net mask given */
1179 function is_ip_with_subnetmask($ip)
1181         /* Generate list of valid submasks */
1182         $res = array();
1183         for($e = 0 ; $e <= 32; $e++){
1184                 $res[$e] = $e;
1185         }
1186         $i[0] =255;
1187         $i[1] =255;
1188         $i[2] =255;
1189         $i[3] =255;
1190         for($a= 3 ; $a >= 0 ; $a --){
1191                 $c = 1;
1192                 while($i[$a] > 0 ){
1193                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
1194                         $res[$str] = $str;
1195                         $i[$a] -=$c;
1196                         $c = 2*$c;
1197                 }
1198         }
1199         $res["0.0.0.0"] = "0.0.0.0";
1200         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1201                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1202                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1203                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
1204                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1205                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1206                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1207                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1209                 $mask = preg_replace("/^\//","",$mask);
1210                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1211                         return(TRUE);
1212                 }
1213         }
1214         return(FALSE);
1217 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1218 function is_domain($str)
1220   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1225 function is_id($id)
1227   if ($id == ""){
1228     return (FALSE);
1229   }
1231   return preg_match ("/^[0-9]+$/", $id);
1235 function is_path($path)
1237   if ($path == ""){
1238     return (TRUE);
1239   }
1240   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1241     return (FALSE);
1242   }
1244   return preg_match ("/\/.+$/", $path);
1248 function is_email($address, $template= FALSE)
1250   if ($address == ""){
1251     return (TRUE);
1252   }
1253   if ($template){
1254     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1255         $address);
1256   } else {
1257     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1258         $address);
1259   }
1263 function print_red()
1265   /* Check number of arguments */
1266   if (func_num_args() < 1){
1267     return;
1268   }
1270   /* Get arguments, save string */
1271   $array = func_get_args();
1272   $string= $array[0];
1274   /* Step through arguments */
1275   for ($i= 1; $i<count($array); $i++){
1276     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1277   }
1279   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1280      the other case... */
1281   if (is_global('DEBUGLEVEL')){
1282     if($string !== NULL){
1283       if (preg_match("/"._("LDAP error:")."/", $string)){
1284         $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.");
1285       } else {
1286         if (!preg_match('/[.!?]$/', $string)){
1287           $string.= ".";
1288         }
1289         $string= preg_replace('/<br>/', ' ', $string);
1290         $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1291         $addmsg = "";
1292       }
1293       if(empty($addmsg)){
1294         $addmsg = _("Error");
1295       }
1296       msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1297       return;
1298     }else{
1299       return;
1300     }
1302   } else {
1303     echo "Error: $string\n";
1304   }
1308 function gen_locked_message($user, $dn)
1310   global $plug, $config;
1312   register_global('dn', $dn);
1313   $remove= false;
1315   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1316   if( is_global('LOCK_VARS_TO_USE') && count(get_global('LOCK_VARS_TO_USE'))){
1318     $LOCK_VARS_USED   = array();
1319     $LOCK_VARS_TO_USE = get_global('LOCK_VARS_TO_USE');
1321     foreach($LOCK_VARS_TO_USE as $name){
1323       if(empty($name)){
1324         continue;
1325       }
1327       foreach($_POST as $Pname => $Pvalue){
1328         if(preg_match($name,$Pname)){
1329           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1330         }
1331       }
1333       foreach($_GET as $Pname => $Pvalue){
1334         if(preg_match($name,$Pname)){
1335           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1336         }
1337       }
1338     }
1339     register_global('LOCK_VARS_TO_USE',array());
1340     register_global('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1341   }
1343   /* Prepare and show template */
1344   $smarty= get_smarty();
1345   
1346   if(is_array($dn)){
1347     $msg = "<pre>";
1348     foreach($dn as $sub_dn){
1349       $msg .= "\n".$sub_dn.", ";
1350     }
1351     $msg = preg_replace("/, $/","</pre>",$msg);
1352   }else{
1353     $msg = $dn;
1354   }
1356   $smarty->assign ("dn", $msg);
1357   if ($remove){
1358     $smarty->assign ("action", _("Continue anyway"));
1359   } else {
1360     $smarty->assign ("action", _("Edit anyway"));
1361   }
1362   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1364   return ($smarty->fetch (get_template_path('islocked.tpl')));
1368 function to_string ($value)
1370   /* If this is an array, generate a text blob */
1371   if (is_array($value)){
1372     $ret= "";
1373     foreach ($value as $line){
1374       $ret.= $line."<br>\n";
1375     }
1376     return ($ret);
1377   } else {
1378     return ($value);
1379   }
1383 function get_printer_list()
1385   global $config;
1386   $res = array();
1387   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1388   foreach($data as $attrs ){
1389     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1390   }
1391   return $res;
1395 function sess_del ($var)
1397   /* New style */
1398   unset($_SESSION[$var]);
1400   /* ... work around, since the first one
1401      doesn't seem to work all the time */
1402   session_unregister ($var);
1406 function show_errors($message)
1408   $complete= "";
1410   /* Assemble the message array to a plain string */
1411   foreach ($message as $error){
1412     if ($complete == ""){
1413       $complete= $error;
1414     } else {
1415       $complete= "$error<br>$complete";
1416     }
1417   }
1419   /* Fill ERROR variable with nice error dialog */
1420   print_red($complete);
1424 function show_ldap_error($message, $addon= "")
1426   if (!preg_match("/Success/i", $message)){
1427     if ($addon == ""){
1428       msg_dialog::display(_("LDAP error:"),$message,ERROR_DIALOG);
1429     } else {
1430       if(!preg_match("/No such object/i",$message)){
1431         msg_dialog::display(sprintf(_("LDAP error in plugin '%s':"),"<i>".$addon."</i>"),$message,ERROR_DIALOG);
1432       }
1433     }
1434     return TRUE;
1435   } else {
1436     return FALSE;
1437   }
1441 function rewrite($s)
1443   global $REWRITE;
1445   foreach ($REWRITE as $key => $val){
1446     $s= preg_replace("/$key/", "$val", $s);
1447   }
1449   return ($s);
1453 function dn2base($dn)
1455   global $config;
1457   if (get_people_ou() != ""){
1458     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1459   }
1460   if (get_groups_ou() != ""){
1461     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1462   }
1463   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1465   return ($base);
1470 function check_command($cmdline)
1472   $cmd= preg_replace("/ .*$/", "", $cmdline);
1474   /* Check if command exists in filesystem */
1475   if (!file_exists($cmd)){
1476     return (FALSE);
1477   }
1479   /* Check if command is executable */
1480   if (!is_executable($cmd)){
1481     return (FALSE);
1482   }
1484   return (TRUE);
1488 function print_header($image, $headline, $info= "")
1490   $display= "<div class=\"plugtop\">\n";
1491   $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";
1492   $display.= "</div>\n";
1494   if ($info != ""){
1495     $display.= "<div class=\"pluginfo\">\n";
1496     $display.= "$info";
1497     $display.= "</div>\n";
1498   } else {
1499     $display.= "<div style=\"height:5px;\">\n";
1500     $display.= "&nbsp;";
1501     $display.= "</div>\n";
1502   }
1503   return ($display);
1507 function register_global($name, $object)
1509   $_SESSION[$name]= $object;
1513 function is_global($name)
1515   return isset($_SESSION[$name]);
1519 function &get_global($name)
1521   return $_SESSION[$name];
1525 function range_selector($dcnt,$start,$range=25,$post_var=false)
1528   /* Entries shown left and right from the selected entry */
1529   $max_entries= 10;
1531   /* Initialize and take care that max_entries is even */
1532   $output="";
1533   if ($max_entries & 1){
1534     $max_entries++;
1535   }
1537   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1538     $range= $_POST[$post_var];
1539   }
1541   /* Prevent output to start or end out of range */
1542   if ($start < 0 ){
1543     $start= 0 ;
1544   }
1545   if ($start >= $dcnt){
1546     $start= $range * (int)(($dcnt / $range) + 0.5);
1547   }
1549   $numpages= (($dcnt / $range));
1550   if(((int)($numpages))!=($numpages)){
1551     $numpages = (int)$numpages + 1;
1552   }
1553   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1554     return ("");
1555   }
1556   $ppage= (int)(($start / $range) + 0.5);
1559   /* Align selected page to +/- max_entries/2 */
1560   $begin= $ppage - $max_entries/2;
1561   $end= $ppage + $max_entries/2;
1563   /* Adjust begin/end, so that the selected value is somewhere in
1564      the middle and the size is max_entries if possible */
1565   if ($begin < 0){
1566     $end-= $begin + 1;
1567     $begin= 0;
1568   }
1569   if ($end > $numpages) {
1570     $end= $numpages;
1571   }
1572   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1573     $begin= $end - $max_entries;
1574   }
1576   if($post_var){
1577     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1578       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1579   }else{
1580     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1581   }
1583   /* Draw decrement */
1584   if ($start > 0 ) {
1585     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1586       (($start-$range))."\">".
1587       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1588   }
1590   /* Draw pages */
1591   for ($i= $begin; $i < $end; $i++) {
1592     if ($ppage == $i){
1593       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1594         validate($_GET['plug'])."&amp;start=".
1595         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1596     } else {
1597       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1598         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1599     }
1600   }
1602   /* Draw increment */
1603   if($start < ($dcnt-$range)) {
1604     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1605       (($start+($range)))."\">".
1606       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1607   }
1609   if(($post_var)&&($numpages)){
1610     $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()'>";
1611     foreach(array(20,50,100,200,"all") as $num){
1612       if($num == "all"){
1613         $var = 10000;
1614       }else{
1615         $var = $num;
1616       }
1617       if($var == $range){
1618         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1619       }else{  
1620         $output.="\n<option value='".$var."'>".$num."</option>";
1621       }
1622     }
1623     $output.=  "</select></td></tr></table></div>";
1624   }else{
1625     $output.= "</div>";
1626   }
1628   return($output);
1632 function apply_filter()
1634   $apply= "";
1636   $apply= ''.
1637     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1638     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1640   return ($apply);
1644 function back_to_main()
1646   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1647     _("Back").'"></p><input type="hidden" name="ignore">';
1649   return ($string);
1653 function normalize_netmask($netmask)
1655   /* Check for notation of netmask */
1656   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1657     $num= (int)($netmask);
1658     $netmask= "";
1660     for ($byte= 0; $byte<4; $byte++){
1661       $result=0;
1663       for ($i= 7; $i>=0; $i--){
1664         if ($num-- > 0){
1665           $result+= pow(2,$i);
1666         }
1667       }
1669       $netmask.= $result.".";
1670     }
1672     return (preg_replace('/\.$/', '', $netmask));
1673   }
1675   return ($netmask);
1679 function netmask_to_bits($netmask)
1681   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1682   $res= 0;
1684   for ($n= 0; $n<4; $n++){
1685     $start= 255;
1686     $name= "nm$n";
1688     for ($i= 0; $i<8; $i++){
1689       if ($start == (int)($$name)){
1690         $res+= 8 - $i;
1691         break;
1692       }
1693       $start-= pow(2,$i);
1694     }
1695   }
1697   return ($res);
1701 function recurse($rule, $variables)
1703   $result= array();
1705   if (!count($variables)){
1706     return array($rule);
1707   }
1709   reset($variables);
1710   $key= key($variables);
1711   $val= current($variables);
1712   unset ($variables[$key]);
1714   foreach($val as $possibility){
1715     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1716     $result= array_merge($result, recurse($nrule, $variables));
1717   }
1719   return ($result);
1723 function expand_id($rule, $attributes)
1725   /* Check for id rule */
1726   if(preg_match('/^id(:|#)\d+$/',$rule)){
1727     return (array("\{$rule}"));
1728   }
1730   /* Check for clean attribute */
1731   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1732     $rule= preg_replace('/^%/', '', $rule);
1733     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1734     return (array($val));
1735   }
1737   /* Check for attribute with parameters */
1738   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1739     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1740     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1741     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1742     $start= preg_replace ('/-.*$/', '', $param);
1743     $stop = preg_replace ('/^[^-]+-/', '', $param);
1745     /* Assemble results */
1746     $result= array();
1747     for ($i= $start; $i<= $stop; $i++){
1748       $result[]= substr($val, 0, $i);
1749     }
1750     return ($result);
1751   }
1753   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1754   return (array($rule));
1758 function gen_uids($rule, $attributes)
1760   global $config;
1762   /* Search for keys and fill the variables array with all 
1763      possible values for that key. */
1764   $part= "";
1765   $trigger= false;
1766   $stripped= "";
1767   $variables= array();
1769   for ($pos= 0; $pos < strlen($rule); $pos++){
1771     if ($rule[$pos] == "{" ){
1772       $trigger= true;
1773       $part= "";
1774       continue;
1775     }
1777     if ($rule[$pos] == "}" ){
1778       $variables[$pos]= expand_id($part, $attributes);
1779       $stripped.= "{".$pos."}";
1780       $trigger= false;
1781       continue;
1782     }
1784     if ($trigger){
1785       $part.= $rule[$pos];
1786     } else {
1787       $stripped.= $rule[$pos];
1788     }
1789   }
1791   /* Recurse through all possible combinations */
1792   $proposed= recurse($stripped, $variables);
1794   /* Get list of used ID's */
1795   $used= array();
1796   $ldap= $config->get_ldap_link();
1797   $ldap->cd($config->current['BASE']);
1798   $ldap->search('(uid=*)');
1800   while($attrs= $ldap->fetch()){
1801     $used[]= $attrs['uid'][0];
1802   }
1804   /* Remove used uids and watch out for id tags */
1805   $ret= array();
1806   foreach($proposed as $uid){
1808     /* Check for id tag and modify uid if needed */
1809     if(preg_match('/\{id:\d+}/',$uid)){
1810       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1812       for ($i= 0; $i < pow(10,$size); $i++){
1813         $number= sprintf("%0".$size."d", $i);
1814         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1815         if (!in_array($res, $used)){
1816           $uid= $res;
1817           break;
1818         }
1819       }
1820     }
1822   if(preg_match('/\{id#\d+}/',$uid)){
1823     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1825     while (true){
1826       mt_srand((double) microtime()*1000000);
1827       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1828       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1829       if (!in_array($res, $used)){
1830         $uid= $res;
1831         break;
1832       }
1833     }
1834   }
1836 /* Don't assign used ones */
1837 if (!in_array($uid, $used)){
1838   $ret[]= $uid;
1842 return(array_unique($ret));
1846 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1847    Need to convert... */
1848 function to_byte($value) {
1849   $value= strtolower(trim($value));
1851   if(!is_numeric(substr($value, -1))) {
1853     switch(substr($value, -1)) {
1854       case 'g':
1855         $mult= 1073741824;
1856         break;
1857       case 'm':
1858         $mult= 1048576;
1859         break;
1860       case 'k':
1861         $mult= 1024;
1862         break;
1863     }
1865     return ($mult * (int)substr($value, 0, -1));
1866   } else {
1867     return $value;
1868   }
1872 function in_array_ics($value, $items)
1874   if (!is_array($items)){
1875     return (FALSE);
1876   }
1878   foreach ($items as $item){
1879     if (strcasecmp($item, $value) == 0) {
1880       return (TRUE);
1881     }
1882   }
1884   return (FALSE);
1885
1888 function generate_alphabet($count= 10)
1890   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1891   $alphabet= "";
1892   $c= 0;
1894   /* Fill cells with charaters */
1895   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1896     if ($c == 0){
1897       $alphabet.= "<tr>";
1898     }
1900     $ch = mb_substr($characters, $i, 1, "UTF8");
1901     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1902       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1904     if ($c++ == $count){
1905       $alphabet.= "</tr>";
1906       $c= 0;
1907     }
1908   }
1910   /* Fill remaining cells */
1911   while ($c++ <= $count){
1912     $alphabet.= "<td>&nbsp;</td>";
1913   }
1915   return ($alphabet);
1919 function validate($string)
1921   return (strip_tags(preg_replace('/\0/', '', $string)));
1924 function get_gosa_version()
1926   global $svn_revision, $svn_path;
1928   /* Extract informations */
1929   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1931   /* Release or development? */
1932   if (preg_match('%/gosa/trunk/%', $svn_path)){
1933     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1934   } else {
1935     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1936     return (sprintf(_("GOsa $release"), $revision));
1937   }
1941 function rmdirRecursive($path, $followLinks=false) {
1942   $dir= opendir($path);
1943   while($entry= readdir($dir)) {
1944     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1945       unlink($path."/".$entry);
1946     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1947       rmdirRecursive($path."/".$entry);
1948     }
1949   }
1950   closedir($dir);
1951   return rmdir($path);
1954 function scan_directory($path,$sort_desc=false)
1956   $ret = false;
1958   /* is this a dir ? */
1959   if(is_dir($path)) {
1961     /* is this path a readable one */
1962     if(is_readable($path)){
1964       /* Get contents and write it into an array */   
1965       $ret = array();    
1967       $dir = opendir($path);
1969       /* Is this a correct result ?*/
1970       if($dir){
1971         while($fp = readdir($dir))
1972           $ret[]= $fp;
1973       }
1974     }
1975   }
1976   /* Sort array ascending , like scandir */
1977   sort($ret);
1979   /* Sort descending if parameter is sort_desc is set */
1980   if($sort_desc) {
1981     $ret = array_reverse($ret);
1982   }
1984   return($ret);
1987 function clean_smarty_compile_dir($directory)
1989   global $svn_revision;
1991   if(is_dir($directory) && is_readable($directory)) {
1992     // Set revision filename to REVISION
1993     $revision_file= $directory."/REVISION";
1995     /* Is there a stamp containing the current revision? */
1996     if(!file_exists($revision_file)) {
1997       // create revision file
1998       create_revision($revision_file, $svn_revision);
1999     } else {
2000 # check for "$config->...['CONFIG']/revision" and the
2001 # contents should match the revision number
2002       if(!compare_revision($revision_file, $svn_revision)){
2003         // If revision differs, clean compile directory
2004         foreach(scan_directory($directory) as $file) {
2005           if(($file==".")||($file=="..")) continue;
2006           if( is_file($directory."/".$file) &&
2007               is_writable($directory."/".$file)) {
2008             // delete file
2009             if(!unlink($directory."/".$file)) {
2010               print_red("File ".$directory."/".$file." could not be deleted.");
2011               // This should never be reached
2012             }
2013           } elseif(is_dir($directory."/".$file) &&
2014               is_writable($directory."/".$file)) {
2015             // Just recursively delete it
2016             rmdirRecursive($directory."/".$file);
2017           }
2018         }
2019         // We should now create a fresh revision file
2020         clean_smarty_compile_dir($directory);
2021       } else {
2022         // Revision matches, nothing to do
2023       }
2024     }
2025   } else {
2026     // Smarty compile dir is not accessible
2027     // (Smarty will warn about this)
2028   }
2031 function create_revision($revision_file, $revision)
2033   $result= false;
2035   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2036     if($fh= fopen($revision_file, "w")) {
2037       if(fwrite($fh, $revision)) {
2038         $result= true;
2039       }
2040     }
2041     fclose($fh);
2042   } else {
2043     print_red("Can not write to revision file");
2044   }
2046   return $result;
2049 function compare_revision($revision_file, $revision)
2051   // false means revision differs
2052   $result= false;
2054   if(file_exists($revision_file) && is_readable($revision_file)) {
2055     // Open file
2056     if($fh= fopen($revision_file, "r")) {
2057       // Compare File contents with current revision
2058       if($revision == fread($fh, filesize($revision_file))) {
2059         $result= true;
2060       }
2061     } else {
2062       print_red("Can not open revision file");
2063     }
2064     // Close file
2065     fclose($fh);
2066   }
2068   return $result;
2071 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2073   $str = ""; // Our return value will be saved in this var
2075   $color  = dechex($percentage+150);
2076   $color2 = dechex(150 - $percentage);
2077   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2079   $progress = (int)(($percentage /100)*$width);
2081   /* Abort printing out percentage, if divs are to small */
2084   /* If theres a better solution for this, use it... */
2085   $str = "
2086     <div style=\" width:".($width)."px; 
2087     height:".($height)."px;
2088   background-color:#000000;
2089 padding:1px;\">
2091           <div style=\" width:".($width)."px;
2092         background-color:#$bgcolor;
2093 height:".($height)."px;\">
2095          <div style=\" width:".$progress."px;
2096 height:".$height."px;
2097        background-color:#".$color2.$color2.$color."; \">";
2100        if(($height >10)&&($showvalue)){
2101          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2102            <b>".$percentage."%</b>
2103            </font>";
2104        }
2106        $str.= "</div></div></div>";
2108        return($str);
2112 function array_key_ics($ikey, $items)
2114   /* Gather keys, make them lowercase */
2115   $tmp= array();
2116   foreach ($items as $key => $value){
2117     $tmp[strtolower($key)]= $key;
2118   }
2120   if (isset($tmp[strtolower($ikey)])){
2121     return($tmp[strtolower($ikey)]);
2122   }
2124   return ("");
2128 function array_differs($src, $dst)
2130   /* If the count is differing, the arrays differ */
2131   if (count ($src) != count ($dst)){
2132     return (TRUE);
2133   }
2135   /* So the count is the same - lets check the contents */
2136   $differs= FALSE;
2137   foreach($src as $value){
2138     if (!in_array($value, $dst)){
2139       $differs= TRUE;
2140     }
2141   }
2143   return ($differs);
2147 function saveFilter($a_filter, $values)
2149   if (isset($_POST['regexit'])){
2150     $a_filter["regex"]= $_POST['regexit'];
2152     foreach($values as $type){
2153       if (isset($_POST[$type])) {
2154         $a_filter[$type]= "checked";
2155       } else {
2156         $a_filter[$type]= "";
2157       }
2158     }
2159   }
2161   /* React on alphabet links if needed */
2162   if (isset($_GET['search'])){
2163     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2164     if ($s == "**"){
2165       $s= "*";
2166     }
2167     $a_filter['regex']= $s;
2168   }
2170   return ($a_filter);
2174 /* Escape all preg_* relevant characters */
2175 function normalizePreg($input)
2177   return (addcslashes($input, '[]()|/.*+-'));
2181 /* Escape all LDAP filter relevant characters */
2182 function normalizeLdap($input)
2184   return (addcslashes($input, '()|'));
2188 /* Resturns the difference between to microtime() results in float  */
2189 function get_MicroTimeDiff($start , $stop)
2191   $a = split("\ ",$start);
2192   $b = split("\ ",$stop);
2194   $secs = $b[1] - $a[1];
2195   $msecs= $b[0] - $a[0]; 
2197   $ret = (float) ($secs+ $msecs);
2198   return($ret);
2202 /* Check if the given department name is valid */
2203 function is_department_name_reserved($name,$base)
2205   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2206                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2207                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2208   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2210   /* Check if name is one of the reserved names */
2211   if(in_array_ics($name,$reservedName)) {
2212     return(true);
2213   }
2215   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2216   foreach($follwedNames as $key => $names){
2217     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2218       return(true);
2219     }
2220   }
2221   return(false);
2225 function get_base_dir()
2227   global $BASE_DIR;
2229   return $BASE_DIR;
2233 function obj_is_readable($dn, $object, $attribute)
2235   global $ui;
2237   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2241 function obj_is_writable($dn, $object, $attribute)
2243   global $ui;
2245   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2249 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2251   /* Initialize variables */
2252   $ret  = array("count" => 0);  // Set count to 0
2253   $next = true;                 // if false, then skip next loops and return
2254   $cnt  = 0;                    // Current number of loops
2255   $max  = 100;                  // Just for security, prevent looops
2256   $ldap = NULL;                 // To check if created result a valid
2257   $keep = "";                   // save last failed parse string
2259   /* Check each parsed dn in ldap ? */
2260   if($config!==NULL && $verify_in_ldap){
2261     $ldap = $config->get_ldap_link();
2262   }
2264   /* Lets start */
2265   $called = false;
2266   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2268     $cnt ++;
2269     if(!preg_match("/,/",$dn)){
2270       $next = false;
2271     }
2272     $object = preg_replace("/[,].*$/","",$dn);
2273     $dn     = preg_replace("/^[^,]+,/","",$dn);
2275     $called = true;
2277     /* Check if current dn is valid */
2278     if($ldap!==NULL){
2279       $ldap->cd($dn);
2280       $ldap->cat($dn,array("dn"));
2281       if($ldap->count()){
2282         $ret[]  = $keep.$object;
2283         $keep   = "";
2284       }else{
2285         $keep  .= $object.",";
2286       }
2287     }else{
2288       $ret[]  = $keep.$object;
2289       $keep   = "";
2290     }
2291   }
2293   /* No dn was posted */
2294   if($cnt == 0 && !empty($dn)){
2295     $ret[] = $dn;
2296   }
2298   /* Append the rest */
2299   $test = $keep.$dn;
2300   if($called && !empty($test)){
2301     $ret[] = $keep.$dn;
2302   }
2303   $ret['count'] = count($ret) - 1;
2305   return($ret);
2308 /* Add "str_split" if this function is missing.
2309  * This function is only available in PHP5
2310  */
2311   if(!function_exists("str_split")){
2312     function str_split($str,$length =1)
2313     {
2314       if($length < 1 ) $length =1;
2316       $ret = array();
2317       for($i = 0 ; $i < strlen($str); $i = $i +$length){
2318         $ret[] = substr($str,$i ,$length);
2319       }
2320       return($ret);
2321     }
2322   }
2325 function get_base_from_hook($dn, $attrib)
2327   global $config;
2329   if (isset($config->current['BASE_HOOK'])){
2330     
2331     /* Call hook script - if present */
2332     $command= $config->current['BASE_HOOK'];
2334     if ($command != ""){
2335       $command.= " '".LDAP::fix($dn)."' $attrib";
2336       if (check_command($command)){
2337         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2338         exec($command, $output);
2339         if (preg_match("/^[0-9]+$/", $output[0])){
2340           return ($output[0]);
2341         } else {
2342           print_red(_("Warning - base_hook is not available. Using default base."));
2343           return ($config->current['UIDBASE']);
2344         }
2345       } else {
2346         print_red(_("Warning - base_hook is not available. Using default base."));
2347         return ($config->current['UIDBASE']);
2348       }
2350     } else {
2352       print_red(_("Warning - no base_hook defined. Using default base."));
2353       return ($config->current['UIDBASE']);
2355     }
2356   }
2359 /* Schema validation functions */
2361 function check_schema_version($class, $version)
2363   return preg_match("/\(v$version\)/", $class['DESC']);
2366 function check_schema($cfg,$rfc2307bis = FALSE)
2368   $messages= array();
2370   /* Get objectclasses */
2371   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2372   $objectclasses = $ldap->get_objectclasses();
2373   if(count($objectclasses) == 0){
2374     print_red(_("Can't get schema information from server. No schema check possible!"));
2375   }
2377   /* This is the default block used for each entry.
2378    *  to avoid unset indexes.
2379    */
2380   $def_check = array("REQUIRED_VERSION" => "0",
2381       "SCHEMA_FILES"     => array(),
2382       "CLASSES_REQUIRED" => array(),
2383       "STATUS"           => FALSE,
2384       "IS_MUST_HAVE"     => FALSE,
2385       "MSG"              => "",
2386       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2388   /* The gosa base schema */
2389   $checks['gosaObject'] = $def_check;
2390   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2391   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2392   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2393   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2395   /* GOsa Account class */
2396   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2397   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2398   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2399   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2400   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2402   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2403   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2404   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2405   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2406   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2407   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2409   /* Some other checks */
2410   foreach(array(
2411         "gosaCacheEntry"        => array("version" => "2.4"),
2412         "gosaDepartment"        => array("version" => "2.4"),
2413         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2414         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2415         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2416         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2417         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2418         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2419         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2420         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2421         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2422         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2423         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2424         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2425         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2426         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2427         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2428         "goLdapServer"          => array("version" => "2.4"),
2429         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2430         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2431         "goKrbServer"           => array("version" => "2.4"),
2432         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2433         ) as $name => $values){
2435           $checks[$name] = $def_check;
2436           if(isset($values['version'])){
2437             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2438           }
2439           if(isset($values['file'])){
2440             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2441           }
2442           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2443         }
2444   foreach($checks as $name => $value){
2445     foreach($value['CLASSES_REQUIRED'] as $class){
2447       if(!isset($objectclasses[$name])){
2448         $checks[$name]['STATUS'] = FALSE;
2449         if($value['IS_MUST_HAVE']){
2450           $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2451         }else{
2452           $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2453         }
2454       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2455         $checks[$name]['STATUS'] = FALSE;
2457         if($value['IS_MUST_HAVE']){
2458           $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2459         }else{
2460           $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2461         }
2462       }else{
2463         $checks[$name]['STATUS'] = TRUE;
2464         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2465       }
2466     }
2467   }
2469   $tmp = $objectclasses;
2471   /* The gosa base schema */
2472   $checks['posixGroup'] = $def_check;
2473   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2474   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2475   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2476   $checks['posixGroup']['STATUS']           = TRUE;
2477   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2478   $checks['posixGroup']['MSG']              = "";
2479   $checks['posixGroup']['INFO']             = "";
2481   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2482   if(isset($tmp['posixGroup'])){
2484     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2485       $checks['posixGroup']['STATUS']           = FALSE;
2486       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2487       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2488     }
2489     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2490       $checks['posixGroup']['STATUS']           = FALSE;
2491       $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2492       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2493     }
2494   }
2496   return($checks);
2502 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2504   $tmp = array(
2505         "de_DE" => "German",
2506         "fr_FR" => "French",
2507         "it_IT" => "Italian",
2508         "es_ES" => "Spanish",
2509         "en_US" => "English",
2510         "nl_NL" => "Dutch",
2511         "pl_PL" => "Polish",
2512         "sv_SE" => "Swedish",
2513         "zh_CN" => "Chinese",
2514         "ru_RU" => "Russian");
2515   
2516   $tmp2= array(
2517         "de_DE" => _("German"),
2518         "fr_FR" => _("French"),
2519         "it_IT" => _("Italian"),
2520         "es_ES" => _("Spanish"),
2521         "en_US" => _("English"),
2522         "nl_NL" => _("Dutch"),
2523         "pl_PL" => _("Polish"),
2524         "sv_SE" => _("Swedish"),
2525         "zh_CN" => _("Chinese"),
2526         "ru_RU" => _("Russian"));
2528   $ret = array();
2529   if($languages_in_own_language){
2531     $old_lang = setlocale(LC_ALL, 0);
2532     foreach($tmp as $key => $name){
2533       $lang = $key.".UTF-8";
2534       setlocale(LC_ALL, $lang);
2535       if($strip_region_tag){
2536         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2537       }else{
2538         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2539       }
2540     }
2541     setlocale(LC_ALL, $old_lang);
2542   }else{
2543     foreach($tmp as $key => $name){
2544       if($strip_region_tag){
2545         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2546       }else{
2547         $ret[$key] = _($name);
2548       }
2549     }
2550   }
2551   return($ret);
2555 /* Returns contents of the given POST variable and check magic quotes settings */
2556 function get_post($name)
2558   if(!isset($_POST[$name])){
2559     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2560     return(FALSE);
2561   }
2562   if(get_magic_quotes_gpc()){
2563     return(stripcslashes($_POST[$name]));
2564   }else{
2565     return($_POST[$name]);
2566   }
2570 /* Check if $ip1 and $ip2 represents a valid IP range 
2571  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2572  */
2573 function is_ip_range($ip1,$ip2)
2575   if(!is_ip($ip1) || !is_ip($ip2)){
2576     return(FALSE);
2577   }else{
2578     $ar1 = split("\.",$ip1);
2579     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2581     $ar2 = split("\.",$ip2);
2582     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2583     return($var1 < $var2);
2584   }
2588 /* Check if the specified IP address $address is inside the given network */
2589 function is_in_network($network, $netmask, $address)
2591   $nw= split('\.', $network);
2592   $nm= split('\.', $netmask);
2593   $ad= split('\.', $address);
2595   /* Generate inverted netmask */
2596   for ($i= 0; $i<4; $i++){
2597     $ni[$i]= 255-$nm[$i];
2598     $la[$i]= $nw[$i] | $ni[$i];
2599   }
2601   /* Transform to integer */
2602   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2603   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2604   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2606   return ($first < $curr&& $last > $curr);
2609 /* Return class name in correct case 
2610  *  mailMethodkolab =>  mailMethodKolab  ( k => K )
2611  */
2612 function get_correct_class_name($cls)
2614   global $class_mapping;
2615   if(isset($class_mapping) && is_array($class_mapping)){
2616     foreach($class_mapping as $class => $file){
2617       if(preg_match("/^".$cls."$/i",$class)){
2618         return($class);
2619       }
2620     }
2621   }
2622   return(FALSE);
2625 // change_password, changes the Password, of the given dn
2626 function change_password ($dn, $password, $mode=0, $hash= "")
2628   global $config;
2629   $newpass= "";
2631   /* Convert to lower. Methods are lowercase */
2632   $hash= strtolower($hash);
2634   // Get all available encryption Methods
2636   // NON STATIC CALL :)
2637   $tmp = new passwordMethod(get_global('config'));
2638   $available = $tmp->get_available_methods();
2640   // read current password entry for $dn, to detect the encryption Method
2641   $ldap       = $config->get_ldap_link();
2642   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2643   $attrs      = $ldap->fetch ();
2645   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2646   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2647     $deactivated = TRUE;
2648   }else{
2649     $deactivated = FALSE;
2650   }
2652   /* Is ensure that clear passwords will stay clear */
2653   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2654     $hash = "clear";
2655   }
2657   // Detect the encryption Method
2658   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2660     /* Check for supported algorithm */
2661     mt_srand((double) microtime()*1000000);
2663     /* Extract used hash */
2664     if ($hash == ""){
2665       $hash= strtolower($matches[1]);
2666     }
2668     $test = new  $available[$hash]($config);
2670   } else {
2671     // User MD5 by default
2672     $hash= "md5";
2673     $test = new  $available['md5']($config);
2674   }
2676   /* Feed password backends with information */
2677   $test->dn= $dn;
2678   $test->attrs= $attrs;
2679   $newpass= $test->generate_hash($password);
2681   // Update shadow timestamp?
2682   if (isset($attrs["shadowLastChange"][0])){
2683     $shadow= (int)(date("U") / 86400);
2684   } else {
2685     $shadow= 0;
2686   }
2688   // Write back modified entry
2689   $ldap->cd($dn);
2690   $attrs= array();
2692   // Not for groups
2693   if ($mode == 0){
2695     if ($shadow != 0){
2696       $attrs['shadowLastChange']= $shadow;
2697     }
2699     // Create SMB Password
2700     $attrs= generate_smb_nt_hash($password);
2701   }
2703  /* Readd ! if user was deactivated */
2704   if($deactivated){
2705     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2706   }
2708   $attrs['userPassword']= array();
2709   $attrs['userPassword']= $newpass;
2711   $ldap->modify($attrs);
2713   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2715   if ($ldap->error != 'Success') {
2716     print_red(sprintf(_("Setting the password failed. LDAP server says '%s'."),
2717           $ldap->get_error()));
2718   } else {
2720     /* Run backend method for change/create */
2721     $test->set_password($password);
2723     /* Find postmodify entries for this class */
2724     $command= $config->search("password", "POSTMODIFY",array('menu'));
2726     if ($command != ""){
2727       /* Walk through attribute list */
2728       $command= preg_replace("/%userPassword/", $password, $command);
2729       $command= preg_replace("/%dn/", $dn, $command);
2731       if (check_command($command)){
2732         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2733         exec($command);
2734       } else {
2735         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2736         print_red ($message);
2737       }
2738     }
2739   }
2741 // Return something like array['sambaLMPassword']= "lalla..."
2742 function generate_smb_nt_hash($password)
2744   global $config;
2745   $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2746   @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2748   exec($tmp, $ar);
2749   flush();
2750   reset($ar);
2751   $hash= current($ar);
2752   if ($hash == "")
2753   {
2754     print_red (_("Setting for SMBHASH in gosa.conf is incorrect! Can't change Samba password."));
2755   }
2756   else
2757   {
2758     list($lm,$nt)= split (":", trim($hash));
2760     if ($config->current['SAMBAVERSION'] == 3)
2761     {
2762       $attrs['sambaLMPassword']= $lm;
2763       $attrs['sambaNTPassword']= $nt;
2764       $attrs['sambaPwdLastSet']= date('U');
2765       $attrs['sambaBadPasswordCount']= "0";
2766       $attrs['sambaBadPasswordTime']= "0";
2767     } else {
2768       $attrs['lmPassword']= $lm;
2769       $attrs['ntPassword']= $nt;
2770       $attrs['pwdLastSet']= date('U');
2771     }
2772     return($attrs);
2773   }
2776 function crypt_single($string,$enc_type )
2778   return( passwordMethod::crypt_single_str($string,$enc_type));
2782 function getEntryCSN($dn)
2784   global $config;
2785   if(empty($dn) || !is_object($config)){
2786     return("");
2787   }
2789   /* Get attribute that we should use as serial number */
2790   if(isset($config->current['UNIQ_IDENTIFIER'])){
2791     $attr = $config->current['UNIQ_IDENTIFIER'];
2792   }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2793     $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2794   }
2795   if(!empty($attr)){
2796     $ldap = $config->get_ldap_link();
2797     $ldap->cat($dn,array($attr));
2798     $csn = $ldap->fetch();
2799     if(isset($csn[$attr][0])){
2800       return($csn[$attr][0]);
2801     }
2802   }
2803   return("");
2806 /* This function returns the offset for the default timezone. 
2807  * $stamp is used to detect summer or winter time.
2808  * In case of PHP5, the integrated timezone functions are used.
2809  * For PHP4 we query an array for offset and add summertime hour.
2810  */
2811 function get_default_timezone($stamp = NULL)
2813   global $config;
2814   $tz ="";
2816   /* Default return value if zone could not be detected */
2817   $zone = array("name" => "unconfigured", "value" => 0);
2819   /* Use current timestamp if $stamp is not set */
2820   if($stamp === NULL){
2821     $stamp = time();
2822   }
2824   /* Is there a timezone configured in the gosa configuration (gosa.conf) */
2825   if(isset($config->current['TIMEZONE']) || isset($config->data['MAIN']['TIMEZONE'])){
2827     /* Get zonename */
2828     if(isset($config->current['TIMEZONE'])){
2829       $tz = $config->current['TIMEZONE'];
2830     }else{
2831       $tz = $config->data['MAIN']['TIMEZONE'];
2832     }
2834     if(!@date_default_timezone_set($tz)){
2835       print_red(sprintf(_("The timezone setting \"".$tz."\" in your gosa.conf is not valid. Can not calculate correct timezone offest."),$tz));
2836     }
2837     $tz_delta = date("Z", $stamp);
2838     $tz_delta = $tz_delta / 3600 ;
2839     return(array("name" => $tz, "value" => $tz_delta));
2841   }
2842   return($zone);
2846 /* Return zone informations */
2847 function _get_tz_zones()
2849   $timezones = array(
2850       'Africa/Abidjan' => 0,
2851       'Africa/Accra' => 0,
2852       'Africa/Addis_Ababa' => 10800,
2853       'Africa/Algiers' => 3600,
2854       'Africa/Asmera' => 10800,
2855       'Africa/Bamako' => 0,
2856       'Africa/Bangui' => 3600,
2857       'Africa/Banjul' => 0,
2858       'Africa/Bissau' => 0,
2859       'Africa/Blantyre' => 7200,
2860       'Africa/Brazzaville' => 3600,
2861       'Africa/Bujumbura' => 7200,
2862       'Africa/Cairo' => 7200,
2863       'Africa/Casablanca' => 0,
2864       'Africa/Ceuta' => 3600,
2865       'Africa/Conakry' => 0,
2866       'Africa/Dakar' => 0,
2867       'Africa/Dar_es_Salaam' => 10800,
2868       'Africa/Djibouti' => 10800,
2869       'Africa/Douala' => 3600,
2870       'Africa/El_Aaiun' => 0,
2871       'Africa/Freetown' => 0,
2872       'Africa/Gaborone' => 7200,
2873       'Africa/Harare' => 7200,
2874       'Africa/Johannesburg' => 7200,
2875       'Africa/Kampala' => 10800,
2876       'Africa/Khartoum' => 10800,
2877       'Africa/Kigali' => 7200,
2878       'Africa/Kinshasa' => 3600,
2879       'Africa/Lagos' => 3600,
2880       'Africa/Libreville' => 3600,
2881       'Africa/Lome' => 0,
2882       'Africa/Luanda' => 3600,
2883       'Africa/Lubumbashi' => 7200,
2884       'Africa/Lusaka' => 7200,
2885       'Africa/Malabo' => 3600,
2886       'Africa/Maputo' => 7200,
2887       'Africa/Maseru' => 7200,
2888       'Africa/Mbabane' => 7200,
2889       'Africa/Mogadishu' => 10800,
2890       'Africa/Monrovia' => 0,
2891       'Africa/Nairobi' => 10800,
2892       'Africa/Ndjamena' => 3600,
2893       'Africa/Niamey' => 3600,
2894       'Africa/Nouakchott' => 0,
2895       'Africa/Ouagadougou' => 0,
2896       'Africa/Porto-Novo' => 3600,
2897       'Africa/Sao_Tome' => 0,
2898       'Africa/Timbuktu' => 0,
2899       'Africa/Tripoli' => 7200,
2900       'Africa/Tunis' => 3600,
2901       'Africa/Windhoek' => 3600,
2902       'America/Adak' => -36000,
2903       'America/Anchorage' => -32400,
2904       'America/Anguilla' => -14400,
2905       'America/Antigua' => -14400,
2906       'America/Araguaina' => -10800,
2907       'America/Argentina/Buenos_Aires' => 0,
2908       'America/Argentina/Catamarca' => 0,
2909       'America/Argentina/ComodRivadavia' => 0,
2910       'America/Argentina/Cordoba' => 0,
2911       'America/Argentina/Jujuy' => 0,
2912       'America/Argentina/La_Rioja' => 0,
2913       'America/Argentina/Mendoza' => 0,
2914       'America/Argentina/Rio_Gallegos' => 0,
2915       'America/Argentina/San_Juan' => 0,
2916       'America/Argentina/Tucuman' => 0,
2917       'America/Argentina/Ushuaia' => 0,
2918       'America/Aruba' => -14400,
2919       'America/Asuncion' => -14400,
2920       'America/Atikokan' => 0,
2921       'America/Atka' => -36000,
2922       'America/Bahia' => 0,
2923       'America/Barbados' => -14400,
2924       'America/Belem' => -10800,
2925       'America/Belize' => -21600,
2926       'America/Blanc-Sablon' => 0,
2927       'America/Boa_Vista' => -14400,
2928       'America/Bogota' => -18000,
2929       'America/Boise' => -25200,
2930       'America/Buenos_Aires' => -10800,
2931       'America/Cambridge_Bay' => -25200,
2932       'America/Campo_Grande' => 0,
2933       'America/Cancun' => -21600,
2934       'America/Caracas' => -14400,
2935       'America/Catamarca' => -10800,
2936       'America/Cayenne' => -10800,
2937       'America/Cayman' => -18000,
2938       'America/Chicago' => -21600,
2939       'America/Chihuahua' => -25200,
2940       'America/Coral_Harbour' => 0,
2941       'America/Cordoba' => -10800,
2942       'America/Costa_Rica' => -21600,
2943       'America/Cuiaba' => -14400,
2944       'America/Curacao' => -14400,
2945       'America/Danmarkshavn' => 0,
2946       'America/Dawson' => -28800,
2947       'America/Dawson_Creek' => -25200,
2948       'America/Denver' => -25200,
2949       'America/Detroit' => -18000,
2950       'America/Dominica' => -14400,
2951       'America/Edmonton' => -25200,
2952       'America/Eirunepe' => -18000,
2953       'America/El_Salvador' => -21600,
2954       'America/Ensenada' => -28800,
2955       'America/Fort_Wayne' => -18000,
2956       'America/Fortaleza' => -10800,
2957       'America/Glace_Bay' => -14400,
2958       'America/Godthab' => -10800,
2959       'America/Goose_Bay' => -14400,
2960       'America/Grand_Turk' => -18000,
2961       'America/Grenada' => -14400,
2962       'America/Guadeloupe' => -14400,
2963       'America/Guatemala' => -21600,
2964       'America/Guayaquil' => -18000,
2965       'America/Guyana' => -14400,
2966       'America/Halifax' => -14400,
2967       'America/Havana' => -18000,
2968       'America/Hermosillo' => -25200,
2969       'America/Indiana/Indianapolis' => -18000,
2970       'America/Indiana/Knox' => -18000,
2971       'America/Indiana/Marengo' => -18000,
2972       'America/Indiana/Petersburg' => 0,
2973       'America/Indiana/Vevay' => -18000,
2974       'America/Indiana/Vincennes' => 0,
2975       'America/Indianapolis' => -18000,
2976       'America/Inuvik' => -25200,
2977       'America/Iqaluit' => -18000,
2978       'America/Jamaica' => -18000,
2979       'America/Jujuy' => -10800,
2980       'America/Juneau' => -32400,
2981       'America/Kentucky/Louisville' => -18000,
2982       'America/Kentucky/Monticello' => -18000,
2983       'America/Knox_IN' => -18000,
2984       'America/La_Paz' => -14400,
2985       'America/Lima' => -18000,
2986       'America/Los_Angeles' => -28800,
2987       'America/Louisville' => -18000,
2988       'America/Maceio' => -10800,
2989       'America/Managua' => -21600,
2990       'America/Manaus' => -14400,
2991       'America/Martinique' => -14400,
2992       'America/Mazatlan' => -25200,
2993       'America/Mendoza' => -10800,
2994       'America/Menominee' => -21600,
2995       'America/Merida' => -21600,
2996       'America/Mexico_City' => -21600,
2997       'America/Miquelon' => -10800,
2998       'America/Moncton' => 0,
2999       'America/Monterrey' => -21600,
3000       'America/Montevideo' => -10800,
3001       'America/Montreal' => -18000,
3002       'America/Montserrat' => -14400,
3003       'America/Nassau' => -18000,
3004       'America/New_York' => -18000,
3005       'America/Nipigon' => -18000,
3006       'America/Nome' => -32400,
3007       'America/Noronha' => -7200,
3008       'America/North_Dakota/Center' => -21600,
3009       'America/North_Dakota/New_Salem' => 0,
3010       'America/Panama' => -18000,
3011       'America/Pangnirtung' => -18000,
3012       'America/Paramaribo' => -10800,
3013       'America/Phoenix' => -25200,
3014       'America/Port-au-Prince' => -18000,
3015       'America/Port_of_Spain' => -14400,
3016       'America/Porto_Acre' => -18000,
3017       'America/Porto_Velho' => -14400,
3018       'America/Puerto_Rico' => -14400,
3019       'America/Rainy_River' => -21600,
3020       'America/Rankin_Inlet' => -21600,
3021       'America/Recife' => -10800,
3022       'America/Regina' => -21600,
3023       'America/Rio_Branco' => -18000,
3024       'America/Rosario' => -10800,
3025       'America/Santiago' => -14400,
3026       'America/Santo_Domingo' => -14400,
3027       'America/Sao_Paulo' => -10800,
3028       'America/Scoresbysund' => -3600,
3029       'America/Shiprock' => -25200,
3030       'America/St_Johns' => -12600,
3031       'America/St_Kitts' => -14400,
3032       'America/St_Lucia' => -14400,
3033       'America/St_Thomas' => -14400,
3034       'America/St_Vincent' => -14400,
3035       'America/Swift_Current' => -21600,
3036       'America/Tegucigalpa' => -21600,
3037       'America/Thule' => -14400,
3038       'America/Thunder_Bay' => -18000,
3039       'America/Tijuana' => -28800,
3040       'America/Toronto' => 0,
3041       'America/Tortola' => -14400,
3042       'America/Vancouver' => -28800,
3043       'America/Virgin' => -14400,
3044       'America/Whitehorse' => -28800,
3045       'America/Winnipeg' => -21600,
3046       'America/Yakutat' => -32400,
3047       'America/Yellowknife' => -25200,
3048       'Antarctica/Casey' => 28800,
3049       'Antarctica/Davis' => 25200,
3050       'Antarctica/DumontDUrville' => 36000,
3051       'Antarctica/Mawson' => 21600,
3052       'Antarctica/McMurdo' => 43200,
3053       'Antarctica/Palmer' => -14400,
3054       'Antarctica/Rothera' => 0,
3055       'Antarctica/South_Pole' => 43200,
3056       'Antarctica/Syowa' => 10800,
3057       'Antarctica/VostokArctic/Longyearbyen' => 0,
3058       'Asia/Aden' => 10800,
3059       'Asia/Almaty' => 21600,
3060       'Asia/Amman' => 7200,
3061       'Asia/Anadyr' => 43200,
3062       'Asia/Aqtau' => 14400,
3063       'Asia/Aqtobe' => 18000,
3064       'Asia/Ashgabat' => 18000,
3065       'Asia/Ashkhabad' => 18000,
3066       'Asia/Baghdad' => 10800,
3067       'Asia/Bahrain' => 10800,
3068       'Asia/Baku' => 14400,
3069       'Asia/Bangkok' => 25200,
3070       'Asia/Beirut' => 7200,
3071       'Asia/Bishkek' => 18000,
3072       'Asia/Brunei' => 28800,
3073       'Asia/Calcutta' => 19800,
3074       'Asia/Choibalsan' => 32400,
3075       'Asia/Chongqing' => 28800,
3076       'Asia/Chungking' => 28800,
3077       'Asia/Colombo' => 21600,
3078       'Asia/Dacca' => 21600,
3079       'Asia/Damascus' => 7200,
3080       'Asia/Dhaka' => 21600,
3081       'Asia/Dili' => 32400,
3082       'Asia/Dubai' => 14400,
3083       'Asia/Dushanbe' => 18000,
3084       'Asia/Gaza' => 7200,
3085       'Asia/Harbin' => 28800,
3086       'Asia/Hong_Kong' => 28800,
3087       'Asia/Hovd' => 25200,
3088       'Asia/Irkutsk' => 28800,
3089       'Asia/Istanbul' => 7200,
3090       'Asia/Jakarta' => 25200,
3091       'Asia/Jayapura' => 32400,
3092       'Asia/Jerusalem' => 7200,
3093       'Asia/Kabul' => 16200,
3094       'Asia/Kamchatka' => 43200,
3095       'Asia/Karachi' => 18000,
3096       'Asia/Kashgar' => 28800,
3097       'Asia/Katmandu' => 20700,
3098       'Asia/Krasnoyarsk' => 25200,
3099       'Asia/Kuala_Lumpur' => 28800,
3100       'Asia/Kuching' => 28800,
3101       'Asia/Kuwait' => 10800,
3102       'Asia/Macao' => 28800,
3103       'Asia/Macau' => 0,
3104       'Asia/Magadan' => 39600,
3105       'Asia/Makassar' => 0,
3106       'Asia/Manila' => 28800,
3107       'Asia/Muscat' => 14400,
3108       'Asia/Nicosia' => 7200,
3109       'Asia/Novosibirsk' => 21600,
3110       'Asia/Omsk' => 21600,
3111       'Asia/Oral' => 0,
3112       'Asia/Phnom_Penh' => 25200,
3113       'Asia/Pontianak' => 25200,
3114       'Asia/Pyongyang' => 32400,
3115       'Asia/Qatar' => 10800,
3116       'Asia/Qyzylorda' => 0,
3117       'Asia/Rangoon' => 23400,
3118       'Asia/Riyadh' => 10800,
3119       'Asia/Saigon' => 25200,
3120       'Asia/Sakhalin' => 36000,
3121       'Asia/Samarkand' => 18000,
3122       'Asia/Seoul' => 32400,
3123       'Asia/Shanghai' => 28800,
3124       'Asia/Singapore' => 28800,
3125       'Asia/Taipei' => 28800,
3126       'Asia/Tashkent' => 18000,
3127       'Asia/Tbilisi' => 14400,
3128       'Asia/Tehran' => 12600,
3129       'Asia/Tel_Aviv' => 7200,
3130       'Asia/Thimbu' => 21600,
3131       'Asia/Thimphu' => 21600,
3132       'Asia/Tokyo' => 32400,
3133       'Asia/Ujung_Pandang' => 28800,
3134       'Asia/Ulaanbaatar' => 28800,
3135       'Asia/Ulan_Bator' => 28800,
3136       'Asia/Urumqi' => 28800,
3137       'Asia/Vientiane' => 25200,
3138       'Asia/Vladivostok' => 36000,
3139       'Asia/Yakutsk' => 32400,
3140       'Asia/Yekaterinburg' => 18000,
3141       'Asia/YerevanAtlantic/Azores' => 0,
3142       'Atlantic/Bermuda' => -14400,
3143       'Atlantic/Canary' => 0,
3144       'Atlantic/Cape_Verde' => -3600,
3145       'Atlantic/Faeroe' => 0,
3146       'Atlantic/Jan_Mayen' => 3600,
3147       'Atlantic/Madeira' => 0,
3148       'Atlantic/Reykjavik' => 0,
3149       'Atlantic/South_Georgia' => -7200,
3150       'Atlantic/St_Helena' => 0,
3151       'Atlantic/Stanley' => -14400,
3152       'Australia/ACT' => 36000,
3153       'Australia/Adelaide' => 34200,
3154       'Australia/Brisbane' => 36000,
3155       'Australia/Broken_Hill' => 34200,
3156       'Australia/Canberra' => 36000,
3157       'Australia/Currie' => 0,
3158       'Australia/Darwin' => 34200,
3159       'Australia/Hobart' => 36000,
3160       'Australia/LHI' => 37800,
3161       'Australia/Lindeman' => 36000,
3162       'Australia/Lord_Howe' => 37800,
3163       'Australia/Melbourne' => 36000,
3164       'Australia/NSW' => 36000,
3165       'Australia/North' => 34200,
3166       'Australia/Perth' => 28800,
3167       'Australia/Queensland' => 36000,
3168       'Australia/South' => 34200,
3169       'Australia/Sydney' => 36000,
3170       'Australia/Tasmania' => 36000,
3171       'Australia/Victoria' => 36000,
3172       'Australia/West' => 28800,
3173       'Australia/Yancowinna' => 34200,
3174       'Europe/Amsterdam' => 3600,
3175       'Europe/Andorra' => 3600,
3176       'Europe/Athens' => 7200,
3177       'Europe/Belfast' => 0,
3178       'Europe/Belgrade' => 3600,
3179       'Europe/Berlin' => 3600,
3180       'Europe/Bratislava' => 3600,
3181       'Europe/Brussels' => 3600,
3182       'Europe/Bucharest' => 7200,
3183       'Europe/Budapest' => 3600,
3184       'Europe/Chisinau' => 7200,
3185       'Europe/Copenhagen' => 3600,
3186       'Europe/Dublin' => 0,
3187       'Europe/Gibraltar' => 3600,
3188       'Europe/Guernsey' => 0,
3189       'Europe/Helsinki' => 7200,
3190       'Europe/Isle_of_Man' => 0,
3191       'Europe/Istanbul' => 7200,
3192       'Europe/Jersey' => 0,
3193       'Europe/Kaliningrad' => 7200,
3194       'Europe/Kiev' => 7200,
3195       'Europe/Lisbon' => 0,
3196       'Europe/Ljubljana' => 3600,
3197       'Europe/London' => 0,
3198       'Europe/Luxembourg' => 3600,
3199       'Europe/Madrid' => 3600,
3200       'Europe/Malta' => 3600,
3201       'Europe/Mariehamn' => 0,
3202       'Europe/Minsk' => 7200,
3203       'Europe/Monaco' => 3600,
3204       'Europe/Moscow' => 10800,
3205       'Europe/Nicosia' => 7200,
3206       'Europe/Oslo' => 3600,
3207       'Europe/Paris' => 3600,
3208       'Europe/Prague' => 3600,
3209       'Europe/Riga' => 7200,
3210       'Europe/Rome' => 3600,
3211       'Europe/Samara' => 14400,
3212       'Europe/San_Marino' => 3600,
3213       'Europe/Sarajevo' => 3600,
3214       'Europe/Simferopol' => 7200,
3215       'Europe/Skopje' => 3600,
3216       'Europe/Sofia' => 7200,
3217       'Europe/Stockholm' => 3600,
3218       'Europe/Tallinn' => 7200,
3219       'Europe/Tirane' => 3600,
3220       'Europe/Tiraspol' => 7200,
3221       'Europe/Uzhgorod' => 7200,
3222       'Europe/Vaduz' => 3600,
3223       'Europe/Vatican' => 3600,
3224       'Europe/Vienna' => 3600,
3225       'Europe/Vilnius' => 7200,
3226       'Europe/Volgograd' => 0,
3227       'Europe/Warsaw' => 3600,
3228       'Europe/Zagreb' => 3600,
3229       'Europe/Zaporozhye' => 7200,
3230       'Europe/Zurich' => 3600,
3231       'Indian/Antananarivo' => 10800,
3232       'Indian/Chagos' => 21600,
3233       'Indian/Christmas' => 25200,
3234       'Indian/Cocos' => 23400,
3235       'Indian/Comoro' => 10800,
3236       'Indian/Kerguelen' => 18000,
3237       'Indian/Mahe' => 14400,
3238       'Indian/Maldives' => 18000,
3239       'Indian/Mauritius' => 14400,
3240       'Indian/Mayotte' => 10800,
3241       'Indian/Reunion' => 14400,
3242       'Pacific/Apia' => -39600,
3243       'Pacific/Auckland' => 43200,
3244       'Pacific/Chatham' => 45900,
3245       'Pacific/Easter' => -21600,
3246       'Pacific/Efate' => 39600,
3247       'Pacific/Enderbury' => 46800,
3248       'Pacific/Fakaofo' => -36000,
3249       'Pacific/Fiji' => 43200,
3250       'Pacific/Funafuti' => 43200,
3251       'Pacific/Galapagos' => -21600,
3252       'Pacific/Gambier' => -32400,
3253       'Pacific/Guadalcanal' => 39600,
3254       'Pacific/Guam' => 36000,
3255       'Pacific/Honolulu' => -36000,
3256       'Pacific/Johnston' => -36000,
3257       'Pacific/Kiritimati' => 50400,
3258       'Pacific/Kosrae' => 39600,
3259       'Pacific/Kwajalein' => 43200,
3260       'Pacific/Majuro' => 43200,
3261       'Pacific/Marquesas' => -34200,
3262       'Pacific/Midway' => -39600,
3263       'Pacific/Nauru' => 43200,
3264       'Pacific/Niue' => -39600,
3265       'Pacific/Norfolk' => 41400,
3266       'Pacific/Noumea' => 39600,
3267       'Pacific/Pago_Pago' => -39600,
3268       'Pacific/Palau' => 32400,
3269       'Pacific/Pitcairn' => -28800,
3270       'Pacific/Ponape' => 39600,
3271       'Pacific/Port_Moresby' => 36000,
3272       'Pacific/Rarotonga' => -36000,
3273       'Pacific/Saipan' => 36000,
3274       'Pacific/Samoa' => -39600,
3275       'Pacific/Tahiti' => -36000,
3276       'Pacific/Tarawa' => 43200,
3277       'Pacific/Tongatapu' => 46800,
3278       'Pacific/Truk' => 36000,
3279       'Pacific/Wake' => 43200,
3280       'Pacific/Wallis' => 43200,
3281       'Pacific/Yap' => 36000 );          
3283   $dst_timezones = array (  
3284       'America/Adak' => 1,
3285       'America/Atka' => 1,
3286       'America/Anchorage' => 1,
3287       'America/Juneau' => 1,
3288       'America/Nome' => 1,
3289       'America/Yakutat' => 1,
3290       'America/Dawson' => 1,
3291       'America/Ensenada' => 1,
3292       'America/Los_Angeles' => 1,
3293       'America/Tijuana' => 1,
3294       'America/Vancouver' => 1,
3295       'America/Whitehorse' => 1,
3296       'America/Boise' => 1,
3297       'America/Cambridge_Bay' => 1,
3298       'America/Chihuahua' => 1,
3299       'America/Denver' => 1,
3300       'America/Edmonton' => 1,
3301       'America/Inuvik' => 1,
3302       'America/Mazatlan' => 1,
3303       'America/Shiprock' => 1,
3304       'America/Yellowknife' => 1,
3305       'America/Cancun' => 1,
3306       'America/Chicago' => 1,
3307       'America/Menominee' => 1,
3308       'America/Merida' => 1,
3309       'America/Monterrey' => 1,
3310       'America/North_Dakota/Center' => 1,
3311       'America/Rainy_River' => 1,
3312       'America/Rankin_Inlet' => 1,
3313       'America/Winnipeg' => 1,
3314       'Pacific/Easter' => 1,
3315       'America/Detroit' => 1,
3316       'America/Grand_Turk' => 1,
3317       'America/Havana' => 1,
3318       'America/Iqaluit' => 1,
3319       'America/Kentucky/Louisville' => 1,
3320       'America/Kentucky/Monticello' => 1,
3321       'America/Louisville' => 1,
3322       'America/Montreal' => 1,
3323       'America/Nassau' => 1,
3324       'America/New_York' => 1,
3325       'America/Nipigon' => 1,
3326       'America/Pangnirtung' => 1,
3327       'America/Thunder_Bay' => 1,
3328       'America/Asuncion' => 1,
3329       'America/Cuiaba' => 1,
3330       'America/Glace_Bay' => 1,
3331       'America/Goose_Bay' => 1,
3332       'America/Halifax' => 1,
3333       'America/Santiago' => 1,
3334       'Antarctica/Palmer' => 1,
3335       'Atlantic/Bermuda' => 1,
3336       'Atlantic/Stanley' => 1,
3337       'America/St_Johns' => 1,
3338       'America/Araguaina' => 1,
3339       'America/Fortaleza' => 1,
3340       'America/Godthab' => 1,
3341       'America/Maceio' => 1,
3342       'America/Miquelon' => 1,
3343       'America/Recife' => 1,
3344       'America/Sao_Paulo' => 1,
3345       'America/Scoresbysund' => 1,
3346       'Atlantic/Canary' => 1,
3347       'Atlantic/Faeroe' => 1,
3348       'Atlantic/Madeira' => 1,
3349       'Europe/Belfast' => 1,
3350       'Europe/Dublin' => 1,
3351       'Europe/Lisbon' => 1,
3352       'Europe/London' => 1,
3353       'Africa/Ceuta' => 1,
3354       'Africa/Windhoek' => 1,
3355       'Atlantic/Jan_Mayen' => 1,
3356       'Europe/Amsterdam' => 1,
3357       'Europe/Andorra' => 1,
3358       'Europe/Belgrade' => 1,
3359       'Europe/Berlin' => 1,
3360       'Europe/Bratislava' => 1,
3361       'Europe/Brussels' => 1,
3362       'Europe/Budapest' => 1,
3363       'Europe/Copenhagen' => 1,
3364       'Europe/Gibraltar' => 1,
3365       'Europe/Ljubljana' => 1,
3366       'Europe/Luxembourg' => 1,
3367       'Europe/Madrid' => 1,
3368       'Europe/Malta' => 1,
3369       'Europe/Monaco' => 1,
3370       'Europe/Oslo' => 1,
3371       'Europe/Paris' => 1,
3372       'Europe/Prague' => 1,
3373       'Europe/Rome' => 1,
3374       'Europe/San_Marino' => 1,
3375       'Europe/Sarajevo' => 1,
3376       'Europe/Skopje' => 1,
3377       'Europe/Stockholm' => 1,
3378       'Europe/Tirane' => 1,
3379       'Europe/Vaduz' => 1,
3380       'Europe/Vatican' => 1,
3381       'Europe/Vienna' => 1,
3382       'Europe/Warsaw' => 1,
3383       'Europe/Zagreb' => 1,
3384       'Europe/Zurich' => 1,
3385       'Africa/Cairo' => 1,
3386       'Asia/Amman' => 1,
3387       'Asia/Beirut' => 1,
3388       'Asia/Damascus' => 1,
3389       'Asia/Gaza' => 1,
3390       'Asia/Istanbul' => 1,
3391       'Asia/Jerusalem' => 1,
3392       'Asia/Nicosia' => 1,
3393       'Asia/Tel_Aviv' => 1,
3394       'Europe/Athens' => 1,
3395       'Europe/Bucharest' => 1,
3396       'Europe/Chisinau' => 1,
3397       'Europe/Helsinki' => 1,
3398       'Europe/Istanbul' => 1,
3399       'Europe/Kaliningrad' => 1,
3400       'Europe/Kiev' => 1,
3401       'Europe/Minsk' => 1,
3402       'Europe/Nicosia' => 1,
3403       'Europe/Riga' => 1,
3404       'Europe/Simferopol' => 1,
3405       'Europe/Sofia' => 1,
3406       'Europe/Tiraspol' => 1,
3407       'Europe/Uzhgorod' => 1,
3408       'Europe/Zaporozhye' => 1,
3409       'Asia/Baghdad' => 1,
3410       'Europe/Moscow' => 1,
3411       'Asia/Tehran' => 1,
3412       'Asia/Aqtau' => 1,
3413       'Asia/Baku' => 1,
3414       'Asia/Tbilisi' => 1,
3415       'Europe/Samara' => 1,
3416       'Asia/Aqtobe' => 1,
3417       'Asia/Bishkek' => 1,
3418       'Asia/Yekaterinburg' => 1,
3419       'Asia/Almaty' => 1,
3420       'Asia/Novosibirsk' => 1,
3421       'Asia/Omsk' => 1,
3422       'Asia/Krasnoyarsk' => 1,
3423       'Asia/Irkutsk' => 1,
3424       'Asia/Yakutsk' => 1,
3425       'Australia/Adelaide' => 1,
3426       'Australia/Broken_Hill' => 1,
3427       'Australia/South' => 1,
3428       'Australia/Yancowinna' => 1,
3429       'Asia/Sakhalin' => 1,
3430       'Asia/Vladivostok' => 1,
3431       'Australia/ACT' => 1,
3432       'Australia/Canberra' => 1,
3433       'Australia/Hobart' => 1,
3434       'Australia/Melbourne' => 1,
3435       'Australia/NSW' => 1,
3436       'Australia/Sydney' => 1,
3437       'Australia/Tasmania' => 1,
3438       'Australia/Victoria' => 1,
3439       'Australia/LHI' => 1,
3440       'Australia/Lord_Howe' => 1,
3441       'Asia/Magadan' => 1,
3442       'Antarctica/McMurdo' => 1,
3443       'Antarctica/South_Pole' => 1,
3444       'Asia/Anadyr' => 1,
3445       'Asia/Kamchatka' => 1,
3446       'Pacific/Auckland' => 1,
3447       'Pacific/Chatham' => 1,
3448       );  
3449   return(array("TIMEZONES" => $timezones, "DST_ZONES" => $dst_timezones));
3453 function display_error_page()
3455   $smarty= get_smarty();
3456   $smarty->display(get_template_path('headers.tpl'));
3457   echo "<body>".msg_dialog::get_dialogs()."</body></html>";
3458   exit();
3461 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3462 ?>