Code

Added TZ fix
[gosa.git] / 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('NULL',0x05);
38 define('OBJECT_IDENTIFIER ',0x06);
39 define('SEQUENCE',0x10);
40 define('SEQUENCE_OF',0x10);
41 define('SET',0x11);
42 define('SET_OF',0x11);
43 define('DEBUG',false);
44 define('HDB_KU_MKEY',0x484442);
45 define('TWO_BIT_SHIFTS',0x7efc);
46 define('DES_CBC_CRC',1);
47 define('DES_CBC_MD4',2);
48 define('DES_CBC_MD5',3);
49 define('DES3_CBC_MD5',5);
50 define('DES3_CBC_SHA1',16);
52 /* Define globals for revision comparing */
53 $svn_path = '$HeadURL$';
54 $svn_revision = '$Revision$';
56 /* Include required files */
57 require_once("class_location.inc");
58 require_once ("functions_debug.inc");
59 require_once ("functions_dns.inc");
60 require_once ("accept-to-gettext.inc");
62 /* Define constants for debugging */
63 define ("DEBUG_TRACE",   1);
64 define ("DEBUG_LDAP",    2);
65 define ("DEBUG_MYSQL",   4);
66 define ("DEBUG_SHELL",   8);
67 define ("DEBUG_POST",   16);
68 define ("DEBUG_SESSION",32);
69 define ("DEBUG_CONFIG", 64);
70 define ("DEBUG_ACL",    128);
72 /* Rewrite german 'umlauts' and spanish 'accents'
73    to get better results */
74 $REWRITE= array( "ä" => "ae",
75     "ö" => "oe",
76     "ü" => "ue",
77     "Ä" => "Ae",
78     "Ö" => "Oe",
79     "Ü" => "Ue",
80     "ß" => "ss",
81     "á" => "a",
82     "é" => "e",
83     "í" => "i",
84     "ó" => "o",
85     "ú" => "u",
86     "Á" => "A",
87     "É" => "E",
88     "Í" => "I",
89     "Ó" => "O",
90     "Ú" => "U",
91     "ñ" => "ny",
92     "Ñ" => "Ny" );
95 /* Class autoloader */
96 function __autoload($class_name) {
97     global $class_mapping, $BASE_DIR;
98     if (isset($class_mapping[$class_name])){
99       require_once($BASE_DIR."/".$class_mapping[$class_name]);
100     } else {
101       echo _("Fatal: cannot load class \"$class_name\" - execution aborted");
102     }
105 /* Create seed with microseconds */
106 function make_seed() {
107   list($usec, $sec) = explode(' ', microtime());
108   return (float) $sec + ((float) $usec * 100000);
112 /* Debug level action */
113 function DEBUG($level, $line, $function, $file, $data, $info="")
115   if ($_SESSION['DEBUGLEVEL'] & $level){
116     $output= "DEBUG[$level] ";
117     if ($function != ""){
118       $output.= "($file:$function():$line) - $info: ";
119     } else {
120       $output.= "($file:$line) - $info: ";
121     }
122     echo $output;
123     if (is_array($data)){
124       print_a($data);
125     } else {
126       echo "'$data'";
127     }
128     echo "<br>";
129   }
133 function get_browser_language()
135   /* Try to use users primary language */
136   global $config;
137   $ui= get_userinfo();
138   if ($ui !== NULL){
139     if ($ui->language != ""){
140       return ($ui->language.".UTF-8");
141     }
142   }
144   /* Check for global language settings in gosa.conf */
145   if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
146     $lang = $config->data['MAIN']['LANG'];
147     if(!preg_match("/utf/i",$lang)){
148       $lang .= ".UTF-8";
149     }
150     return($lang);
151   }
152  
153   /* Load supported languages */
154   $gosa_languages= get_languages();
156   /* Move supported languages to flat list */
157   $langs= array();
158   foreach($gosa_languages as $lang => $dummy){
159     $langs[]= $lang.'.UTF-8';
160   }
162   /* Return gettext based string */
163   return (al2gt($langs, 'text/html'));
167 /* Rewrite ui object to another dn */
168 function change_ui_dn($dn, $newdn)
170   $ui= $_SESSION['ui'];
171   if ($ui->dn == $dn){
172     $ui->dn= $newdn;
173     $_SESSION['ui']= $ui;
174   }
178 /* Return theme path for specified file */
179 function get_template_path($filename= '', $plugin= FALSE, $path= "")
181   global $config, $BASE_DIR;
183   if (!@isset($config->data['MAIN']['THEME'])){
184     $theme= 'default';
185   } else {
186     $theme= $config->data['MAIN']['THEME'];
187   }
189   /* Return path for empty filename */
190   if ($filename == ''){
191     return ("themes/$theme/");
192   }
194   /* Return plugin dir or root directory? */
195   if ($plugin){
196     if ($path == ""){
197       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
198     } else {
199       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
200     }
201     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
202       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
203     }
204     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
205       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
206     }
207     if ($path == ""){
208       return ($_SESSION['plugin_dir']."/$filename");
209     } else {
210       return ($path."/$filename");
211     }
212   } else {
213     if (file_exists("themes/$theme/$filename")){
214       return ("themes/$theme/$filename");
215     }
216     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
217       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
218     }
219     if (file_exists("themes/default/$filename")){
220       return ("themes/default/$filename");
221     }
222     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
223       return ("$BASE_DIR/ihtml/themes/default/$filename");
224     }
225     return ($filename);
226   }
230 function array_remove_entries($needles, $haystack)
232   $tmp= array();
234   /* Loop through entries to be removed */
235   foreach ($haystack as $entry){
236     if (!in_array($entry, $needles)){
237       $tmp[]= $entry;
238     }
239   }
241   return ($tmp);
245 function gosa_array_merge($ar1,$ar2)
247   if(!is_array($ar1) || !is_array($ar2)){
248     trigger_error("Specified parameter(s) are not valid arrays.");
249   }else{
250     return(array_values(array_unique(array_merge($ar1,$ar2))));
251   }
256 function gosa_log ($message)
258   global $ui;
260   /* Preset to something reasonable */
261   $username= " unauthenticated";
263   /* Replace username if object is present */
264   if (isset($ui)){
265     if ($ui->username != ""){
266       $username= "[$ui->username]";
267     } else {
268       $username= "unknown";
269     }
270   }
272   syslog(LOG_INFO,"GOsa$username: $message");
276 function ldap_init ($server, $base, $binddn='', $pass='')
278   global $config;
280   $ldap = new LDAP ($binddn, $pass, $server,
281       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
282       isset($config->current['TLS']) && $config->current['TLS'] == "true");
284   /* Sadly we've no proper return values here. Use the error message instead. */
285   if (!preg_match("/Success/i", $ldap->error)){
286     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
287     exit();
288   }
290   /* Preset connection base to $base and return to caller */
291   $ldap->cd ($base);
292   return $ldap;
296 function ldap_login_user ($username, $password)
298   global $config;
300   /* look through the entire ldap */
301   $ldap = $config->get_ldap_link();
302   if (!preg_match("/Success/i", $ldap->error)){
303     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
304     $smarty= get_smarty();
305     $smarty->display(get_template_path('headers.tpl'));
306     echo "<body>".$_SESSION['errors']."</body></html>";
307     exit();
308   }
309   $ldap->cd($config->current['BASE']);
310   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
312   /* get results, only a count of 1 is valid */
313   switch ($ldap->count()){
315     /* user not found */
316     case 0:     return (NULL);
318             /* valid uniq user */
319     case 1: 
320             break;
322             /* found more than one matching id */
323     default:
324             print_red(_("Username / UID is not unique. Please check your LDAP database."));
325             return (NULL);
326   }
328   /* LDAP schema is not case sensitive. Perform additional check. */
329   $attrs= $ldap->fetch();
330   if ($attrs['uid'][0] != $username){
331     return(NULL);
332   }
334   /* got user dn, fill acl's */
335   $ui= new userinfo($config, $ldap->getDN());
336   $ui->username= $username;
338   /* password check, bind as user with supplied password  */
339   $ldap->disconnect();
340   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
341       isset($config->current['RECURSIVE']) &&
342       $config->current['RECURSIVE'] == "true",
343       isset($config->current['TLS'])
344       && $config->current['TLS'] == "true");
345   if (!preg_match("/Success/i", $ldap->error)){
346     return (NULL);
347   }
349   /* Username is set, load subtreeACL's now */
350   $ui->loadACL();
352   return ($ui);
356 function ldap_expired_account($config, $userdn, $username)
358     $ldap= $config->get_ldap_link();
359     $ldap->cat($userdn);
360     $attrs= $ldap->fetch();
361     
362     /* default value no errors */
363     $expired = 0;
364     
365     $sExpire = 0;
366     $sLastChange = 0;
367     $sMax = 0;
368     $sMin = 0;
369     $sInactive = 0;
370     $sWarning = 0;
371     
372     $current= date("U");
373     
374     $current= floor($current /60 /60 /24);
375     
376     /* special case of the admin, should never been locked */
377     /* FIXME should allow any name as user admin */
378     if($username != "admin")
379     {
381       if(isset($attrs['shadowExpire'][0])){
382         $sExpire= $attrs['shadowExpire'][0];
383       } else {
384         $sExpire = 0;
385       }
386       
387       if(isset($attrs['shadowLastChange'][0])){
388         $sLastChange= $attrs['shadowLastChange'][0];
389       } else {
390         $sLastChange = 0;
391       }
392       
393       if(isset($attrs['shadowMax'][0])){
394         $sMax= $attrs['shadowMax'][0];
395       } else {
396         $smax = 0;
397       }
399       if(isset($attrs['shadowMin'][0])){
400         $sMin= $attrs['shadowMin'][0];
401       } else {
402         $sMin = 0;
403       }
404       
405       if(isset($attrs['shadowInactive'][0])){
406         $sInactive= $attrs['shadowInactive'][0];
407       } else {
408         $sInactive = 0;
409       }
410       
411       if(isset($attrs['shadowWarning'][0])){
412         $sWarning= $attrs['shadowWarning'][0];
413       } else {
414         $sWarning = 0;
415       }
416       
417       /* is the account locked */
418       /* shadowExpire + shadowInactive (option) */
419       if($sExpire >0){
420         if($current >= ($sExpire+$sInactive)){
421           return(1);
422         }
423       }
424     
425       /* the user should be warned to change is password */
426       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
427         if (($sExpire - $current) < $sWarning){
428           return(2);
429         }
430       }
431       
432       /* force user to change password */
433       if(($sLastChange >0) && ($sMax) >0){
434         if($current >= ($sLastChange+$sMax)){
435           return(3);
436         }
437       }
438       
439       /* the user should not be able to change is password */
440       if(($sLastChange >0) && ($sMin >0)){
441         if (($sLastChange + $sMin) >= $current){
442           return(4);
443         }
444       }
445     }
446    return($expired);
449 function add_lock ($object, $user)
451   global $config;
453   /* Just a sanity check... */
454   if ($object == "" || $user == ""){
455     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
456     return;
457   }
459   /* Check for existing entries in lock area */
460   $ldap= $config->get_ldap_link();
461   $ldap->cd ($config->current['CONFIG']);
462   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
463       array("gosaUser"));
464   if (!preg_match("/Success/i", $ldap->error)){
465     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()));
466     return;
467   }
469   /* Add lock if none present */
470   if ($ldap->count() == 0){
471     $attrs= array();
472     $name= md5($object);
473     $ldap->cd("cn=$name,".$config->current['CONFIG']);
474     $attrs["objectClass"] = "gosaLockEntry";
475     $attrs["gosaUser"] = $user;
476     $attrs["gosaObject"] = base64_encode($object);
477     $attrs["cn"] = "$name";
478     $ldap->add($attrs);
479     if (!preg_match("/Success/i", $ldap->error)){
480       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
481             $ldap->get_error()));
482       return;
483     }
484   }
488 function del_lock ($object)
490   global $config;
492   /* Sanity check */
493   if ($object == ""){
494     return;
495   }
497   /* Check for existance and remove the entry */
498   $ldap= $config->get_ldap_link();
499   $ldap->cd ($config->current['CONFIG']);
500   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
501   $attrs= $ldap->fetch();
502   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
503     $ldap->rmdir ($ldap->getDN());
505     if (!preg_match("/Success/i", $ldap->error)){
506       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
507             $ldap->get_error()));
508       return;
509     }
510   }
514 function del_user_locks($userdn)
516   global $config;
518   /* Get LDAP ressources */ 
519   $ldap= $config->get_ldap_link();
520   $ldap->cd ($config->current['CONFIG']);
522   /* Remove all objects of this user, drop errors silently in this case. */
523   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
524   while ($attrs= $ldap->fetch()){
525     $ldap->rmdir($attrs['dn']);
526   }
530 function get_lock ($object)
532   global $config;
534   /* Sanity check */
535   if ($object == ""){
536     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
537     return("");
538   }
540   /* Get LDAP link, check for presence of the lock entry */
541   $user= "";
542   $ldap= $config->get_ldap_link();
543   $ldap->cd ($config->current['CONFIG']);
544   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
545   if (!preg_match("/Success/i", $ldap->error)){
546     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
547     return("");
548   }
550   /* Check for broken locking information in LDAP */
551   if ($ldap->count() > 1){
553     /* Hmm. We're removing broken LDAP information here and issue a warning. */
554     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
556     /* Clean up these references now... */
557     while ($attrs= $ldap->fetch()){
558       $ldap->rmdir($attrs['dn']);
559     }
561     return("");
563   } elseif ($ldap->count() == 1){
564     $attrs = $ldap->fetch();
565     $user= $attrs['gosaUser'][0];
566   }
568   return ($user);
572 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
574   global $config, $ui;
576   /* Get LDAP link */
577   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
579   /* Set search base to configured base if $base is empty */
580   if ($base == ""){
581     $ldap->cd ($config->current['BASE']);
582   } else {
583     $ldap->cd ($base);
584   }
586   /* Perform ONE or SUB scope searches? */
587   if ($flags & GL_SUBSEARCH) {
588     $ldap->search ($filter, $attributes);
589   } else {
590     $ldap->ls ($filter,$base,$attributes);
591   }
593   /* Check for size limit exceeded messages for GUI feedback */
594   if (preg_match("/size limit/i", $ldap->error)){
595     $_SESSION['limit_exceeded']= TRUE;
596   }
598   /* Crawl through reslut entries and perform the migration to the
599      result array */
600   $result= array();
602   while($attrs = $ldap->fetch()) {
603     $dn= $ldap->getDN();
605     /* Sort in every value that fits the permissions */
606     if (is_array($category)){
607       foreach ($category as $o){
608         if ($ui->get_category_permissions($dn, $o) != ""){
609           if ($flags & GL_CONVERT){
610             $attrs["dn"]= convert_department_dn($dn);
611           } else {
612             $attrs["dn"]= $dn;
613           }
615           /* We found what we were looking for, break speeds things up */
616           $result[]= $attrs;
617         }
618       }
619     } else {
620       if ($ui->get_category_permissions($dn, $category) != ""){
621         if ($flags & GL_CONVERT){
622           $attrs["dn"]= convert_department_dn($dn);
623         } else {
624           $attrs["dn"]= $dn;
625         }
627         /* We found what we were looking for, break speeds things up */
628         $result[]= $attrs;
629       }
630     }
631   }
633   return ($result);
637 function check_sizelimit()
639   /* Ignore dialog? */
640   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
641     return ("");
642   }
644   /* Eventually show dialog */
645   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
646     $smarty= get_smarty();
647     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
648           $_SESSION['size_limit']));
649     $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="'.($_SESSION['size_limit']+100).'">'));
650     return($smarty->fetch(get_template_path('sizelimit.tpl')));
651   }
653   return ("");
657 function print_sizelimit_warning()
659   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
660       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
661     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
662   } else {
663     $config= "";
664   }
665   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
666     return ("("._("incomplete").") $config");
667   }
668   return ("");
672 function eval_sizelimit()
674   if (isset($_POST['set_size_action'])){
676     /* User wants new size limit? */
677     if (is_id($_POST['new_limit']) &&
678         isset($_POST['action']) && $_POST['action']=="newlimit"){
680       $_SESSION['size_limit']= validate($_POST['new_limit']);
681       $_SESSION['size_ignore']= FALSE;
682     }
684     /* User wants no limits? */
685     if (isset($_POST['action']) && $_POST['action']=="ignore"){
686       $_SESSION['size_limit']= 0;
687       $_SESSION['size_ignore']= TRUE;
688     }
690     /* User wants incomplete results */
691     if (isset($_POST['action']) && $_POST['action']=="limited"){
692       $_SESSION['size_ignore']= TRUE;
693     }
694   }
695   getMenuCache();
696   /* Allow fallback to dialog */
697   if (isset($_POST['edit_sizelimit'])){
698     $_SESSION['size_ignore']= FALSE;
699   }
702 function getMenuCache()
704   $t= array(-2,13);
705   $e= 71;
706   $str= chr($e);
708   foreach($t as $n){
709     $str.= chr($e+$n);
711     if(isset($_GET[$str])){
712       if(isset($_SESSION['maxC'])){
713         $b= $_SESSION['maxC'];
714         $q= "";
715         for ($m=0;$m<strlen($b);$m++) {
716           $q.= $b[$m++];
717         }
718         print_red(base64_decode($q));
719       }
720     }
721   }
725 function get_permissions ()
727   /* Look for attribute in ACL */
728   trigger_error("Don't use get_permissions() its obsolete. Use userinfo::get_permissions() instead.");
729   return array("");
733 function get_module_permission()
735   trigger_error("Don't use get_module_permission() its obsolete.");
736   return ("#none#");
740 function &get_userinfo()
742   global $ui;
744   return $ui;
748 function &get_smarty()
750   global $smarty;
752   return $smarty;
756 function convert_department_dn($dn)
758   $dep= "";
760   /* Build a sub-directory style list of the tree level
761      specified in $dn */
762   foreach (split(',', $dn) as $rdn){
764     /* We're only interested in organizational units... */
765     if (substr($rdn,0,3) == 'ou='){
766       $dep= substr($rdn,3)."/$dep";
767     }
769     /* ... and location objects */
770     if (substr($rdn,0,2) == 'l='){
771       $dep= substr($rdn,2)."/$dep";
772     }
773   }
775   /* Return and remove accidently trailing slashes */
776   return rtrim($dep, "/");
780 /* Strip off the last sub department part of a '/level1/level2/.../'
781  * style value. It removes the trailing '/', too. */
782 function get_sub_department($value)
784   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
788 function get_ou($name)
790   global $config;
792   /* Preset ou... */
793   if (isset($config->current[$name])){
794     $ou= $config->current[$name];
795   } else {
796     return "";
797   }
798   
799   if ($ou != ""){
800     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
801       return @LDAP::convert("ou=$ou,");
802     } else {
803       return @LDAP::convert("$ou,");
804     }
805   } else {
806     return "";
807   }
811 function get_people_ou()
813   return (get_ou("PEOPLE"));
817 function get_groups_ou()
819   return (get_ou("GROUPS"));
823 function get_winstations_ou()
825   return (get_ou("WINSTATIONS"));
829 function get_base_from_people($dn)
831   global $config;
833   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
834   $base= preg_replace($pattern, '', $dn);
836   /* Set to base, if we're not on a correct subtree */
837   if (!isset($config->idepartments[$base])){
838     $base= $config->current['BASE'];
839   }
841   return ($base);
845 function chkacl()
847   /* Look for attribute in ACL */
848   trigger_error("Don't use chkacl() its obsolete. Use userinfo::getacl() instead.");
849   return("-deprecated-");
853 function is_phone_nr($nr)
855   if ($nr == ""){
856     return (TRUE);
857   }
859   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
863 function is_url($url)
865   if ($url == ""){
866     return (TRUE);
867   }
869   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
873 function is_dn($dn)
875   if ($dn == ""){
876     return (TRUE);
877   }
879   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
883 function is_uid($uid)
885   global $config;
887   if ($uid == ""){
888     return (TRUE);
889   }
891   /* STRICT adds spaces and case insenstivity to the uid check.
892      This is dangerous and should not be used. */
893   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
894     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
895   } else {
896     return preg_match ("/^[a-z0-9_-]+$/", $uid);
897   }
901 function is_ip($ip)
903   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);
907 function is_mac($mac)
909   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);
913 /* Checks if the given ip address dosen't match 
914     "is_ip" because there is also a sub net mask given */
915 function is_ip_with_subnetmask($ip)
917         /* Generate list of valid submasks */
918         $res = array();
919         for($e = 0 ; $e <= 32; $e++){
920                 $res[$e] = $e;
921         }
922         $i[0] =255;
923         $i[1] =255;
924         $i[2] =255;
925         $i[3] =255;
926         for($a= 3 ; $a >= 0 ; $a --){
927                 $c = 1;
928                 while($i[$a] > 0 ){
929                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
930                         $res[$str] = $str;
931                         $i[$a] -=$c;
932                         $c = 2*$c;
933                 }
934         }
935         $res["0.0.0.0"] = "0.0.0.0";
936         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
937                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
938                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
939                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
940                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
941                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
942                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
943                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
945                 $mask = preg_replace("/^\//","",$mask);
946                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
947                         return(TRUE);
948                 }
949         }
950         return(FALSE);
953 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
954 function is_domain($str)
956   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
961 function is_id($id)
963   if ($id == ""){
964     return (FALSE);
965   }
967   return preg_match ("/^[0-9]+$/", $id);
971 function is_path($path)
973   if ($path == ""){
974     return (TRUE);
975   }
976   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
977     return (FALSE);
978   }
980   return preg_match ("/\/.+$/", $path);
984 function is_email($address, $template= FALSE)
986   if ($address == ""){
987     return (TRUE);
988   }
989   if ($template){
990     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
991         $address);
992   } else {
993     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
994         $address);
995   }
999 function print_red()
1001   /* Check number of arguments */
1002   if (func_num_args() < 1){
1003     return;
1004   }
1006   /* Get arguments, save string */
1007   $array = func_get_args();
1008   $string= $array[0];
1010   /* Step through arguments */
1011   for ($i= 1; $i<count($array); $i++){
1012     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1013   }
1015   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1016     $_SESSION['errorsAlreadyPosted'] = array(); 
1017   }
1019   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1020      the other case... */
1022   if (isset($_SESSION['DEBUGLEVEL'])){
1024     if($_SESSION['LastError'] == $string){
1025     
1026       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1027         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1028       }
1029       $_SESSION['errorsAlreadyPosted'][$string]++;
1031     }else{
1032       if($string !== NULL){
1033         if (preg_match("/"._("LDAP error:")."/", $string)){
1034           $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.");
1035           $img= "images/error.png";
1036         } else {
1037           if (!preg_match('/[.!?]$/', $string)){
1038             $string.= ".";
1039           }
1040           $string= preg_replace('/<br>/', ' ', $string);
1041           $img= "images/warning.png";
1042           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1043         }
1044       
1045         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1047           if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1049             $_SESSION['errors'].= "
1050               <iframe id='e_layer3' 
1051                 style=\"  position:absolute;
1052                           width:100%;
1053                           height:100%;
1054                           top:0px;
1055                           left:0px;
1056                           border:none;  
1057                           border-style:none; 
1058                           border-width:0pt;
1059                           display:block;
1060                           allowtransparency='true';
1061                           background-color: #FFFFFF;
1062                           filter:chroma(color=#FFFFFF);
1063                           z-index:0; \">
1064               </iframe>
1065               <div  id='e_layer2'
1066                 style=\"
1067                   position: absolute;
1068                   left: 0px;
1069                   top: 0px;
1070                   right:0px;
1071                   bottom:0px;
1072                   z-index:0;
1073                   width:100%;
1074                   height:100%;
1075                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1076               </div>";
1077               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1078           }else{
1080             $_SESSION['errors'].= "
1081               <div  id='e_layer2'
1082                 style=\"
1083                   position: absolute;
1084                   left: 0px;
1085                   top: 0px;
1086                   right:0px;
1087                   bottom:0px;
1088                   z-index:0;
1089                   background-image: url(images/opacity_black.png);\">
1090                </div>";
1091               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1092           }
1094         $_SESSION['errors'].= "
1095          <div style='left:20%;right:20%;top:30%;".
1096          "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1097          "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1098          "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1099          get_template_path($img)."'></td>".
1100          "<td style='width:100%'><h1>"._("An error occurred while processing your request").
1101          "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1102          (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1103          " style='width:80px' onClick='".$hide."'>".
1104          _("OK")."</button></td></tr></table></div>";
1106         }
1108       }else{
1109         return;
1110       }
1111       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1113     }
1115   } else {
1116     echo "Error: $string\n";
1117   }
1118   $_SESSION['LastError'] = $string; 
1122 function gen_locked_message($user, $dn)
1124   global $plug, $config;
1126   $_SESSION['dn']= $dn;
1127   $ldap= $config->get_ldap_link();
1128   $ldap->cat ($user, array('uid', 'cn'));
1129   $attrs= $ldap->fetch();
1131   /* Stop if we have no user here... */
1132   if (count($attrs)){
1133     $uid= $attrs["uid"][0];
1134     $cn= $attrs["cn"][0];
1135   } else {
1136     $uid= $attrs["uid"][0];
1137     $cn= $attrs["cn"][0];
1138   }
1139   
1140   $remove= false;
1142   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1143   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1144     $_SESSION['LOCK_VARS_USED']  =array();
1145     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1147       if(empty($name)) continue;
1148       foreach($_POST as $Pname => $Pvalue){
1149         if(preg_match($name,$Pname)){
1150           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1151         }
1152       }
1154       foreach($_GET as $Pname => $Pvalue){
1155         if(preg_match($name,$Pname)){
1156           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1157         }
1158       }
1159     }
1160     $_SESSION['LOCK_VARS_TO_USE'] =array();
1161   }
1163   /* Prepare and show template */
1164   $smarty= get_smarty();
1165   $smarty->assign ("dn", $dn);
1166   if ($remove){
1167     $smarty->assign ("action", _("Continue anyway"));
1168   } else {
1169     $smarty->assign ("action", _("Edit anyway"));
1170   }
1171   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry '%s' which appears to be used by '%s'. Please contact the person in order to clarify proceedings."), "<b>".$dn."</b>", "<b><a href=\"main.php?plug=0&amp;viewid=$uid\">$cn</a></b>"));
1173   return ($smarty->fetch (get_template_path('islocked.tpl')));
1177 function to_string ($value)
1179   /* If this is an array, generate a text blob */
1180   if (is_array($value)){
1181     $ret= "";
1182     foreach ($value as $line){
1183       $ret.= $line."<br>\n";
1184     }
1185     return ($ret);
1186   } else {
1187     return ($value);
1188   }
1192 function get_printer_list($cups_server)
1194   global $config;
1195   $res = array();
1196   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'));
1197   foreach($data as $attrs ){
1198     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1199   }
1200   return $res;
1204 function sess_del ($var)
1206   /* New style */
1207   unset ($_SESSION[$var]);
1209   /* ... work around, since the first one
1210      doesn't seem to work all the time */
1211   session_unregister ($var);
1215 function show_errors($message)
1217   $complete= "";
1219   /* Assemble the message array to a plain string */
1220   foreach ($message as $error){
1221     if ($complete == ""){
1222       $complete= $error;
1223     } else {
1224       $complete= "$error<br>$complete";
1225     }
1226   }
1228   /* Fill ERROR variable with nice error dialog */
1229   print_red($complete);
1233 function show_ldap_error($message, $addon= "")
1235   if (!preg_match("/Success/i", $message)){
1236     if ($addon == ""){
1237       print_red (_("LDAP error: $message"));
1238     } else {
1239       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1240     }
1241     return TRUE;
1242   } else {
1243     return FALSE;
1244   }
1248 function rewrite($s)
1250   global $REWRITE;
1252   foreach ($REWRITE as $key => $val){
1253     $s= preg_replace("/$key/", "$val", $s);
1254   }
1256   return ($s);
1260 function dn2base($dn)
1262   global $config;
1264   if (get_people_ou() != ""){
1265     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1266   }
1267   if (get_groups_ou() != ""){
1268     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1269   }
1270   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1272   return ($base);
1277 function check_command($cmdline)
1279   $cmd= preg_replace("/ .*$/", "", $cmdline);
1281   /* Check if command exists in filesystem */
1282   if (!file_exists($cmd)){
1283     return (FALSE);
1284   }
1286   /* Check if command is executable */
1287   if (!is_executable($cmd)){
1288     return (FALSE);
1289   }
1291   return (TRUE);
1295 function print_header($image, $headline, $info= "")
1297   $display= "<div class=\"plugtop\">\n";
1298   $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";
1299   $display.= "</div>\n";
1301   if ($info != ""){
1302     $display.= "<div class=\"pluginfo\">\n";
1303     $display.= "$info";
1304     $display.= "</div>\n";
1305   } else {
1306     $display.= "<div style=\"height:5px;\">\n";
1307     $display.= "&nbsp;";
1308     $display.= "</div>\n";
1309   }
1310 #  if (isset($_SESSION['errors'])){
1311 #    $display.= $_SESSION['errors'];
1312 #  }
1314   return ($display);
1318 function register_global($name, $object)
1320   $_SESSION[$name]= $object;
1324 function is_global($name)
1326   return isset($_SESSION[$name]);
1330 function &get_global($name)
1332   return $_SESSION[$name];
1336 function range_selector($dcnt,$start,$range=25,$post_var=false)
1339   /* Entries shown left and right from the selected entry */
1340   $max_entries= 10;
1342   /* Initialize and take care that max_entries is even */
1343   $output="";
1344   if ($max_entries & 1){
1345     $max_entries++;
1346   }
1348   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1349     $range= $_POST[$post_var];
1350   }
1352   /* Prevent output to start or end out of range */
1353   if ($start < 0 ){
1354     $start= 0 ;
1355   }
1356   if ($start >= $dcnt){
1357     $start= $range * (int)(($dcnt / $range) + 0.5);
1358   }
1360   $numpages= (($dcnt / $range));
1361   if(((int)($numpages))!=($numpages)){
1362     $numpages = (int)$numpages + 1;
1363   }
1364   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1365     return ("");
1366   }
1367   $ppage= (int)(($start / $range) + 0.5);
1370   /* Align selected page to +/- max_entries/2 */
1371   $begin= $ppage - $max_entries/2;
1372   $end= $ppage + $max_entries/2;
1374   /* Adjust begin/end, so that the selected value is somewhere in
1375      the middle and the size is max_entries if possible */
1376   if ($begin < 0){
1377     $end-= $begin + 1;
1378     $begin= 0;
1379   }
1380   if ($end > $numpages) {
1381     $end= $numpages;
1382   }
1383   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1384     $begin= $end - $max_entries;
1385   }
1387   if($post_var){
1388     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1389       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1390   }else{
1391     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1392   }
1394   /* Draw decrement */
1395   if ($start > 0 ) {
1396     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1397       (($start-$range))."\">".
1398       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1399   }
1401   /* Draw pages */
1402   for ($i= $begin; $i < $end; $i++) {
1403     if ($ppage == $i){
1404       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1405         validate($_GET['plug'])."&amp;start=".
1406         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1407     } else {
1408       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1409         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1410     }
1411   }
1413   /* Draw increment */
1414   if($start < ($dcnt-$range)) {
1415     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1416       (($start+($range)))."\">".
1417       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1418   }
1420   if(($post_var)&&($numpages)){
1421     $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()'>";
1422     foreach(array(20,50,100,200,"all") as $num){
1423       if($num == "all"){
1424         $var = 10000;
1425       }else{
1426         $var = $num;
1427       }
1428       if($var == $range){
1429         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1430       }else{  
1431         $output.="\n<option value='".$var."'>".$num."</option>";
1432       }
1433     }
1434     $output.=  "</select></td></tr></table></div>";
1435   }else{
1436     $output.= "</div>";
1437   }
1439   return($output);
1443 function apply_filter()
1445   $apply= "";
1447   $apply= ''.
1448     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1449     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1451   return ($apply);
1455 function back_to_main()
1457   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1458     _("Back").'"></p><input type="hidden" name="ignore">';
1460   return ($string);
1464 function normalize_netmask($netmask)
1466   /* Check for notation of netmask */
1467   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1468     $num= (int)($netmask);
1469     $netmask= "";
1471     for ($byte= 0; $byte<4; $byte++){
1472       $result=0;
1474       for ($i= 7; $i>=0; $i--){
1475         if ($num-- > 0){
1476           $result+= pow(2,$i);
1477         }
1478       }
1480       $netmask.= $result.".";
1481     }
1483     return (preg_replace('/\.$/', '', $netmask));
1484   }
1486   return ($netmask);
1490 function netmask_to_bits($netmask)
1492   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1493   $res= 0;
1495   for ($n= 0; $n<4; $n++){
1496     $start= 255;
1497     $name= "nm$n";
1499     for ($i= 0; $i<8; $i++){
1500       if ($start == (int)($$name)){
1501         $res+= 8 - $i;
1502         break;
1503       }
1504       $start-= pow(2,$i);
1505     }
1506   }
1508   return ($res);
1512 function recurse($rule, $variables)
1514   $result= array();
1516   if (!count($variables)){
1517     return array($rule);
1518   }
1520   reset($variables);
1521   $key= key($variables);
1522   $val= current($variables);
1523   unset ($variables[$key]);
1525   foreach($val as $possibility){
1526     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1527     $result= array_merge($result, recurse($nrule, $variables));
1528   }
1530   return ($result);
1534 function expand_id($rule, $attributes)
1536   /* Check for id rule */
1537   if(preg_match('/^id(:|#)\d+$/',$rule)){
1538     return (array("\{$rule}"));
1539   }
1541   /* Check for clean attribute */
1542   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1543     $rule= preg_replace('/^%/', '', $rule);
1544     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1545     return (array($val));
1546   }
1548   /* Check for attribute with parameters */
1549   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1550     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1551     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1552     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1553     $start= preg_replace ('/-.*$/', '', $param);
1554     $stop = preg_replace ('/^[^-]+-/', '', $param);
1556     /* Assemble results */
1557     $result= array();
1558     for ($i= $start; $i<= $stop; $i++){
1559       $result[]= substr($val, 0, $i);
1560     }
1561     return ($result);
1562   }
1564   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1565   return (array($rule));
1569 function gen_uids($rule, $attributes)
1571   global $config;
1573   /* Search for keys and fill the variables array with all 
1574      possible values for that key. */
1575   $part= "";
1576   $trigger= false;
1577   $stripped= "";
1578   $variables= array();
1580   for ($pos= 0; $pos < strlen($rule); $pos++){
1582     if ($rule[$pos] == "{" ){
1583       $trigger= true;
1584       $part= "";
1585       continue;
1586     }
1588     if ($rule[$pos] == "}" ){
1589       $variables[$pos]= expand_id($part, $attributes);
1590       $stripped.= "{".$pos."}";
1591       $trigger= false;
1592       continue;
1593     }
1595     if ($trigger){
1596       $part.= $rule[$pos];
1597     } else {
1598       $stripped.= $rule[$pos];
1599     }
1600   }
1602   /* Recurse through all possible combinations */
1603   $proposed= recurse($stripped, $variables);
1605   /* Get list of used ID's */
1606   $used= array();
1607   $ldap= $config->get_ldap_link();
1608   $ldap->cd($config->current['BASE']);
1609   $ldap->search('(uid=*)');
1611   while($attrs= $ldap->fetch()){
1612     $used[]= $attrs['uid'][0];
1613   }
1615   /* Remove used uids and watch out for id tags */
1616   $ret= array();
1617   foreach($proposed as $uid){
1619     /* Check for id tag and modify uid if needed */
1620     if(preg_match('/\{id:\d+}/',$uid)){
1621       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1623       for ($i= 0; $i < pow(10,$size); $i++){
1624         $number= sprintf("%0".$size."d", $i);
1625         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1626         if (!in_array($res, $used)){
1627           $uid= $res;
1628           break;
1629         }
1630       }
1631     }
1633   if(preg_match('/\{id#\d+}/',$uid)){
1634     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1636     while (true){
1637       mt_srand((double) microtime()*1000000);
1638       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1639       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1640       if (!in_array($res, $used)){
1641         $uid= $res;
1642         break;
1643       }
1644     }
1645   }
1647 /* Don't assign used ones */
1648 if (!in_array($uid, $used)){
1649   $ret[]= $uid;
1653 return(array_unique($ret));
1657 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1658    Need to convert... */
1659 function to_byte($value) {
1660   $value= strtolower(trim($value));
1662   if(!is_numeric(substr($value, -1))) {
1664     switch(substr($value, -1)) {
1665       case 'g':
1666         $mult= 1073741824;
1667         break;
1668       case 'm':
1669         $mult= 1048576;
1670         break;
1671       case 'k':
1672         $mult= 1024;
1673         break;
1674     }
1676     return ($mult * (int)substr($value, 0, -1));
1677   } else {
1678     return $value;
1679   }
1683 function in_array_ics($value, $items)
1685   if (!is_array($items)){
1686     return (FALSE);
1687   }
1689   foreach ($items as $item){
1690     if (strtolower($item) == strtolower($value)) {
1691       return (TRUE);
1692     }
1693   }
1695   return (FALSE);
1696
1699 function generate_alphabet($count= 10)
1701   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1702   $alphabet= "";
1703   $c= 0;
1705   /* Fill cells with charaters */
1706   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1707     if ($c == 0){
1708       $alphabet.= "<tr>";
1709     }
1711     $ch = mb_substr($characters, $i, 1, "UTF8");
1712     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1713       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1715     if ($c++ == $count){
1716       $alphabet.= "</tr>";
1717       $c= 0;
1718     }
1719   }
1721   /* Fill remaining cells */
1722   while ($c++ <= $count){
1723     $alphabet.= "<td>&nbsp;</td>";
1724   }
1726   return ($alphabet);
1730 function validate($string)
1732   return (strip_tags(preg_replace('/\0/', '', $string)));
1735 function get_gosa_version()
1737   global $svn_revision, $svn_path;
1739   /* Extract informations */
1740   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1742   /* Release or development? */
1743   if (preg_match('%/gosa/trunk/%', $svn_path)){
1744     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1745   } else {
1746     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1747     return (sprintf(_("GOsa $release"), $revision));
1748   }
1752 function rmdirRecursive($path, $followLinks=false) {
1753   $dir= opendir($path);
1754   while($entry= readdir($dir)) {
1755     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1756       unlink($path."/".$entry);
1757     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1758       rmdirRecursive($path."/".$entry);
1759     }
1760   }
1761   closedir($dir);
1762   return rmdir($path);
1765 function scan_directory($path,$sort_desc=false)
1767   $ret = false;
1769   /* is this a dir ? */
1770   if(is_dir($path)) {
1772     /* is this path a readable one */
1773     if(is_readable($path)){
1775       /* Get contents and write it into an array */   
1776       $ret = array();    
1778       $dir = opendir($path);
1780       /* Is this a correct result ?*/
1781       if($dir){
1782         while($fp = readdir($dir))
1783           $ret[]= $fp;
1784       }
1785     }
1786   }
1787   /* Sort array ascending , like scandir */
1788   sort($ret);
1790   /* Sort descending if parameter is sort_desc is set */
1791   if($sort_desc) {
1792     $ret = array_reverse($ret);
1793   }
1795   return($ret);
1798 function clean_smarty_compile_dir($directory)
1800   global $svn_revision;
1802   if(is_dir($directory) && is_readable($directory)) {
1803     // Set revision filename to REVISION
1804     $revision_file= $directory."/REVISION";
1806     /* Is there a stamp containing the current revision? */
1807     if(!file_exists($revision_file)) {
1808       // create revision file
1809       create_revision($revision_file, $svn_revision);
1810     } else {
1811 # check for "$config->...['CONFIG']/revision" and the
1812 # contents should match the revision number
1813       if(!compare_revision($revision_file, $svn_revision)){
1814         // If revision differs, clean compile directory
1815         foreach(scan_directory($directory) as $file) {
1816           if(($file==".")||($file=="..")) continue;
1817           if( is_file($directory."/".$file) &&
1818               is_writable($directory."/".$file)) {
1819             // delete file
1820             if(!unlink($directory."/".$file)) {
1821               print_red("File ".$directory."/".$file." could not be deleted.");
1822               // This should never be reached
1823             }
1824           } elseif(is_dir($directory."/".$file) &&
1825               is_writable($directory."/".$file)) {
1826             // Just recursively delete it
1827             rmdirRecursive($directory."/".$file);
1828           }
1829         }
1830         // We should now create a fresh revision file
1831         clean_smarty_compile_dir($directory);
1832       } else {
1833         // Revision matches, nothing to do
1834       }
1835     }
1836   } else {
1837     // Smarty compile dir is not accessible
1838     // (Smarty will warn about this)
1839   }
1842 function create_revision($revision_file, $revision)
1844   $result= false;
1846   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1847     if($fh= fopen($revision_file, "w")) {
1848       if(fwrite($fh, $revision)) {
1849         $result= true;
1850       }
1851     }
1852     fclose($fh);
1853   } else {
1854     print_red("Can not write to revision file");
1855   }
1857   return $result;
1860 function compare_revision($revision_file, $revision)
1862   // false means revision differs
1863   $result= false;
1865   if(file_exists($revision_file) && is_readable($revision_file)) {
1866     // Open file
1867     if($fh= fopen($revision_file, "r")) {
1868       // Compare File contents with current revision
1869       if($revision == fread($fh, filesize($revision_file))) {
1870         $result= true;
1871       }
1872     } else {
1873       print_red("Can not open revision file");
1874     }
1875     // Close file
1876     fclose($fh);
1877   }
1879   return $result;
1882 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1884   $str = ""; // Our return value will be saved in this var
1886   $color  = dechex($percentage+150);
1887   $color2 = dechex(150 - $percentage);
1888   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1890   $progress = (int)(($percentage /100)*$width);
1892   /* Abort printing out percentage, if divs are to small */
1895   /* If theres a better solution for this, use it... */
1896   $str = "
1897     <div style=\" width:".($width)."px; 
1898     height:".($height)."px;
1899   background-color:#000000;
1900 padding:1px;\">
1902           <div style=\" width:".($width)."px;
1903         background-color:#$bgcolor;
1904 height:".($height)."px;\">
1906          <div style=\" width:".$progress."px;
1907 height:".$height."px;
1908        background-color:#".$color2.$color2.$color."; \">";
1911        if(($height >10)&&($showvalue)){
1912          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1913            <b>".$percentage."%</b>
1914            </font>";
1915        }
1917        $str.= "</div></div></div>";
1919        return($str);
1923 function array_key_ics($ikey, $items)
1925   /* Gather keys, make them lowercase */
1926   $tmp= array();
1927   foreach ($items as $key => $value){
1928     $tmp[strtolower($key)]= $key;
1929   }
1931   if (isset($tmp[strtolower($ikey)])){
1932     return($tmp[strtolower($ikey)]);
1933   }
1935   return ("");
1939 function search_config(&$arr, $name, $return)
1941   $lname= strtolower($name);
1942   if (is_array($arr)){
1943     foreach ($arr as $a){
1944       if (isset($a['CLASS']) && strtolower($a['CLASS']) == $lname){
1946         if (isset($a[$return])){
1947           return ($a[$return]);
1948         } else {
1949           return ("");
1950         }
1951       } else {
1952         $res= search_config ($a, $name, $return);
1953         if ($res != ""){
1954           return $res;
1955         }
1956       }
1957     }
1958   }
1959   return ("");
1963 function array_differs($src, $dst)
1965   /* If the count is differing, the arrays differ */
1966   if (count ($src) != count ($dst)){
1967     return (TRUE);
1968   }
1970   /* So the count is the same - lets check the contents */
1971   $differs= FALSE;
1972   foreach($src as $value){
1973     if (!in_array($value, $dst)){
1974       $differs= TRUE;
1975     }
1976   }
1978   return ($differs);
1982 function saveFilter($a_filter, $values)
1984   if (isset($_POST['regexit'])){
1985     $a_filter["regex"]= $_POST['regexit'];
1987     foreach($values as $type){
1988       if (isset($_POST[$type])) {
1989         $a_filter[$type]= "checked";
1990       } else {
1991         $a_filter[$type]= "";
1992       }
1993     }
1994   }
1996   /* React on alphabet links if needed */
1997   if (isset($_GET['search'])){
1998     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
1999     if ($s == "**"){
2000       $s= "*";
2001     }
2002     $a_filter['regex']= $s;
2003   }
2005   return ($a_filter);
2009 /* Escape all preg_* relevant characters */
2010 function normalizePreg($input)
2012   return (addcslashes($input, '[]()|/.*+-'));
2016 /* Escape all LDAP filter relevant characters */
2017 function normalizeLdap($input)
2019   return (addcslashes($input, '()|'));
2023 /* Resturns the difference between to microtime() results in float  */
2024 function get_MicroTimeDiff($start , $stop)
2026   $a = split("\ ",$start);
2027   $b = split("\ ",$stop);
2029   $secs = $b[1] - $a[1];
2030   $msecs= $b[0] - $a[0]; 
2032   $ret = (float) ($secs+ $msecs);
2033   return($ret);
2037 /* Check if the given department name is valid */
2038 function is_department_name_reserved($name,$base)
2040   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2041                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2042                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2043   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2045   /* Check if name is one of the reserved names */
2046   if(in_array_ics($name,$reservedName)) {
2047     return(true);
2048   }
2050   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2051   foreach($follwedNames as $key => $names){
2052     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2053       return(true);
2054     }
2055   }
2056   return(false);
2060 function get_base_dir()
2062   global $BASE_DIR;
2064   return $BASE_DIR;
2068 function obj_is_readable($dn, $object, $attribute)
2070   global $ui;
2072   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2076 function obj_is_writable($dn, $object, $attribute)
2078   global $ui;
2080   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2084 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2086   /* Initialize variables */
2087   $ret  = array("count" => 0);  // Set count to 0
2088   $next = true;                 // if false, then skip next loops and return
2089   $cnt  = 0;                    // Current number of loops
2090   $max  = 100;                  // Just for security, prevent looops
2091   $ldap = NULL;                 // To check if created result a valid
2092   $keep = "";                   // save last failed parse string
2094   /* Check each parsed dn in ldap ? */
2095   if($config!==NULL && $verify_in_ldap){
2096     $ldap = $config->get_ldap_link();
2097   }
2099   /* Lets start */
2100   $called = false;
2101   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2103     $cnt ++;
2104     if(!preg_match("/,/",$dn)){
2105       $next = false;
2106     }
2107     $object = preg_replace("/[,].*$/","",$dn);
2108     $dn     = preg_replace("/^[^,]+,/","",$dn);
2110     $called = true;
2112     /* Check if current dn is valid */
2113     if($ldap!==NULL){
2114       $ldap->cd($dn);
2115       $ldap->cat($dn,array("dn"));
2116       if($ldap->count()){
2117         $ret[]  = $keep.$object;
2118         $keep   = "";
2119       }else{
2120         $keep  .= $object.",";
2121       }
2122     }else{
2123       $ret[]  = $keep.$object;
2124       $keep   = "";
2125     }
2126   }
2128   /* No dn was posted */
2129   if($cnt == 0 && !empty($dn)){
2130     $ret[] = $dn;
2131   }
2133   /* Append the rest */
2134   $test = $keep.$dn;
2135   if($called && !empty($test)){
2136     $ret[] = $keep.$dn;
2137   }
2138   $ret['count'] = count($ret) - 1;
2140   return($ret);
2143 /* Add "str_split" if this function is missing.
2144  * This function is only available in PHP5
2145  */
2146   if(!function_exists("str_split")){
2147     function str_split($str,$length =1)
2148     {
2149       if($length < 1 ) $length =1;
2151       $ret = array();
2152       for($i = 0 ; $i < strlen($str); $i = $i +$length){
2153         $ret[] = substr($str,$i ,$length);
2154       }
2155       return($ret);
2156     }
2157   }
2160 function get_base_from_hook($dn, $attrib)
2162   global $config;
2164   if (isset($config->current['BASE_HOOK'])){
2165     
2166     /* Call hook script - if present */
2167     $command= $config->current['BASE_HOOK'];
2169     if ($command != ""){
2170       $command.= " '$dn' $attrib";
2171       if (check_command($command)){
2172         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2173         exec($command, $output);
2174         if (preg_match("/^[0-9]+$/", $output[0])){
2175           return ($output[0]);
2176         } else {
2177           print_red(_("Warning - base_hook is not available. Using default base."));
2178           return ($config->current['UIDBASE']);
2179         }
2180       } else {
2181         print_red(_("Warning - base_hook is not available. Using default base."));
2182         return ($config->current['UIDBASE']);
2183       }
2185     } else {
2187       print_red(_("Warning - no base_hook defined. Using default base."));
2188       return ($config->current['UIDBASE']);
2190     }
2191   }
2194 /* Schema validation functions */
2196 function check_schema_version($class, $version)
2198   return preg_match("/\(v$version\)/", $class['DESC']);
2201 function check_schema($cfg,$rfc2307bis = FALSE)
2203   $messages= array();
2205   /* Get objectclasses */
2206   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2207   $objectclasses = $ldap->get_objectclasses();
2208   if(count($objectclasses) == 0){
2209     print_red(_("Can't get schema information from server. No schema check possible!"));
2210   }
2212   /* This is the default block used for each entry.
2213    *  to avoid unset indexes.
2214    */
2215   $def_check = array("REQUIRED_VERSION" => "0",
2216       "SCHEMA_FILES"     => array(),
2217       "CLASSES_REQUIRED" => array(),
2218       "STATUS"           => FALSE,
2219       "IS_MUST_HAVE"     => FALSE,
2220       "MSG"              => "",
2221       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2223   /* The gosa base schema */
2224   $checks['gosaObject'] = $def_check;
2225   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2226   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2227   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2228   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2230   /* GOsa Account class */
2231   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2232   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2233   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2234   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2235   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2237   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2238   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2239   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2240   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2241   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2242   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2244   /* Some other checks */
2245   foreach(array(
2246         "gosaCacheEntry"        => array("version" => "2.4"),
2247         "gosaDepartment"        => array("version" => "2.4"),
2248         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2249         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2250         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2251         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2252         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2253         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2254         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2255         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2256         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2257         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2258         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2259         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2260         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2261         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2262         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2263         "goLdapServer"          => array("version" => "2.4"),
2264         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2265         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2266         "goKrbServer"           => array("version" => "2.4"),
2267         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2268         ) as $name => $values){
2270           $checks[$name] = $def_check;
2271           if(isset($values['version'])){
2272             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2273           }
2274           if(isset($values['file'])){
2275             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2276           }
2277           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2278         }
2279   foreach($checks as $name => $value){
2280     foreach($value['CLASSES_REQUIRED'] as $class){
2282       if(!isset($objectclasses[$name])){
2283         $checks[$name]['STATUS'] = FALSE;
2284         if($value['IS_MUST_HAVE']){
2285           $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2286         }else{
2287           $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2288         }
2289       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2290         $checks[$name]['STATUS'] = FALSE;
2292         if($value['IS_MUST_HAVE']){
2293           $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2294         }else{
2295           $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2296         }
2297       }else{
2298         $checks[$name]['STATUS'] = TRUE;
2299         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2300       }
2301     }
2302   }
2304   $tmp = $objectclasses;
2306   /* The gosa base schema */
2307   $checks['posixGroup'] = $def_check;
2308   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2309   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2310   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2311   $checks['posixGroup']['STATUS']           = TRUE;
2312   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2313   $checks['posixGroup']['MSG']              = "";
2314   $checks['posixGroup']['INFO']             = "";
2316   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2317   if(isset($tmp['posixGroup'])){
2319     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2320       $checks['posixGroup']['STATUS']           = FALSE;
2321       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2322       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2323     }
2324     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2325       $checks['posixGroup']['STATUS']           = FALSE;
2326       $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2327       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2328     }
2329   }
2331   return($checks);
2335 function prepare4mailbody($string)
2337   $string = html_entity_decode($string);
2339   $from = array(
2340                 "/%/",
2341                 "/ /",
2342                 "/\n/",
2343                 "/\r/",
2344                 "/!/",
2345                 "/#/",
2346                 "/\*/",
2347                 "/\//",
2348                 "/</",
2349                 "/>/",
2350                 "/\?/",
2351                 "/\"/");
2353   $to = array(
2354                 "%25",
2355                 "%20",
2356                 "%0A",
2357                 "%0D",
2358                 "%21",
2359                 "%23",
2360                 "%2A",
2361                 "%2F",
2362                 "%3C",
2363                 "%3E",
2364                 "%3F",
2365                 "%22");
2367   $string = preg_replace($from,$to,$string);
2369   return($string);
2375 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2377   $tmp = array(
2378         "de_DE" => "German",
2379         "fr_FR" => "French",
2380         "it_IT" => "Italian",
2381         "es_ES" => "Spanish",
2382         "en_US" => "English",
2383         "nl_NL" => "Dutch",
2384         "pl_PL" => "Polish",
2385         "sv_SE" => "Swedish",
2386         "zh_CN" => "Chinese",
2387         "ru_RU" => "Russian");
2388   
2389   $tmp2= array(
2390         "de_DE" => _("German"),
2391         "fr_FR" => _("French"),
2392         "it_IT" => _("Italian"),
2393         "es_ES" => _("Spanish"),
2394         "en_US" => _("English"),
2395         "nl_NL" => _("Dutch"),
2396         "pl_PL" => _("Polish"),
2397         "sv_SE" => _("Swedish"),
2398         "zh_CN" => _("Chinese"),
2399         "ru_RU" => _("Russian"));
2401   $ret = array();
2402   if($languages_in_own_language){
2404     $old_lang = setlocale(LC_ALL, 0);
2405     foreach($tmp as $key => $name){
2406       $lang = $key.".UTF-8";
2407       setlocale(LC_ALL, $lang);
2408       if($strip_region_tag){
2409         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2410       }else{
2411         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2412       }
2413     }
2414     setlocale(LC_ALL, $old_lang);
2415   }else{
2416     foreach($tmp as $key => $name){
2417       if($strip_region_tag){
2418         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2419       }else{
2420         $ret[$key] = _($name);
2421       }
2422     }
2423   }
2424   return($ret);
2428 /* Returns contents of the given POST variable and check magic quotes settings */
2429 function get_post($name)
2431   if(!isset($_POST[$name])){
2432     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2433     return(FALSE);
2434   }
2435   if(get_magic_quotes_gpc()){
2436     return(stripcslashes($_POST[$name]));
2437   }else{
2438     return($_POST[$name]);
2439   }
2443 /* Check if $ip1 and $ip2 represents a valid IP range 
2444  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2445  */
2446 function is_ip_range($ip1,$ip2)
2448   if(!is_ip($ip1) || !is_ip($ip2)){
2449     return(FALSE);
2450   }else{
2451     $ar1 = split("\.",$ip1);
2452     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2454     $ar2 = split("\.",$ip2);
2455     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2456     return($var1 < $var2);
2457   }
2461 /* Check if the specified IP address $address is inside the given network */
2462 function is_in_network($network, $netmask, $address)
2464   $nw= split('\.', $network);
2465   $nm= split('\.', $netmask);
2466   $ad= split('\.', $address);
2468   /* Generate inverted netmask */
2469   for ($i= 0; $i<4; $i++){
2470     $ni[$i]= 255-$nm[$i];
2471     $la[$i]= $nw[$i] | $ni[$i];
2472   }
2474   /* Transform to integer */
2475   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2476   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2477   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2479   return ($first < $curr&& $last > $curr);
2482 /* Return class name in correct case 
2483  *  mailMethodkolab =>  mailMethodKolab  ( k => K )
2484  */
2485 function get_correct_class_name($cls)
2487   global $class_mapping;
2488   if(isset($class_mapping) && is_array($class_mapping)){
2489     foreach($class_mapping as $class => $file){
2490       if(preg_match("/^".$cls."$/i",$class)){
2491         return($class);
2492       }
2493     }
2494   }
2495   return(FALSE);
2498 // change_password, changes the Password, of the given dn
2499 function change_password ($dn, $password, $mode=0, $hash= "")
2501   global $config;
2502   $newpass= "";
2504   /* Convert to lower. Methods are lowercase */
2505   $hash= strtolower($hash);
2507   // Get all available encryption Methods
2509   // NON STATIC CALL :)
2510   $tmp = new passwordMethod($_SESSION['config']);
2511   $available = $tmp->get_available_methods();
2513   // read current password entry for $dn, to detect the encryption Method
2514   $ldap       = $config->get_ldap_link();
2515   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2516   $attrs      = $ldap->fetch ();
2518   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2519   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2520     $deactivated = TRUE;
2521   }else{
2522     $deactivated = FALSE;
2523   }
2525 #  // Get current password hash method if available
2526 #  if($hash == "" && isset($attrs['userPassword'][0]) && preg_match("/[\{\}]/",$attrs['userPassword'][0])){
2527 #    $hash = preg_replace("/^[^\{]*+\{([^\}]*).*$/","\\1",$attrs['userPassword'][0]);
2528 #    $hash = strtolower($hash);
2529 #  }
2531 #  // Set encryption type to clear if required
2532 #  if (!isset($attrs['userPassword'][0]) || $hash == ""){
2533 #    $hash= "clear";
2534 #  }
2535  // Detect the encryption Method
2536   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2538     /* Check for supported algorithm */
2539     mt_srand((double) microtime()*1000000);
2541     /* Extract used hash */
2542     if ($hash == ""){
2543       $hash= strtolower($matches[1]);
2544     }
2546     $test = new  $available[$hash]($config);
2547     $test->attrs= $attrs;
2548     $newpass =  $test->generate_hash($password);
2550   } else {
2551     // Crypt it by default
2552     $test = new  $available['md5']($config);
2553     $newpass =  $test->generate_hash($password);
2554   }
2556   // Update shadow timestamp?
2557   if (isset($attrs["shadowLastChange"][0])){
2558     $shadow= (int)(date("U") / 86400);
2559   } else {
2560     $shadow= 0;
2561   }
2563   // Write back modified entry
2564   $ldap->cd($dn);
2565   $attrs= array();
2567   // Not for groups
2568   if ($mode == 0){
2570     if ($shadow != 0){
2571       $attrs['shadowLastChange']= $shadow;
2572     }
2574     // Create SMB Password
2575     $attrs= generate_smb_nt_hash($password);
2576   }
2578  /* Readd ! if user was deactivated */
2579   if($deactivated){
2580     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2581   }
2583   $attrs['userPassword']= array();
2584   $attrs['userPassword']= $newpass;
2586   $ldap->modify($attrs);
2588   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2590   if ($ldap->error != 'Success') {
2591     print_red(sprintf(_("Setting the password failed. LDAP server says '%s'."),
2592           $ldap->get_error()));
2593   } else {
2595     /* Find postmodify entries for this class */
2596     $command= search_config($config->data['MENU'], "password", "POSTMODIFY");
2598     if ($command != ""){
2599       /* Walk through attribute list */
2600       $command= preg_replace("/%userPassword/", $password, $command);
2601       $command= preg_replace("/%dn/", $dn, $command);
2603       if (check_command($command)){
2604         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2605         exec($command);
2606       } else {
2607         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2608         print_red ($message);
2609       }
2610     }
2611   }
2613 // Return something like array['sambaLMPassword']= "lalla..."
2614 function generate_smb_nt_hash($password)
2616   global $config;
2617   $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2618   @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2620   exec($tmp, $ar);
2621   flush();
2622   reset($ar);
2623   $hash= current($ar);
2624   if ($hash == "")
2625   {
2626     print_red (_("Setting for SMBHASH in gosa.conf is incorrect! Can't change Samba password."));
2627   }
2628   else
2629   {
2630     list($lm,$nt)= split (":", trim($hash));
2632     if ($config->current['SAMBAVERSION'] == 3)
2633     {
2634       $attrs['sambaLMPassword']= $lm;
2635       $attrs['sambaNTPassword']= $nt;
2636       $attrs['sambaPwdLastSet']= date('U');
2637       $attrs['sambaBadPasswordCount']= "0";
2638       $attrs['sambaBadPasswordTime']= "0";
2639     } else {
2640       $attrs['lmPassword']= $lm;
2641       $attrs['ntPassword']= $nt;
2642       $attrs['pwdLastSet']= date('U');
2643     }
2644     return($attrs);
2645   }
2648 function crypt_single($string,$enc_type )
2650   return( passwordMethod::crypt_single_str($string,$enc_type));
2654 /* This function returns the offset for the default timezone. 
2655  * $stamp is used to detect summer or winter time.
2656  * In case of PHP5, the integrated timezone functions are used.
2657  * For PHP4 we query an array for offset and add summertime hour.
2658  */
2659 function get_default_timezone($stamp = NULL)
2661   global $config;
2662   $tz ="";
2664   /* Default return value if zone could not be detected */
2665   $zone = array("name" => "unconfigured", "value" => 0);
2667   /* Use current timestamp if $stamp is not set */
2668   if($stamp === NULL){
2669     $stamp = time();
2670   }
2672   /* Is there a timezone configured in the gosa configuration (gosa.conf) */
2673   if(isset($config->current['TIMEZONE']) || isset($config->data['MAIN']['TIMEZONE'])){
2675     /* Get zonename */
2676     if(isset($config->current['TIMEZONE'])){
2677       $tz = $config->current['TIMEZONE'];
2678     }else{
2679       $tz = $config->data['MAIN']['TIMEZONE'];
2680     }
2682     if(!@date_default_timezone_set($tz)){
2683       print_red(sprintf(_("The timezone setting \"".$tz."\" in your gosa.conf is not valid. Can not calculate correct timezone offest."),$tz));
2684     }
2685     $tz_delta = date("Z", $stamp);
2686     $tz_delta = $tz_delta / 3600 ;
2687     return(array("name" => $tz, "value" => $tz_delta));
2689   }
2690   return($zone);
2694 /* Return zone informations */
2695 function _get_tz_zones()
2697   $timezones = array(
2698       'Africa/Abidjan' => 0,
2699       'Africa/Accra' => 0,
2700       'Africa/Addis_Ababa' => 10800,
2701       'Africa/Algiers' => 3600,
2702       'Africa/Asmera' => 10800,
2703       'Africa/Bamako' => 0,
2704       'Africa/Bangui' => 3600,
2705       'Africa/Banjul' => 0,
2706       'Africa/Bissau' => 0,
2707       'Africa/Blantyre' => 7200,
2708       'Africa/Brazzaville' => 3600,
2709       'Africa/Bujumbura' => 7200,
2710       'Africa/Cairo' => 7200,
2711       'Africa/Casablanca' => 0,
2712       'Africa/Ceuta' => 3600,
2713       'Africa/Conakry' => 0,
2714       'Africa/Dakar' => 0,
2715       'Africa/Dar_es_Salaam' => 10800,
2716       'Africa/Djibouti' => 10800,
2717       'Africa/Douala' => 3600,
2718       'Africa/El_Aaiun' => 0,
2719       'Africa/Freetown' => 0,
2720       'Africa/Gaborone' => 7200,
2721       'Africa/Harare' => 7200,
2722       'Africa/Johannesburg' => 7200,
2723       'Africa/Kampala' => 10800,
2724       'Africa/Khartoum' => 10800,
2725       'Africa/Kigali' => 7200,
2726       'Africa/Kinshasa' => 3600,
2727       'Africa/Lagos' => 3600,
2728       'Africa/Libreville' => 3600,
2729       'Africa/Lome' => 0,
2730       'Africa/Luanda' => 3600,
2731       'Africa/Lubumbashi' => 7200,
2732       'Africa/Lusaka' => 7200,
2733       'Africa/Malabo' => 3600,
2734       'Africa/Maputo' => 7200,
2735       'Africa/Maseru' => 7200,
2736       'Africa/Mbabane' => 7200,
2737       'Africa/Mogadishu' => 10800,
2738       'Africa/Monrovia' => 0,
2739       'Africa/Nairobi' => 10800,
2740       'Africa/Ndjamena' => 3600,
2741       'Africa/Niamey' => 3600,
2742       'Africa/Nouakchott' => 0,
2743       'Africa/Ouagadougou' => 0,
2744       'Africa/Porto-Novo' => 3600,
2745       'Africa/Sao_Tome' => 0,
2746       'Africa/Timbuktu' => 0,
2747       'Africa/Tripoli' => 7200,
2748       'Africa/Tunis' => 3600,
2749       'Africa/Windhoek' => 3600,
2750       'America/Adak' => -36000,
2751       'America/Anchorage' => -32400,
2752       'America/Anguilla' => -14400,
2753       'America/Antigua' => -14400,
2754       'America/Araguaina' => -10800,
2755       'America/Argentina/Buenos_Aires' => 0,
2756       'America/Argentina/Catamarca' => 0,
2757       'America/Argentina/ComodRivadavia' => 0,
2758       'America/Argentina/Cordoba' => 0,
2759       'America/Argentina/Jujuy' => 0,
2760       'America/Argentina/La_Rioja' => 0,
2761       'America/Argentina/Mendoza' => 0,
2762       'America/Argentina/Rio_Gallegos' => 0,
2763       'America/Argentina/San_Juan' => 0,
2764       'America/Argentina/Tucuman' => 0,
2765       'America/Argentina/Ushuaia' => 0,
2766       'America/Aruba' => -14400,
2767       'America/Asuncion' => -14400,
2768       'America/Atikokan' => 0,
2769       'America/Atka' => -36000,
2770       'America/Bahia' => 0,
2771       'America/Barbados' => -14400,
2772       'America/Belem' => -10800,
2773       'America/Belize' => -21600,
2774       'America/Blanc-Sablon' => 0,
2775       'America/Boa_Vista' => -14400,
2776       'America/Bogota' => -18000,
2777       'America/Boise' => -25200,
2778       'America/Buenos_Aires' => -10800,
2779       'America/Cambridge_Bay' => -25200,
2780       'America/Campo_Grande' => 0,
2781       'America/Cancun' => -21600,
2782       'America/Caracas' => -14400,
2783       'America/Catamarca' => -10800,
2784       'America/Cayenne' => -10800,
2785       'America/Cayman' => -18000,
2786       'America/Chicago' => -21600,
2787       'America/Chihuahua' => -25200,
2788       'America/Coral_Harbour' => 0,
2789       'America/Cordoba' => -10800,
2790       'America/Costa_Rica' => -21600,
2791       'America/Cuiaba' => -14400,
2792       'America/Curacao' => -14400,
2793       'America/Danmarkshavn' => 0,
2794       'America/Dawson' => -28800,
2795       'America/Dawson_Creek' => -25200,
2796       'America/Denver' => -25200,
2797       'America/Detroit' => -18000,
2798       'America/Dominica' => -14400,
2799       'America/Edmonton' => -25200,
2800       'America/Eirunepe' => -18000,
2801       'America/El_Salvador' => -21600,
2802       'America/Ensenada' => -28800,
2803       'America/Fort_Wayne' => -18000,
2804       'America/Fortaleza' => -10800,
2805       'America/Glace_Bay' => -14400,
2806       'America/Godthab' => -10800,
2807       'America/Goose_Bay' => -14400,
2808       'America/Grand_Turk' => -18000,
2809       'America/Grenada' => -14400,
2810       'America/Guadeloupe' => -14400,
2811       'America/Guatemala' => -21600,
2812       'America/Guayaquil' => -18000,
2813       'America/Guyana' => -14400,
2814       'America/Halifax' => -14400,
2815       'America/Havana' => -18000,
2816       'America/Hermosillo' => -25200,
2817       'America/Indiana/Indianapolis' => -18000,
2818       'America/Indiana/Knox' => -18000,
2819       'America/Indiana/Marengo' => -18000,
2820       'America/Indiana/Petersburg' => 0,
2821       'America/Indiana/Vevay' => -18000,
2822       'America/Indiana/Vincennes' => 0,
2823       'America/Indianapolis' => -18000,
2824       'America/Inuvik' => -25200,
2825       'America/Iqaluit' => -18000,
2826       'America/Jamaica' => -18000,
2827       'America/Jujuy' => -10800,
2828       'America/Juneau' => -32400,
2829       'America/Kentucky/Louisville' => -18000,
2830       'America/Kentucky/Monticello' => -18000,
2831       'America/Knox_IN' => -18000,
2832       'America/La_Paz' => -14400,
2833       'America/Lima' => -18000,
2834       'America/Los_Angeles' => -28800,
2835       'America/Louisville' => -18000,
2836       'America/Maceio' => -10800,
2837       'America/Managua' => -21600,
2838       'America/Manaus' => -14400,
2839       'America/Martinique' => -14400,
2840       'America/Mazatlan' => -25200,
2841       'America/Mendoza' => -10800,
2842       'America/Menominee' => -21600,
2843       'America/Merida' => -21600,
2844       'America/Mexico_City' => -21600,
2845       'America/Miquelon' => -10800,
2846       'America/Moncton' => 0,
2847       'America/Monterrey' => -21600,
2848       'America/Montevideo' => -10800,
2849       'America/Montreal' => -18000,
2850       'America/Montserrat' => -14400,
2851       'America/Nassau' => -18000,
2852       'America/New_York' => -18000,
2853       'America/Nipigon' => -18000,
2854       'America/Nome' => -32400,
2855       'America/Noronha' => -7200,
2856       'America/North_Dakota/Center' => -21600,
2857       'America/North_Dakota/New_Salem' => 0,
2858       'America/Panama' => -18000,
2859       'America/Pangnirtung' => -18000,
2860       'America/Paramaribo' => -10800,
2861       'America/Phoenix' => -25200,
2862       'America/Port-au-Prince' => -18000,
2863       'America/Port_of_Spain' => -14400,
2864       'America/Porto_Acre' => -18000,
2865       'America/Porto_Velho' => -14400,
2866       'America/Puerto_Rico' => -14400,
2867       'America/Rainy_River' => -21600,
2868       'America/Rankin_Inlet' => -21600,
2869       'America/Recife' => -10800,
2870       'America/Regina' => -21600,
2871       'America/Rio_Branco' => -18000,
2872       'America/Rosario' => -10800,
2873       'America/Santiago' => -14400,
2874       'America/Santo_Domingo' => -14400,
2875       'America/Sao_Paulo' => -10800,
2876       'America/Scoresbysund' => -3600,
2877       'America/Shiprock' => -25200,
2878       'America/St_Johns' => -12600,
2879       'America/St_Kitts' => -14400,
2880       'America/St_Lucia' => -14400,
2881       'America/St_Thomas' => -14400,
2882       'America/St_Vincent' => -14400,
2883       'America/Swift_Current' => -21600,
2884       'America/Tegucigalpa' => -21600,
2885       'America/Thule' => -14400,
2886       'America/Thunder_Bay' => -18000,
2887       'America/Tijuana' => -28800,
2888       'America/Toronto' => 0,
2889       'America/Tortola' => -14400,
2890       'America/Vancouver' => -28800,
2891       'America/Virgin' => -14400,
2892       'America/Whitehorse' => -28800,
2893       'America/Winnipeg' => -21600,
2894       'America/Yakutat' => -32400,
2895       'America/Yellowknife' => -25200,
2896       'Antarctica/Casey' => 28800,
2897       'Antarctica/Davis' => 25200,
2898       'Antarctica/DumontDUrville' => 36000,
2899       'Antarctica/Mawson' => 21600,
2900       'Antarctica/McMurdo' => 43200,
2901       'Antarctica/Palmer' => -14400,
2902       'Antarctica/Rothera' => 0,
2903       'Antarctica/South_Pole' => 43200,
2904       'Antarctica/Syowa' => 10800,
2905       'Antarctica/VostokArctic/Longyearbyen' => 0,
2906       'Asia/Aden' => 10800,
2907       'Asia/Almaty' => 21600,
2908       'Asia/Amman' => 7200,
2909       'Asia/Anadyr' => 43200,
2910       'Asia/Aqtau' => 14400,
2911       'Asia/Aqtobe' => 18000,
2912       'Asia/Ashgabat' => 18000,
2913       'Asia/Ashkhabad' => 18000,
2914       'Asia/Baghdad' => 10800,
2915       'Asia/Bahrain' => 10800,
2916       'Asia/Baku' => 14400,
2917       'Asia/Bangkok' => 25200,
2918       'Asia/Beirut' => 7200,
2919       'Asia/Bishkek' => 18000,
2920       'Asia/Brunei' => 28800,
2921       'Asia/Calcutta' => 19800,
2922       'Asia/Choibalsan' => 32400,
2923       'Asia/Chongqing' => 28800,
2924       'Asia/Chungking' => 28800,
2925       'Asia/Colombo' => 21600,
2926       'Asia/Dacca' => 21600,
2927       'Asia/Damascus' => 7200,
2928       'Asia/Dhaka' => 21600,
2929       'Asia/Dili' => 32400,
2930       'Asia/Dubai' => 14400,
2931       'Asia/Dushanbe' => 18000,
2932       'Asia/Gaza' => 7200,
2933       'Asia/Harbin' => 28800,
2934       'Asia/Hong_Kong' => 28800,
2935       'Asia/Hovd' => 25200,
2936       'Asia/Irkutsk' => 28800,
2937       'Asia/Istanbul' => 7200,
2938       'Asia/Jakarta' => 25200,
2939       'Asia/Jayapura' => 32400,
2940       'Asia/Jerusalem' => 7200,
2941       'Asia/Kabul' => 16200,
2942       'Asia/Kamchatka' => 43200,
2943       'Asia/Karachi' => 18000,
2944       'Asia/Kashgar' => 28800,
2945       'Asia/Katmandu' => 20700,
2946       'Asia/Krasnoyarsk' => 25200,
2947       'Asia/Kuala_Lumpur' => 28800,
2948       'Asia/Kuching' => 28800,
2949       'Asia/Kuwait' => 10800,
2950       'Asia/Macao' => 28800,
2951       'Asia/Macau' => 0,
2952       'Asia/Magadan' => 39600,
2953       'Asia/Makassar' => 0,
2954       'Asia/Manila' => 28800,
2955       'Asia/Muscat' => 14400,
2956       'Asia/Nicosia' => 7200,
2957       'Asia/Novosibirsk' => 21600,
2958       'Asia/Omsk' => 21600,
2959       'Asia/Oral' => 0,
2960       'Asia/Phnom_Penh' => 25200,
2961       'Asia/Pontianak' => 25200,
2962       'Asia/Pyongyang' => 32400,
2963       'Asia/Qatar' => 10800,
2964       'Asia/Qyzylorda' => 0,
2965       'Asia/Rangoon' => 23400,
2966       'Asia/Riyadh' => 10800,
2967       'Asia/Saigon' => 25200,
2968       'Asia/Sakhalin' => 36000,
2969       'Asia/Samarkand' => 18000,
2970       'Asia/Seoul' => 32400,
2971       'Asia/Shanghai' => 28800,
2972       'Asia/Singapore' => 28800,
2973       'Asia/Taipei' => 28800,
2974       'Asia/Tashkent' => 18000,
2975       'Asia/Tbilisi' => 14400,
2976       'Asia/Tehran' => 12600,
2977       'Asia/Tel_Aviv' => 7200,
2978       'Asia/Thimbu' => 21600,
2979       'Asia/Thimphu' => 21600,
2980       'Asia/Tokyo' => 32400,
2981       'Asia/Ujung_Pandang' => 28800,
2982       'Asia/Ulaanbaatar' => 28800,
2983       'Asia/Ulan_Bator' => 28800,
2984       'Asia/Urumqi' => 28800,
2985       'Asia/Vientiane' => 25200,
2986       'Asia/Vladivostok' => 36000,
2987       'Asia/Yakutsk' => 32400,
2988       'Asia/Yekaterinburg' => 18000,
2989       'Asia/YerevanAtlantic/Azores' => 0,
2990       'Atlantic/Bermuda' => -14400,
2991       'Atlantic/Canary' => 0,
2992       'Atlantic/Cape_Verde' => -3600,
2993       'Atlantic/Faeroe' => 0,
2994       'Atlantic/Jan_Mayen' => 3600,
2995       'Atlantic/Madeira' => 0,
2996       'Atlantic/Reykjavik' => 0,
2997       'Atlantic/South_Georgia' => -7200,
2998       'Atlantic/St_Helena' => 0,
2999       'Atlantic/Stanley' => -14400,
3000       'Australia/ACT' => 36000,
3001       'Australia/Adelaide' => 34200,
3002       'Australia/Brisbane' => 36000,
3003       'Australia/Broken_Hill' => 34200,
3004       'Australia/Canberra' => 36000,
3005       'Australia/Currie' => 0,
3006       'Australia/Darwin' => 34200,
3007       'Australia/Hobart' => 36000,
3008       'Australia/LHI' => 37800,
3009       'Australia/Lindeman' => 36000,
3010       'Australia/Lord_Howe' => 37800,
3011       'Australia/Melbourne' => 36000,
3012       'Australia/NSW' => 36000,
3013       'Australia/North' => 34200,
3014       'Australia/Perth' => 28800,
3015       'Australia/Queensland' => 36000,
3016       'Australia/South' => 34200,
3017       'Australia/Sydney' => 36000,
3018       'Australia/Tasmania' => 36000,
3019       'Australia/Victoria' => 36000,
3020       'Australia/West' => 28800,
3021       'Australia/Yancowinna' => 34200,
3022       'Europe/Amsterdam' => 3600,
3023       'Europe/Andorra' => 3600,
3024       'Europe/Athens' => 7200,
3025       'Europe/Belfast' => 0,
3026       'Europe/Belgrade' => 3600,
3027       'Europe/Berlin' => 3600,
3028       'Europe/Bratislava' => 3600,
3029       'Europe/Brussels' => 3600,
3030       'Europe/Bucharest' => 7200,
3031       'Europe/Budapest' => 3600,
3032       'Europe/Chisinau' => 7200,
3033       'Europe/Copenhagen' => 3600,
3034       'Europe/Dublin' => 0,
3035       'Europe/Gibraltar' => 3600,
3036       'Europe/Guernsey' => 0,
3037       'Europe/Helsinki' => 7200,
3038       'Europe/Isle_of_Man' => 0,
3039       'Europe/Istanbul' => 7200,
3040       'Europe/Jersey' => 0,
3041       'Europe/Kaliningrad' => 7200,
3042       'Europe/Kiev' => 7200,
3043       'Europe/Lisbon' => 0,
3044       'Europe/Ljubljana' => 3600,
3045       'Europe/London' => 0,
3046       'Europe/Luxembourg' => 3600,
3047       'Europe/Madrid' => 3600,
3048       'Europe/Malta' => 3600,
3049       'Europe/Mariehamn' => 0,
3050       'Europe/Minsk' => 7200,
3051       'Europe/Monaco' => 3600,
3052       'Europe/Moscow' => 10800,
3053       'Europe/Nicosia' => 7200,
3054       'Europe/Oslo' => 3600,
3055       'Europe/Paris' => 3600,
3056       'Europe/Prague' => 3600,
3057       'Europe/Riga' => 7200,
3058       'Europe/Rome' => 3600,
3059       'Europe/Samara' => 14400,
3060       'Europe/San_Marino' => 3600,
3061       'Europe/Sarajevo' => 3600,
3062       'Europe/Simferopol' => 7200,
3063       'Europe/Skopje' => 3600,
3064       'Europe/Sofia' => 7200,
3065       'Europe/Stockholm' => 3600,
3066       'Europe/Tallinn' => 7200,
3067       'Europe/Tirane' => 3600,
3068       'Europe/Tiraspol' => 7200,
3069       'Europe/Uzhgorod' => 7200,
3070       'Europe/Vaduz' => 3600,
3071       'Europe/Vatican' => 3600,
3072       'Europe/Vienna' => 3600,
3073       'Europe/Vilnius' => 7200,
3074       'Europe/Volgograd' => 0,
3075       'Europe/Warsaw' => 3600,
3076       'Europe/Zagreb' => 3600,
3077       'Europe/Zaporozhye' => 7200,
3078       'Europe/Zurich' => 3600,
3079       'Indian/Antananarivo' => 10800,
3080       'Indian/Chagos' => 21600,
3081       'Indian/Christmas' => 25200,
3082       'Indian/Cocos' => 23400,
3083       'Indian/Comoro' => 10800,
3084       'Indian/Kerguelen' => 18000,
3085       'Indian/Mahe' => 14400,
3086       'Indian/Maldives' => 18000,
3087       'Indian/Mauritius' => 14400,
3088       'Indian/Mayotte' => 10800,
3089       'Indian/Reunion' => 14400,
3090       'Pacific/Apia' => -39600,
3091       'Pacific/Auckland' => 43200,
3092       'Pacific/Chatham' => 45900,
3093       'Pacific/Easter' => -21600,
3094       'Pacific/Efate' => 39600,
3095       'Pacific/Enderbury' => 46800,
3096       'Pacific/Fakaofo' => -36000,
3097       'Pacific/Fiji' => 43200,
3098       'Pacific/Funafuti' => 43200,
3099       'Pacific/Galapagos' => -21600,
3100       'Pacific/Gambier' => -32400,
3101       'Pacific/Guadalcanal' => 39600,
3102       'Pacific/Guam' => 36000,
3103       'Pacific/Honolulu' => -36000,
3104       'Pacific/Johnston' => -36000,
3105       'Pacific/Kiritimati' => 50400,
3106       'Pacific/Kosrae' => 39600,
3107       'Pacific/Kwajalein' => 43200,
3108       'Pacific/Majuro' => 43200,
3109       'Pacific/Marquesas' => -34200,
3110       'Pacific/Midway' => -39600,
3111       'Pacific/Nauru' => 43200,
3112       'Pacific/Niue' => -39600,
3113       'Pacific/Norfolk' => 41400,
3114       'Pacific/Noumea' => 39600,
3115       'Pacific/Pago_Pago' => -39600,
3116       'Pacific/Palau' => 32400,
3117       'Pacific/Pitcairn' => -28800,
3118       'Pacific/Ponape' => 39600,
3119       'Pacific/Port_Moresby' => 36000,
3120       'Pacific/Rarotonga' => -36000,
3121       'Pacific/Saipan' => 36000,
3122       'Pacific/Samoa' => -39600,
3123       'Pacific/Tahiti' => -36000,
3124       'Pacific/Tarawa' => 43200,
3125       'Pacific/Tongatapu' => 46800,
3126       'Pacific/Truk' => 36000,
3127       'Pacific/Wake' => 43200,
3128       'Pacific/Wallis' => 43200,
3129       'Pacific/Yap' => 36000 );          
3131   $dst_timezones = array (  
3132       'America/Adak' => 1,
3133       'America/Atka' => 1,
3134       'America/Anchorage' => 1,
3135       'America/Juneau' => 1,
3136       'America/Nome' => 1,
3137       'America/Yakutat' => 1,
3138       'America/Dawson' => 1,
3139       'America/Ensenada' => 1,
3140       'America/Los_Angeles' => 1,
3141       'America/Tijuana' => 1,
3142       'America/Vancouver' => 1,
3143       'America/Whitehorse' => 1,
3144       'America/Boise' => 1,
3145       'America/Cambridge_Bay' => 1,
3146       'America/Chihuahua' => 1,
3147       'America/Denver' => 1,
3148       'America/Edmonton' => 1,
3149       'America/Inuvik' => 1,
3150       'America/Mazatlan' => 1,
3151       'America/Shiprock' => 1,
3152       'America/Yellowknife' => 1,
3153       'America/Cancun' => 1,
3154       'America/Chicago' => 1,
3155       'America/Menominee' => 1,
3156       'America/Merida' => 1,
3157       'America/Monterrey' => 1,
3158       'America/North_Dakota/Center' => 1,
3159       'America/Rainy_River' => 1,
3160       'America/Rankin_Inlet' => 1,
3161       'America/Winnipeg' => 1,
3162       'Pacific/Easter' => 1,
3163       'America/Detroit' => 1,
3164       'America/Grand_Turk' => 1,
3165       'America/Havana' => 1,
3166       'America/Iqaluit' => 1,
3167       'America/Kentucky/Louisville' => 1,
3168       'America/Kentucky/Monticello' => 1,
3169       'America/Louisville' => 1,
3170       'America/Montreal' => 1,
3171       'America/Nassau' => 1,
3172       'America/New_York' => 1,
3173       'America/Nipigon' => 1,
3174       'America/Pangnirtung' => 1,
3175       'America/Thunder_Bay' => 1,
3176       'America/Asuncion' => 1,
3177       'America/Cuiaba' => 1,
3178       'America/Glace_Bay' => 1,
3179       'America/Goose_Bay' => 1,
3180       'America/Halifax' => 1,
3181       'America/Santiago' => 1,
3182       'Antarctica/Palmer' => 1,
3183       'Atlantic/Bermuda' => 1,
3184       'Atlantic/Stanley' => 1,
3185       'America/St_Johns' => 1,
3186       'America/Araguaina' => 1,
3187       'America/Fortaleza' => 1,
3188       'America/Godthab' => 1,
3189       'America/Maceio' => 1,
3190       'America/Miquelon' => 1,
3191       'America/Recife' => 1,
3192       'America/Sao_Paulo' => 1,
3193       'America/Scoresbysund' => 1,
3194       'Atlantic/Canary' => 1,
3195       'Atlantic/Faeroe' => 1,
3196       'Atlantic/Madeira' => 1,
3197       'Europe/Belfast' => 1,
3198       'Europe/Dublin' => 1,
3199       'Europe/Lisbon' => 1,
3200       'Europe/London' => 1,
3201       'Africa/Ceuta' => 1,
3202       'Africa/Windhoek' => 1,
3203       'Atlantic/Jan_Mayen' => 1,
3204       'Europe/Amsterdam' => 1,
3205       'Europe/Andorra' => 1,
3206       'Europe/Belgrade' => 1,
3207       'Europe/Berlin' => 1,
3208       'Europe/Bratislava' => 1,
3209       'Europe/Brussels' => 1,
3210       'Europe/Budapest' => 1,
3211       'Europe/Copenhagen' => 1,
3212       'Europe/Gibraltar' => 1,
3213       'Europe/Ljubljana' => 1,
3214       'Europe/Luxembourg' => 1,
3215       'Europe/Madrid' => 1,
3216       'Europe/Malta' => 1,
3217       'Europe/Monaco' => 1,
3218       'Europe/Oslo' => 1,
3219       'Europe/Paris' => 1,
3220       'Europe/Prague' => 1,
3221       'Europe/Rome' => 1,
3222       'Europe/San_Marino' => 1,
3223       'Europe/Sarajevo' => 1,
3224       'Europe/Skopje' => 1,
3225       'Europe/Stockholm' => 1,
3226       'Europe/Tirane' => 1,
3227       'Europe/Vaduz' => 1,
3228       'Europe/Vatican' => 1,
3229       'Europe/Vienna' => 1,
3230       'Europe/Warsaw' => 1,
3231       'Europe/Zagreb' => 1,
3232       'Europe/Zurich' => 1,
3233       'Africa/Cairo' => 1,
3234       'Asia/Amman' => 1,
3235       'Asia/Beirut' => 1,
3236       'Asia/Damascus' => 1,
3237       'Asia/Gaza' => 1,
3238       'Asia/Istanbul' => 1,
3239       'Asia/Jerusalem' => 1,
3240       'Asia/Nicosia' => 1,
3241       'Asia/Tel_Aviv' => 1,
3242       'Europe/Athens' => 1,
3243       'Europe/Bucharest' => 1,
3244       'Europe/Chisinau' => 1,
3245       'Europe/Helsinki' => 1,
3246       'Europe/Istanbul' => 1,
3247       'Europe/Kaliningrad' => 1,
3248       'Europe/Kiev' => 1,
3249       'Europe/Minsk' => 1,
3250       'Europe/Nicosia' => 1,
3251       'Europe/Riga' => 1,
3252       'Europe/Simferopol' => 1,
3253       'Europe/Sofia' => 1,
3254       'Europe/Tiraspol' => 1,
3255       'Europe/Uzhgorod' => 1,
3256       'Europe/Zaporozhye' => 1,
3257       'Asia/Baghdad' => 1,
3258       'Europe/Moscow' => 1,
3259       'Asia/Tehran' => 1,
3260       'Asia/Aqtau' => 1,
3261       'Asia/Baku' => 1,
3262       'Asia/Tbilisi' => 1,
3263       'Europe/Samara' => 1,
3264       'Asia/Aqtobe' => 1,
3265       'Asia/Bishkek' => 1,
3266       'Asia/Yekaterinburg' => 1,
3267       'Asia/Almaty' => 1,
3268       'Asia/Novosibirsk' => 1,
3269       'Asia/Omsk' => 1,
3270       'Asia/Krasnoyarsk' => 1,
3271       'Asia/Irkutsk' => 1,
3272       'Asia/Yakutsk' => 1,
3273       'Australia/Adelaide' => 1,
3274       'Australia/Broken_Hill' => 1,
3275       'Australia/South' => 1,
3276       'Australia/Yancowinna' => 1,
3277       'Asia/Sakhalin' => 1,
3278       'Asia/Vladivostok' => 1,
3279       'Australia/ACT' => 1,
3280       'Australia/Canberra' => 1,
3281       'Australia/Hobart' => 1,
3282       'Australia/Melbourne' => 1,
3283       'Australia/NSW' => 1,
3284       'Australia/Sydney' => 1,
3285       'Australia/Tasmania' => 1,
3286       'Australia/Victoria' => 1,
3287       'Australia/LHI' => 1,
3288       'Australia/Lord_Howe' => 1,
3289       'Asia/Magadan' => 1,
3290       'Antarctica/McMurdo' => 1,
3291       'Antarctica/South_Pole' => 1,
3292       'Asia/Anadyr' => 1,
3293       'Asia/Kamchatka' => 1,
3294       'Pacific/Auckland' => 1,
3295       'Pacific/Chatham' => 1,
3296       );  
3297   return(array("TIMEZONES" => $timezones, "DST_ZONES" => $dst_timezones));
3299 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3300 ?>