Code

Udpated some error messages that cause execution to abort.
[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('OBJECT_IDENTIFIER ',0x06);
38 define('SEQUENCE',0x10);
39 define('SEQUENCE_OF',0x10);
40 define('SET',0x11);
41 define('SET_OF',0x11);
42 define('DEBUG',false);
43 define('HDB_KU_MKEY',0x484442);
44 define('TWO_BIT_SHIFTS',0x7efc);
45 define('DES_CBC_CRC',1);
46 define('DES_CBC_MD4',2);
47 define('DES_CBC_MD5',3);
48 define('DES3_CBC_MD5',5);
49 define('DES3_CBC_SHA1',16);
51 /* Define globals for revision comparing */
52 $svn_path = '$HeadURL$';
53 $svn_revision = '$Revision$';
55 /* Include required files */
56 require_once("class_location.inc");
57 require_once ("functions_debug.inc");
58 require_once ("functions_dns.inc");
59 require_once ("accept-to-gettext.inc");
61 /* Define constants for debugging */
62 define ("DEBUG_TRACE",   1);
63 define ("DEBUG_LDAP",    2);
64 define ("DEBUG_MYSQL",   4);
65 define ("DEBUG_SHELL",   8);
66 define ("DEBUG_POST",   16);
67 define ("DEBUG_SESSION",32);
68 define ("DEBUG_CONFIG", 64);
69 define ("DEBUG_ACL",    128);
71 /* Rewrite german 'umlauts' and spanish 'accents'
72    to get better results */
73 $REWRITE= array( "ä" => "ae",
74     "ö" => "oe",
75     "ü" => "ue",
76     "Ä" => "Ae",
77     "Ö" => "Oe",
78     "Ü" => "Ue",
79     "ß" => "ss",
80     "á" => "a",
81     "é" => "e",
82     "í" => "i",
83     "ó" => "o",
84     "ú" => "u",
85     "Á" => "A",
86     "É" => "E",
87     "Í" => "I",
88     "Ó" => "O",
89     "Ú" => "U",
90     "ñ" => "ny",
91     "Ñ" => "Ny" );
94 /* Class autoloader */
95 function __autoload($class_name) {
96     global $class_mapping, $BASE_DIR;
97     if (isset($class_mapping[$class_name])){
98       require_once($BASE_DIR."/".$class_mapping[$class_name]);
99     } else {
100       echo _("Fatal: cannot load class \"$class_name\" - execution aborted");
101     }
104 /* Create seed with microseconds */
105 function make_seed() {
106   list($usec, $sec) = explode(' ', microtime());
107   return (float) $sec + ((float) $usec * 100000);
111 /* Debug level action */
112 function DEBUG($level, $line, $function, $file, $data, $info="")
114   if ($_SESSION['DEBUGLEVEL'] & $level){
115     $output= "DEBUG[$level] ";
116     if ($function != ""){
117       $output.= "($file:$function():$line) - $info: ";
118     } else {
119       $output.= "($file:$line) - $info: ";
120     }
121     echo $output;
122     if (is_array($data)){
123       print_a($data);
124     } else {
125       echo "'$data'";
126     }
127     echo "<br>";
128   }
132 function get_browser_language()
134   /* Try to use users primary language */
135   global $config;
136   $ui= get_userinfo();
137   if (isset($ui) && $ui !== NULL){
138     if ($ui->language != ""){
139       return ($ui->language.".UTF-8");
140     }
141   }
143   /* Check for global language settings in gosa.conf */
144   if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
145     $lang = $config->data['MAIN']['LANG'];
146     if(!preg_match("/utf/i",$lang)){
147       $lang .= ".UTF-8";
148     }
149     return($lang);
150   }
151  
152   /* Load supported languages */
153   $gosa_languages= get_languages();
155   /* Move supported languages to flat list */
156   $langs= array();
157   foreach($gosa_languages as $lang => $dummy){
158     $langs[]= $lang.'.UTF-8';
159   }
161   /* Return gettext based string */
162   return (al2gt($langs, 'text/html'));
166 /* Rewrite ui object to another dn */
167 function change_ui_dn($dn, $newdn)
169   $ui= $_SESSION['ui'];
170   if ($ui->dn == $dn){
171     $ui->dn= $newdn;
172     $_SESSION['ui']= $ui;
173   }
177 /* Return theme path for specified file */
178 function get_template_path($filename= '', $plugin= FALSE, $path= "")
180   global $config, $BASE_DIR;
182   if (!@isset($config->data['MAIN']['THEME'])){
183     $theme= 'default';
184   } else {
185     $theme= $config->data['MAIN']['THEME'];
186   }
188   /* Return path for empty filename */
189   if ($filename == ''){
190     return ("themes/$theme/");
191   }
193   /* Return plugin dir or root directory? */
194   if ($plugin){
195     if ($path == ""){
196       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
197     } else {
198       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
199     }
200     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
201       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
202     }
203     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
204       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
205     }
206     if ($path == ""){
207       return ($_SESSION['plugin_dir']."/$filename");
208     } else {
209       return ($path."/$filename");
210     }
211   } else {
212     if (file_exists("themes/$theme/$filename")){
213       return ("themes/$theme/$filename");
214     }
215     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
216       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
217     }
218     if (file_exists("themes/default/$filename")){
219       return ("themes/default/$filename");
220     }
221     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
222       return ("$BASE_DIR/ihtml/themes/default/$filename");
223     }
224     return ($filename);
225   }
229 function array_remove_entries($needles, $haystack)
231   $tmp= array();
233   /* Loop through entries to be removed */
234   foreach ($haystack as $entry){
235     if (!in_array($entry, $needles)){
236       $tmp[]= $entry;
237     }
238   }
240   return ($tmp);
244 function gosa_array_merge($ar1,$ar2)
246   if(!is_array($ar1) || !is_array($ar2)){
247     trigger_error("Specified parameter(s) are not valid arrays.");
248   }else{
249     return(array_values(array_unique(array_merge($ar1,$ar2))));
250   }
255 function gosa_log ($message)
257   global $ui;
259   /* Preset to something reasonable */
260   $username= " unauthenticated";
262   /* Replace username if object is present */
263   if (isset($ui)){
264     if ($ui->username != ""){
265       $username= "[$ui->username]";
266     } else {
267       $username= "unknown";
268     }
269   }
271   syslog(LOG_INFO,"GOsa$username: $message");
275 function ldap_init ($server, $base, $binddn='', $pass='')
277   global $config;
279   $ldap = new LDAP ($binddn, $pass, $server,
280       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
281       isset($config->current['TLS']) && $config->current['TLS'] == "true");
283   /* Sadly we've no proper return values here. Use the error message instead. */
284   if (!preg_match("/Success/i", $ldap->error)){
285     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
286     exit();
287   }
289   /* Preset connection base to $base and return to caller */
290   $ldap->cd ($base);
291   return $ldap;
295 function ldap_login_user ($username, $password)
297   global $config;
299   /* look through the entire ldap */
300   $ldap = $config->get_ldap_link();
301   if (!preg_match("/Success/i", $ldap->error)){
302     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
303     $smarty= get_smarty();
304     $smarty->display(get_template_path('headers.tpl'));
305     echo "<body>".$_SESSION['errors']."</body></html>";
306     exit();
307   }
308   $ldap->cd($config->current['BASE']);
309   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
311   /* get results, only a count of 1 is valid */
312   switch ($ldap->count()){
314     /* user not found */
315     case 0:     return (NULL);
317             /* valid uniq user */
318     case 1: 
319             break;
321             /* found more than one matching id */
322     default:
323             print_red(_("Username / UID is not unique. Please check your LDAP database."));
324             return (NULL);
325   }
327   /* LDAP schema is not case sensitive. Perform additional check. */
328   $attrs= $ldap->fetch();
329   if ($attrs['uid'][0] != $username){
330     return(NULL);
331   }
333   /* got user dn, fill acl's */
334   $ui= new userinfo($config, $ldap->getDN());
335   $ui->username= $username;
337   /* password check, bind as user with supplied password  */
338   $ldap->disconnect();
339   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
340       isset($config->current['RECURSIVE']) &&
341       $config->current['RECURSIVE'] == "true",
342       isset($config->current['TLS'])
343       && $config->current['TLS'] == "true");
344   if (!preg_match("/Success/i", $ldap->error)){
345     return (NULL);
346   }
348   /* Username is set, load subtreeACL's now */
349   $ui->loadACL();
351   return ($ui);
355 function ldap_expired_account($config, $userdn, $username)
357     $ldap= $config->get_ldap_link();
358     $ldap->cat($userdn);
359     $attrs= $ldap->fetch();
360     
361     /* default value no errors */
362     $expired = 0;
363     
364     $sExpire = 0;
365     $sLastChange = 0;
366     $sMax = 0;
367     $sMin = 0;
368     $sInactive = 0;
369     $sWarning = 0;
370     
371     $current= date("U");
372     
373     $current= floor($current /60 /60 /24);
374     
375     /* special case of the admin, should never been locked */
376     /* FIXME should allow any name as user admin */
377     if($username != "admin")
378     {
380       if(isset($attrs['shadowExpire'][0])){
381         $sExpire= $attrs['shadowExpire'][0];
382       } else {
383         $sExpire = 0;
384       }
385       
386       if(isset($attrs['shadowLastChange'][0])){
387         $sLastChange= $attrs['shadowLastChange'][0];
388       } else {
389         $sLastChange = 0;
390       }
391       
392       if(isset($attrs['shadowMax'][0])){
393         $sMax= $attrs['shadowMax'][0];
394       } else {
395         $smax = 0;
396       }
398       if(isset($attrs['shadowMin'][0])){
399         $sMin= $attrs['shadowMin'][0];
400       } else {
401         $sMin = 0;
402       }
403       
404       if(isset($attrs['shadowInactive'][0])){
405         $sInactive= $attrs['shadowInactive'][0];
406       } else {
407         $sInactive = 0;
408       }
409       
410       if(isset($attrs['shadowWarning'][0])){
411         $sWarning= $attrs['shadowWarning'][0];
412       } else {
413         $sWarning = 0;
414       }
415       
416       /* is the account locked */
417       /* shadowExpire + shadowInactive (option) */
418       if($sExpire >0){
419         if($current >= ($sExpire+$sInactive)){
420           return(1);
421         }
422       }
423     
424       /* the user should be warned to change is password */
425       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
426         if (($sExpire - $current) < $sWarning){
427           return(2);
428         }
429       }
430       
431       /* force user to change password */
432       if(($sLastChange >0) && ($sMax) >0){
433         if($current >= ($sLastChange+$sMax)){
434           return(3);
435         }
436       }
437       
438       /* the user should not be able to change is password */
439       if(($sLastChange >0) && ($sMin >0)){
440         if (($sLastChange + $sMin) >= $current){
441           return(4);
442         }
443       }
444     }
445    return($expired);
448 function add_lock ($object, $user)
450   global $config;
452   /* Just a sanity check... */
453   if ($object == "" || $user == ""){
454     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
455     return;
456   }
458   /* Check for existing entries in lock area */
459   $ldap= $config->get_ldap_link();
460   $ldap->cd ($config->current['CONFIG']);
461   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
462       array("gosaUser"));
463   if (!preg_match("/Success/i", $ldap->error)){
464     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()));
465     return;
466   }
468   /* Add lock if none present */
469   if ($ldap->count() == 0){
470     $attrs= array();
471     $name= md5($object);
472     $ldap->cd("cn=$name,".$config->current['CONFIG']);
473     $attrs["objectClass"] = "gosaLockEntry";
474     $attrs["gosaUser"] = $user;
475     $attrs["gosaObject"] = base64_encode($object);
476     $attrs["cn"] = "$name";
477     $ldap->add($attrs);
478     if (!preg_match("/Success/i", $ldap->error)){
479       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
480             $ldap->get_error()));
481       return;
482     }
483   }
487 function del_lock ($object)
489   global $config;
491   /* Sanity check */
492   if ($object == ""){
493     return;
494   }
496   /* Check for existance and remove the entry */
497   $ldap= $config->get_ldap_link();
498   $ldap->cd ($config->current['CONFIG']);
499   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
500   $attrs= $ldap->fetch();
501   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
502     $ldap->rmdir ($ldap->getDN());
504     if (!preg_match("/Success/i", $ldap->error)){
505       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
506             $ldap->get_error()));
507       return;
508     }
509   }
513 function del_user_locks($userdn)
515   global $config;
517   /* Get LDAP ressources */ 
518   $ldap= $config->get_ldap_link();
519   $ldap->cd ($config->current['CONFIG']);
521   /* Remove all objects of this user, drop errors silently in this case. */
522   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
523   while ($attrs= $ldap->fetch()){
524     $ldap->rmdir($attrs['dn']);
525   }
529 function get_lock ($object)
531   global $config;
533   /* Sanity check */
534   if ($object == ""){
535     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
536     return("");
537   }
539   /* Get LDAP link, check for presence of the lock entry */
540   $user= "";
541   $ldap= $config->get_ldap_link();
542   $ldap->cd ($config->current['CONFIG']);
543   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
544   if (!preg_match("/Success/i", $ldap->error)){
545     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
546     return("");
547   }
549   /* Check for broken locking information in LDAP */
550   if ($ldap->count() > 1){
552     /* Hmm. We're removing broken LDAP information here and issue a warning. */
553     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
555     /* Clean up these references now... */
556     while ($attrs= $ldap->fetch()){
557       $ldap->rmdir($attrs['dn']);
558     }
560     return("");
562   } elseif ($ldap->count() == 1){
563     $attrs = $ldap->fetch();
564     $user= $attrs['gosaUser'][0];
565   }
567   return ($user);
571 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
573   global $config, $ui;
575   /* Get LDAP link */
576   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
578   /* Set search base to configured base if $base is empty */
579   if ($base == ""){
580     $ldap->cd ($config->current['BASE']);
581   } else {
582     $ldap->cd ($base);
583   }
585   /* Perform ONE or SUB scope searches? */
586   if ($flags & GL_SUBSEARCH) {
587     $ldap->search ($filter, $attributes);
588   } else {
589     $ldap->ls ($filter,$base,$attributes);
590   }
592   /* Check for size limit exceeded messages for GUI feedback */
593   if (preg_match("/size limit/i", $ldap->error)){
594     $_SESSION['limit_exceeded']= TRUE;
595   }
597   /* Crawl through reslut entries and perform the migration to the
598      result array */
599   $result= array();
601   while($attrs = $ldap->fetch()) {
602     $dn= $ldap->getDN();
604     /* Sort in every value that fits the permissions */
605     if (is_array($category)){
606       foreach ($category as $o){
607         if ($ui->get_category_permissions($dn, $o) != ""){
608           if ($flags & GL_CONVERT){
609             $attrs["dn"]= convert_department_dn($dn);
610           } else {
611             $attrs["dn"]= $dn;
612           }
614           /* We found what we were looking for, break speeds things up */
615           $result[]= $attrs;
616         }
617       }
618     } else {
619       if ($ui->get_category_permissions($dn, $category) != ""){
620         if ($flags & GL_CONVERT){
621           $attrs["dn"]= convert_department_dn($dn);
622         } else {
623           $attrs["dn"]= $dn;
624         }
626         /* We found what we were looking for, break speeds things up */
627         $result[]= $attrs;
628       }
629     }
630   }
632   return ($result);
636 function check_sizelimit()
638   /* Ignore dialog? */
639   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
640     return ("");
641   }
643   /* Eventually show dialog */
644   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
645     $smarty= get_smarty();
646     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
647           $_SESSION['size_limit']));
648     $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).'">'));
649     return($smarty->fetch(get_template_path('sizelimit.tpl')));
650   }
652   return ("");
656 function print_sizelimit_warning()
658   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
659       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
660     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
661   } else {
662     $config= "";
663   }
664   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
665     return ("("._("incomplete").") $config");
666   }
667   return ("");
671 function eval_sizelimit()
673   if (isset($_POST['set_size_action'])){
675     /* User wants new size limit? */
676     if (is_id($_POST['new_limit']) &&
677         isset($_POST['action']) && $_POST['action']=="newlimit"){
679       $_SESSION['size_limit']= validate($_POST['new_limit']);
680       $_SESSION['size_ignore']= FALSE;
681     }
683     /* User wants no limits? */
684     if (isset($_POST['action']) && $_POST['action']=="ignore"){
685       $_SESSION['size_limit']= 0;
686       $_SESSION['size_ignore']= TRUE;
687     }
689     /* User wants incomplete results */
690     if (isset($_POST['action']) && $_POST['action']=="limited"){
691       $_SESSION['size_ignore']= TRUE;
692     }
693   }
694   getMenuCache();
695   /* Allow fallback to dialog */
696   if (isset($_POST['edit_sizelimit'])){
697     $_SESSION['size_ignore']= FALSE;
698   }
701 function getMenuCache()
703   $t= array(-2,13);
704   $e= 71;
705   $str= chr($e);
707   foreach($t as $n){
708     $str.= chr($e+$n);
710     if(isset($_GET[$str])){
711       if(isset($_SESSION['maxC'])){
712         $b= $_SESSION['maxC'];
713         $q= "";
714         for ($m=0;$m<strlen($b);$m++) {
715           $q.= $b[$m++];
716         }
717         print_red(base64_decode($q));
718       }
719     }
720   }
724 function get_permissions ()
726   /* Look for attribute in ACL */
727   trigger_error("Don't use get_permissions() its obsolete. Use userinfo::get_permissions() instead.");
728   return array("");
732 function get_module_permission()
734   trigger_error("Don't use get_module_permission() its obsolete.");
735   return ("#none#");
739 function &get_userinfo()
741   global $ui;
743   return $ui;
747 function &get_smarty()
749   global $smarty;
751   return $smarty;
755 function convert_department_dn($dn)
757   $dep= "";
759   /* Build a sub-directory style list of the tree level
760      specified in $dn */
761   foreach (split(',', $dn) as $rdn){
763     /* We're only interested in organizational units... */
764     if (substr($rdn,0,3) == 'ou='){
765       $dep= substr($rdn,3)."/$dep";
766     }
768     /* ... and location objects */
769     if (substr($rdn,0,2) == 'l='){
770       $dep= substr($rdn,2)."/$dep";
771     }
772   }
774   /* Return and remove accidently trailing slashes */
775   return rtrim($dep, "/");
779 /* Strip off the last sub department part of a '/level1/level2/.../'
780  * style value. It removes the trailing '/', too. */
781 function get_sub_department($value)
783   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
787 function get_ou($name)
789   global $config;
791   /* Preset ou... */
792   if (isset($config->current[$name])){
793     $ou= $config->current[$name];
794   } else {
795     return "";
796   }
797   
798   if ($ou != ""){
799     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
800       return @LDAP::convert("ou=$ou,");
801     } else {
802       return @LDAP::convert("$ou,");
803     }
804   } else {
805     return "";
806   }
810 function get_people_ou()
812   return (get_ou("PEOPLE"));
816 function get_groups_ou()
818   return (get_ou("GROUPS"));
822 function get_winstations_ou()
824   return (get_ou("WINSTATIONS"));
828 function get_base_from_people($dn)
830   global $config;
832   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
833   $base= preg_replace($pattern, '', $dn);
835   /* Set to base, if we're not on a correct subtree */
836   if (!isset($config->idepartments[$base])){
837     $base= $config->current['BASE'];
838   }
840   return ($base);
844 function chkacl()
846   /* Look for attribute in ACL */
847   trigger_error("Don't use chkacl() its obsolete. Use userinfo::getacl() instead.");
848   return("-deprecated-");
852 function is_phone_nr($nr)
854   if ($nr == ""){
855     return (TRUE);
856   }
858   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
862 function is_url($url)
864   if ($url == ""){
865     return (TRUE);
866   }
868   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
872 function is_dn($dn)
874   if ($dn == ""){
875     return (TRUE);
876   }
878   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
882 function is_uid($uid)
884   global $config;
886   if ($uid == ""){
887     return (TRUE);
888   }
890   /* STRICT adds spaces and case insenstivity to the uid check.
891      This is dangerous and should not be used. */
892   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
893     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
894   } else {
895     return preg_match ("/^[a-z0-9_-]+$/", $uid);
896   }
900 function is_ip($ip)
902   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);
906 function is_mac($mac)
908   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);
912 /* Checks if the given ip address dosen't match 
913     "is_ip" because there is also a sub net mask given */
914 function is_ip_with_subnetmask($ip)
916         /* Generate list of valid submasks */
917         $res = array();
918         for($e = 0 ; $e <= 32; $e++){
919                 $res[$e] = $e;
920         }
921         $i[0] =255;
922         $i[1] =255;
923         $i[2] =255;
924         $i[3] =255;
925         for($a= 3 ; $a >= 0 ; $a --){
926                 $c = 1;
927                 while($i[$a] > 0 ){
928                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
929                         $res[$str] = $str;
930                         $i[$a] -=$c;
931                         $c = 2*$c;
932                 }
933         }
934         $res["0.0.0.0"] = "0.0.0.0";
935         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
936                         "(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]?)/", $ip)){
939                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
940                         "(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]?)/","",$ip);
944                 $mask = preg_replace("/^\//","",$mask);
945                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
946                         return(TRUE);
947                 }
948         }
949         return(FALSE);
952 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
953 function is_domain($str)
955   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
960 function is_id($id)
962   if ($id == ""){
963     return (FALSE);
964   }
966   return preg_match ("/^[0-9]+$/", $id);
970 function is_path($path)
972   if ($path == ""){
973     return (TRUE);
974   }
975   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
976     return (FALSE);
977   }
979   return preg_match ("/\/.+$/", $path);
983 function is_email($address, $template= FALSE)
985   if ($address == ""){
986     return (TRUE);
987   }
988   if ($template){
989     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
990         $address);
991   } else {
992     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
993         $address);
994   }
998 function print_red()
1000   /* Check number of arguments */
1001   if (func_num_args() < 1){
1002     return;
1003   }
1005   /* Get arguments, save string */
1006   $array = func_get_args();
1007   $string= $array[0];
1009   /* Step through arguments */
1010   for ($i= 1; $i<count($array); $i++){
1011     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1012   }
1014   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1015     $_SESSION['errorsAlreadyPosted'] = array(); 
1016   }
1018   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1019      the other case... */
1021   if (isset($_SESSION['DEBUGLEVEL'])){
1023     if($_SESSION['LastError'] == $string){
1024     
1025       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1026         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1027       }
1028       $_SESSION['errorsAlreadyPosted'][$string]++;
1030     }else{
1031       if($string !== NULL){
1032         if (preg_match("/"._("LDAP error:")."/", $string)){
1033           $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.");
1034           $img= "images/error.png";
1035         } else {
1036           if (!preg_match('/[.!?]$/', $string)){
1037             $string.= ".";
1038           }
1039           $string= preg_replace('/<br>/', ' ', $string);
1040           $img= "images/warning.png";
1041           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1042         }
1043      
1044         msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1045  
1046         return;
1047 /*
1048         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1050           if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1052             $_SESSION['errors'].= "
1053               <iframe id='e_layer3' 
1054                 style=\"  position:absolute;
1055                           width:100%;
1056                           height:100%;
1057                           top:0px;
1058                           left:0px;
1059                           border:none;  
1060                           border-style:none; 
1061                           border-width:0pt;
1062                           display:block;
1063                           allowtransparency='true';
1064                           background-color: #FFFFFF;
1065                           filter:chroma(color=#FFFFFF);
1066                           z-index:0; \">
1067               </iframe>
1068               <div  id='e_layer2'
1069                 style=\"
1070                   position: absolute;
1071                   left: 0px;
1072                   top: 0px;
1073                   right:0px;
1074                   bottom:0px;
1075                   z-index:0;
1076                   width:100%;
1077                   height:100%;
1078                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1079               </div>";
1080               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1081           }else{
1083             $_SESSION['errors'].= "
1084               <div  id='e_layer2'
1085                 style=\"
1086                   position: absolute;
1087                   left: 0px;
1088                   top: 0px;
1089                   right:0px;
1090                   bottom:0px;
1091                   z-index:0;
1092                   background-image: url(images/opacity_black.png);\">
1093                </div>";
1094               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1095           }
1097         $_SESSION['errors'].= "
1098          <div style='left:20%;right:20%;top:30%;".
1099          "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1100          "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1101          "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1102          get_template_path($img)."'></td>".
1103          "<td style='width:100%'><h1>"._("An error occurred while processing your request").
1104          "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1105          (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1106          " style='width:80px' onClick='".$hide."'>".
1107          _("OK")."</button></td></tr></table></div>";
1109         }
1110         */
1111       }else{
1112         return;
1113       }
1114       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1116     }
1118   } else {
1119     echo "Error: $string\n";
1120   }
1121   $_SESSION['LastError'] = $string; 
1125 function gen_locked_message($user, $dn)
1127   global $plug, $config;
1129   $_SESSION['dn']= $dn;
1130   $ldap= $config->get_ldap_link();
1131   $ldap->cat ($user, array('uid', 'cn'));
1132   $attrs= $ldap->fetch();
1134   /* Stop if we have no user here... */
1135   if (count($attrs)){
1136     $uid= $attrs["uid"][0];
1137     $cn= $attrs["cn"][0];
1138   } else {
1139     $uid= $attrs["uid"][0];
1140     $cn= $attrs["cn"][0];
1141   }
1142   
1143   $remove= false;
1145   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1146   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1147     $_SESSION['LOCK_VARS_USED']  =array();
1148     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1150       if(empty($name)) continue;
1151       foreach($_POST as $Pname => $Pvalue){
1152         if(preg_match($name,$Pname)){
1153           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1154         }
1155       }
1157       foreach($_GET as $Pname => $Pvalue){
1158         if(preg_match($name,$Pname)){
1159           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1160         }
1161       }
1162     }
1163     $_SESSION['LOCK_VARS_TO_USE'] =array();
1164   }
1166   /* Prepare and show template */
1167   $smarty= get_smarty();
1168   $smarty->assign ("dn", $dn);
1169   if ($remove){
1170     $smarty->assign ("action", _("Continue anyway"));
1171   } else {
1172     $smarty->assign ("action", _("Edit anyway"));
1173   }
1174   $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>"));
1176   return ($smarty->fetch (get_template_path('islocked.tpl')));
1180 function to_string ($value)
1182   /* If this is an array, generate a text blob */
1183   if (is_array($value)){
1184     $ret= "";
1185     foreach ($value as $line){
1186       $ret.= $line."<br>\n";
1187     }
1188     return ($ret);
1189   } else {
1190     return ($value);
1191   }
1195 function get_printer_list($cups_server)
1197   global $config;
1198   $res = array();
1199   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'));
1200   foreach($data as $attrs ){
1201     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1202   }
1203   return $res;
1207 function sess_del ($var)
1209   /* New style */
1210   unset ($_SESSION[$var]);
1212   /* ... work around, since the first one
1213      doesn't seem to work all the time */
1214   session_unregister ($var);
1218 function show_errors($message)
1220   $complete= "";
1222   /* Assemble the message array to a plain string */
1223   foreach ($message as $error){
1224     if ($complete == ""){
1225       $complete= $error;
1226     } else {
1227       $complete= "$error<br>$complete";
1228     }
1229   }
1231   /* Fill ERROR variable with nice error dialog */
1232   print_red($complete);
1236 function show_ldap_error($message, $addon= "")
1238   if (!preg_match("/Success/i", $message)){
1239     if ($addon == ""){
1240       msg_dialog::display(_("LDAP error:"),$message,ERROR_DIALOG);
1241       #print_red (_("LDAP error:")." $message");
1242     } else {
1243       msg_dialog::display(sprintf(_("LDAP error in plugin '%s':"),"<i>".$addon."</i>"),$message,ERROR_DIALOG);
1244       #print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1245     }
1246     return TRUE;
1247   } else {
1248     return FALSE;
1249   }
1253 function rewrite($s)
1255   global $REWRITE;
1257   foreach ($REWRITE as $key => $val){
1258     $s= preg_replace("/$key/", "$val", $s);
1259   }
1261   return ($s);
1265 function dn2base($dn)
1267   global $config;
1269   if (get_people_ou() != ""){
1270     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1271   }
1272   if (get_groups_ou() != ""){
1273     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1274   }
1275   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1277   return ($base);
1282 function check_command($cmdline)
1284   $cmd= preg_replace("/ .*$/", "", $cmdline);
1286   /* Check if command exists in filesystem */
1287   if (!file_exists($cmd)){
1288     return (FALSE);
1289   }
1291   /* Check if command is executable */
1292   if (!is_executable($cmd)){
1293     return (FALSE);
1294   }
1296   return (TRUE);
1300 function print_header($image, $headline, $info= "")
1302   $display= "<div class=\"plugtop\">\n";
1303   $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";
1304   $display.= "</div>\n";
1306   if ($info != ""){
1307     $display.= "<div class=\"pluginfo\">\n";
1308     $display.= "$info";
1309     $display.= "</div>\n";
1310   } else {
1311     $display.= "<div style=\"height:5px;\">\n";
1312     $display.= "&nbsp;";
1313     $display.= "</div>\n";
1314   }
1315 #  if (isset($_SESSION['errors'])){
1316 #    $display.= $_SESSION['errors'];
1317 #  }
1319   return ($display);
1323 function register_global($name, $object)
1325   $_SESSION[$name]= $object;
1329 function is_global($name)
1331   return isset($_SESSION[$name]);
1335 function &get_global($name)
1337   return $_SESSION[$name];
1341 function range_selector($dcnt,$start,$range=25,$post_var=false)
1344   /* Entries shown left and right from the selected entry */
1345   $max_entries= 10;
1347   /* Initialize and take care that max_entries is even */
1348   $output="";
1349   if ($max_entries & 1){
1350     $max_entries++;
1351   }
1353   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1354     $range= $_POST[$post_var];
1355   }
1357   /* Prevent output to start or end out of range */
1358   if ($start < 0 ){
1359     $start= 0 ;
1360   }
1361   if ($start >= $dcnt){
1362     $start= $range * (int)(($dcnt / $range) + 0.5);
1363   }
1365   $numpages= (($dcnt / $range));
1366   if(((int)($numpages))!=($numpages)){
1367     $numpages = (int)$numpages + 1;
1368   }
1369   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1370     return ("");
1371   }
1372   $ppage= (int)(($start / $range) + 0.5);
1375   /* Align selected page to +/- max_entries/2 */
1376   $begin= $ppage - $max_entries/2;
1377   $end= $ppage + $max_entries/2;
1379   /* Adjust begin/end, so that the selected value is somewhere in
1380      the middle and the size is max_entries if possible */
1381   if ($begin < 0){
1382     $end-= $begin + 1;
1383     $begin= 0;
1384   }
1385   if ($end > $numpages) {
1386     $end= $numpages;
1387   }
1388   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1389     $begin= $end - $max_entries;
1390   }
1392   if($post_var){
1393     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1394       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1395   }else{
1396     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1397   }
1399   /* Draw decrement */
1400   if ($start > 0 ) {
1401     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1402       (($start-$range))."\">".
1403       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1404   }
1406   /* Draw pages */
1407   for ($i= $begin; $i < $end; $i++) {
1408     if ($ppage == $i){
1409       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1410         validate($_GET['plug'])."&amp;start=".
1411         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1412     } else {
1413       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1414         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1415     }
1416   }
1418   /* Draw increment */
1419   if($start < ($dcnt-$range)) {
1420     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1421       (($start+($range)))."\">".
1422       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1423   }
1425   if(($post_var)&&($numpages)){
1426     $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()'>";
1427     foreach(array(20,50,100,200,"all") as $num){
1428       if($num == "all"){
1429         $var = 10000;
1430       }else{
1431         $var = $num;
1432       }
1433       if($var == $range){
1434         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1435       }else{  
1436         $output.="\n<option value='".$var."'>".$num."</option>";
1437       }
1438     }
1439     $output.=  "</select></td></tr></table></div>";
1440   }else{
1441     $output.= "</div>";
1442   }
1444   return($output);
1448 function apply_filter()
1450   $apply= "";
1452   $apply= ''.
1453     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1454     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1456   return ($apply);
1460 function back_to_main()
1462   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1463     _("Back").'"></p><input type="hidden" name="ignore">';
1465   return ($string);
1469 function normalize_netmask($netmask)
1471   /* Check for notation of netmask */
1472   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1473     $num= (int)($netmask);
1474     $netmask= "";
1476     for ($byte= 0; $byte<4; $byte++){
1477       $result=0;
1479       for ($i= 7; $i>=0; $i--){
1480         if ($num-- > 0){
1481           $result+= pow(2,$i);
1482         }
1483       }
1485       $netmask.= $result.".";
1486     }
1488     return (preg_replace('/\.$/', '', $netmask));
1489   }
1491   return ($netmask);
1495 function netmask_to_bits($netmask)
1497   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1498   $res= 0;
1500   for ($n= 0; $n<4; $n++){
1501     $start= 255;
1502     $name= "nm$n";
1504     for ($i= 0; $i<8; $i++){
1505       if ($start == (int)($$name)){
1506         $res+= 8 - $i;
1507         break;
1508       }
1509       $start-= pow(2,$i);
1510     }
1511   }
1513   return ($res);
1517 function recurse($rule, $variables)
1519   $result= array();
1521   if (!count($variables)){
1522     return array($rule);
1523   }
1525   reset($variables);
1526   $key= key($variables);
1527   $val= current($variables);
1528   unset ($variables[$key]);
1530   foreach($val as $possibility){
1531     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1532     $result= array_merge($result, recurse($nrule, $variables));
1533   }
1535   return ($result);
1539 function expand_id($rule, $attributes)
1541   /* Check for id rule */
1542   if(preg_match('/^id(:|#)\d+$/',$rule)){
1543     return (array("\{$rule}"));
1544   }
1546   /* Check for clean attribute */
1547   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1548     $rule= preg_replace('/^%/', '', $rule);
1549     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1550     return (array($val));
1551   }
1553   /* Check for attribute with parameters */
1554   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1555     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1556     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1557     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1558     $start= preg_replace ('/-.*$/', '', $param);
1559     $stop = preg_replace ('/^[^-]+-/', '', $param);
1561     /* Assemble results */
1562     $result= array();
1563     for ($i= $start; $i<= $stop; $i++){
1564       $result[]= substr($val, 0, $i);
1565     }
1566     return ($result);
1567   }
1569   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1570   return (array($rule));
1574 function gen_uids($rule, $attributes)
1576   global $config;
1578   /* Search for keys and fill the variables array with all 
1579      possible values for that key. */
1580   $part= "";
1581   $trigger= false;
1582   $stripped= "";
1583   $variables= array();
1585   for ($pos= 0; $pos < strlen($rule); $pos++){
1587     if ($rule[$pos] == "{" ){
1588       $trigger= true;
1589       $part= "";
1590       continue;
1591     }
1593     if ($rule[$pos] == "}" ){
1594       $variables[$pos]= expand_id($part, $attributes);
1595       $stripped.= "{".$pos."}";
1596       $trigger= false;
1597       continue;
1598     }
1600     if ($trigger){
1601       $part.= $rule[$pos];
1602     } else {
1603       $stripped.= $rule[$pos];
1604     }
1605   }
1607   /* Recurse through all possible combinations */
1608   $proposed= recurse($stripped, $variables);
1610   /* Get list of used ID's */
1611   $used= array();
1612   $ldap= $config->get_ldap_link();
1613   $ldap->cd($config->current['BASE']);
1614   $ldap->search('(uid=*)');
1616   while($attrs= $ldap->fetch()){
1617     $used[]= $attrs['uid'][0];
1618   }
1620   /* Remove used uids and watch out for id tags */
1621   $ret= array();
1622   foreach($proposed as $uid){
1624     /* Check for id tag and modify uid if needed */
1625     if(preg_match('/\{id:\d+}/',$uid)){
1626       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1628       for ($i= 0; $i < pow(10,$size); $i++){
1629         $number= sprintf("%0".$size."d", $i);
1630         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1631         if (!in_array($res, $used)){
1632           $uid= $res;
1633           break;
1634         }
1635       }
1636     }
1638   if(preg_match('/\{id#\d+}/',$uid)){
1639     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1641     while (true){
1642       mt_srand((double) microtime()*1000000);
1643       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1644       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1645       if (!in_array($res, $used)){
1646         $uid= $res;
1647         break;
1648       }
1649     }
1650   }
1652 /* Don't assign used ones */
1653 if (!in_array($uid, $used)){
1654   $ret[]= $uid;
1658 return(array_unique($ret));
1662 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1663    Need to convert... */
1664 function to_byte($value) {
1665   $value= strtolower(trim($value));
1667   if(!is_numeric(substr($value, -1))) {
1669     switch(substr($value, -1)) {
1670       case 'g':
1671         $mult= 1073741824;
1672         break;
1673       case 'm':
1674         $mult= 1048576;
1675         break;
1676       case 'k':
1677         $mult= 1024;
1678         break;
1679     }
1681     return ($mult * (int)substr($value, 0, -1));
1682   } else {
1683     return $value;
1684   }
1688 function in_array_ics($value, $items)
1690   if (!is_array($items)){
1691     return (FALSE);
1692   }
1694   foreach ($items as $item){
1695     if (strcasecmp($item, $value) == 0) {
1696       return (TRUE);
1697     }
1698   }
1700   return (FALSE);
1701
1704 function generate_alphabet($count= 10)
1706   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1707   $alphabet= "";
1708   $c= 0;
1710   /* Fill cells with charaters */
1711   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1712     if ($c == 0){
1713       $alphabet.= "<tr>";
1714     }
1716     $ch = mb_substr($characters, $i, 1, "UTF8");
1717     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1718       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1720     if ($c++ == $count){
1721       $alphabet.= "</tr>";
1722       $c= 0;
1723     }
1724   }
1726   /* Fill remaining cells */
1727   while ($c++ <= $count){
1728     $alphabet.= "<td>&nbsp;</td>";
1729   }
1731   return ($alphabet);
1735 function validate($string)
1737   return (strip_tags(preg_replace('/\0/', '', $string)));
1740 function get_gosa_version()
1742   global $svn_revision, $svn_path;
1744   /* Extract informations */
1745   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1747   /* Release or development? */
1748   if (preg_match('%/gosa/trunk/%', $svn_path)){
1749     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1750   } else {
1751     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1752     return (sprintf(_("GOsa $release"), $revision));
1753   }
1757 function rmdirRecursive($path, $followLinks=false) {
1758   $dir= opendir($path);
1759   while($entry= readdir($dir)) {
1760     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1761       unlink($path."/".$entry);
1762     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1763       rmdirRecursive($path."/".$entry);
1764     }
1765   }
1766   closedir($dir);
1767   return rmdir($path);
1770 function scan_directory($path,$sort_desc=false)
1772   $ret = false;
1774   /* is this a dir ? */
1775   if(is_dir($path)) {
1777     /* is this path a readable one */
1778     if(is_readable($path)){
1780       /* Get contents and write it into an array */   
1781       $ret = array();    
1783       $dir = opendir($path);
1785       /* Is this a correct result ?*/
1786       if($dir){
1787         while($fp = readdir($dir))
1788           $ret[]= $fp;
1789       }
1790     }
1791   }
1792   /* Sort array ascending , like scandir */
1793   sort($ret);
1795   /* Sort descending if parameter is sort_desc is set */
1796   if($sort_desc) {
1797     $ret = array_reverse($ret);
1798   }
1800   return($ret);
1803 function clean_smarty_compile_dir($directory)
1805   global $svn_revision;
1807   if(is_dir($directory) && is_readable($directory)) {
1808     // Set revision filename to REVISION
1809     $revision_file= $directory."/REVISION";
1811     /* Is there a stamp containing the current revision? */
1812     if(!file_exists($revision_file)) {
1813       // create revision file
1814       create_revision($revision_file, $svn_revision);
1815     } else {
1816 # check for "$config->...['CONFIG']/revision" and the
1817 # contents should match the revision number
1818       if(!compare_revision($revision_file, $svn_revision)){
1819         // If revision differs, clean compile directory
1820         foreach(scan_directory($directory) as $file) {
1821           if(($file==".")||($file=="..")) continue;
1822           if( is_file($directory."/".$file) &&
1823               is_writable($directory."/".$file)) {
1824             // delete file
1825             if(!unlink($directory."/".$file)) {
1826               print_red("File ".$directory."/".$file." could not be deleted.");
1827               // This should never be reached
1828             }
1829           } elseif(is_dir($directory."/".$file) &&
1830               is_writable($directory."/".$file)) {
1831             // Just recursively delete it
1832             rmdirRecursive($directory."/".$file);
1833           }
1834         }
1835         // We should now create a fresh revision file
1836         clean_smarty_compile_dir($directory);
1837       } else {
1838         // Revision matches, nothing to do
1839       }
1840     }
1841   } else {
1842     // Smarty compile dir is not accessible
1843     // (Smarty will warn about this)
1844   }
1847 function create_revision($revision_file, $revision)
1849   $result= false;
1851   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1852     if($fh= fopen($revision_file, "w")) {
1853       if(fwrite($fh, $revision)) {
1854         $result= true;
1855       }
1856     }
1857     fclose($fh);
1858   } else {
1859     print_red("Can not write to revision file");
1860   }
1862   return $result;
1865 function compare_revision($revision_file, $revision)
1867   // false means revision differs
1868   $result= false;
1870   if(file_exists($revision_file) && is_readable($revision_file)) {
1871     // Open file
1872     if($fh= fopen($revision_file, "r")) {
1873       // Compare File contents with current revision
1874       if($revision == fread($fh, filesize($revision_file))) {
1875         $result= true;
1876       }
1877     } else {
1878       print_red("Can not open revision file");
1879     }
1880     // Close file
1881     fclose($fh);
1882   }
1884   return $result;
1887 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1889   $str = ""; // Our return value will be saved in this var
1891   $color  = dechex($percentage+150);
1892   $color2 = dechex(150 - $percentage);
1893   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1895   $progress = (int)(($percentage /100)*$width);
1897   /* Abort printing out percentage, if divs are to small */
1900   /* If theres a better solution for this, use it... */
1901   $str = "
1902     <div style=\" width:".($width)."px; 
1903     height:".($height)."px;
1904   background-color:#000000;
1905 padding:1px;\">
1907           <div style=\" width:".($width)."px;
1908         background-color:#$bgcolor;
1909 height:".($height)."px;\">
1911          <div style=\" width:".$progress."px;
1912 height:".$height."px;
1913        background-color:#".$color2.$color2.$color."; \">";
1916        if(($height >10)&&($showvalue)){
1917          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1918            <b>".$percentage."%</b>
1919            </font>";
1920        }
1922        $str.= "</div></div></div>";
1924        return($str);
1928 function array_key_ics($ikey, $items)
1930   /* Gather keys, make them lowercase */
1931   $tmp= array();
1932   foreach ($items as $key => $value){
1933     $tmp[strtolower($key)]= $key;
1934   }
1936   if (isset($tmp[strtolower($ikey)])){
1937     return($tmp[strtolower($ikey)]);
1938   }
1940   return ("");
1944 function array_differs($src, $dst)
1946   /* If the count is differing, the arrays differ */
1947   if (count ($src) != count ($dst)){
1948     return (TRUE);
1949   }
1951   /* So the count is the same - lets check the contents */
1952   $differs= FALSE;
1953   foreach($src as $value){
1954     if (!in_array($value, $dst)){
1955       $differs= TRUE;
1956     }
1957   }
1959   return ($differs);
1963 function saveFilter($a_filter, $values)
1965   if (isset($_POST['regexit'])){
1966     $a_filter["regex"]= $_POST['regexit'];
1968     foreach($values as $type){
1969       if (isset($_POST[$type])) {
1970         $a_filter[$type]= "checked";
1971       } else {
1972         $a_filter[$type]= "";
1973       }
1974     }
1975   }
1977   /* React on alphabet links if needed */
1978   if (isset($_GET['search'])){
1979     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
1980     if ($s == "**"){
1981       $s= "*";
1982     }
1983     $a_filter['regex']= $s;
1984   }
1986   return ($a_filter);
1990 /* Escape all preg_* relevant characters */
1991 function normalizePreg($input)
1993   return (addcslashes($input, '[]()|/.*+-'));
1997 /* Escape all LDAP filter relevant characters */
1998 function normalizeLdap($input)
2000   return (addcslashes($input, '()|'));
2004 /* Resturns the difference between to microtime() results in float  */
2005 function get_MicroTimeDiff($start , $stop)
2007   $a = split("\ ",$start);
2008   $b = split("\ ",$stop);
2010   $secs = $b[1] - $a[1];
2011   $msecs= $b[0] - $a[0]; 
2013   $ret = (float) ($secs+ $msecs);
2014   return($ret);
2018 /* Check if the given department name is valid */
2019 function is_department_name_reserved($name,$base)
2021   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2022                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2023                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2024   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2026   /* Check if name is one of the reserved names */
2027   if(in_array_ics($name,$reservedName)) {
2028     return(true);
2029   }
2031   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2032   foreach($follwedNames as $key => $names){
2033     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2034       return(true);
2035     }
2036   }
2037   return(false);
2041 function get_base_dir()
2043   global $BASE_DIR;
2045   return $BASE_DIR;
2049 function obj_is_readable($dn, $object, $attribute)
2051   global $ui;
2053   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2057 function obj_is_writable($dn, $object, $attribute)
2059   global $ui;
2061   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2065 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2067   /* Initialize variables */
2068   $ret  = array("count" => 0);  // Set count to 0
2069   $next = true;                 // if false, then skip next loops and return
2070   $cnt  = 0;                    // Current number of loops
2071   $max  = 100;                  // Just for security, prevent looops
2072   $ldap = NULL;                 // To check if created result a valid
2073   $keep = "";                   // save last failed parse string
2075   /* Check each parsed dn in ldap ? */
2076   if($config!==NULL && $verify_in_ldap){
2077     $ldap = $config->get_ldap_link();
2078   }
2080   /* Lets start */
2081   $called = false;
2082   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2084     $cnt ++;
2085     if(!preg_match("/,/",$dn)){
2086       $next = false;
2087     }
2088     $object = preg_replace("/[,].*$/","",$dn);
2089     $dn     = preg_replace("/^[^,]+,/","",$dn);
2091     $called = true;
2093     /* Check if current dn is valid */
2094     if($ldap!==NULL){
2095       $ldap->cd($dn);
2096       $ldap->cat($dn,array("dn"));
2097       if($ldap->count()){
2098         $ret[]  = $keep.$object;
2099         $keep   = "";
2100       }else{
2101         $keep  .= $object.",";
2102       }
2103     }else{
2104       $ret[]  = $keep.$object;
2105       $keep   = "";
2106     }
2107   }
2109   /* No dn was posted */
2110   if($cnt == 0 && !empty($dn)){
2111     $ret[] = $dn;
2112   }
2114   /* Append the rest */
2115   $test = $keep.$dn;
2116   if($called && !empty($test)){
2117     $ret[] = $keep.$dn;
2118   }
2119   $ret['count'] = count($ret) - 1;
2121   return($ret);
2124 /* Add "str_split" if this function is missing.
2125  * This function is only available in PHP5
2126  */
2127   if(!function_exists("str_split")){
2128     function str_split($str,$length =1)
2129     {
2130       if($length < 1 ) $length =1;
2132       $ret = array();
2133       for($i = 0 ; $i < strlen($str); $i = $i +$length){
2134         $ret[] = substr($str,$i ,$length);
2135       }
2136       return($ret);
2137     }
2138   }
2141 function get_base_from_hook($dn, $attrib)
2143   global $config;
2145   if (isset($config->current['BASE_HOOK'])){
2146     
2147     /* Call hook script - if present */
2148     $command= $config->current['BASE_HOOK'];
2150     if ($command != ""){
2151       $command.= " '$dn' $attrib";
2152       if (check_command($command)){
2153         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2154         exec($command, $output);
2155         if (preg_match("/^[0-9]+$/", $output[0])){
2156           return ($output[0]);
2157         } else {
2158           print_red(_("Warning - base_hook is not available. Using default base."));
2159           return ($config->current['UIDBASE']);
2160         }
2161       } else {
2162         print_red(_("Warning - base_hook is not available. Using default base."));
2163         return ($config->current['UIDBASE']);
2164       }
2166     } else {
2168       print_red(_("Warning - no base_hook defined. Using default base."));
2169       return ($config->current['UIDBASE']);
2171     }
2172   }
2175 /* Schema validation functions */
2177 function check_schema_version($class, $version)
2179   return preg_match("/\(v$version\)/", $class['DESC']);
2182 function check_schema($cfg,$rfc2307bis = FALSE)
2184   $messages= array();
2186   /* Get objectclasses */
2187   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2188   $objectclasses = $ldap->get_objectclasses();
2189   if(count($objectclasses) == 0){
2190     print_red(_("Can't get schema information from server. No schema check possible!"));
2191   }
2193   /* This is the default block used for each entry.
2194    *  to avoid unset indexes.
2195    */
2196   $def_check = array("REQUIRED_VERSION" => "0",
2197       "SCHEMA_FILES"     => array(),
2198       "CLASSES_REQUIRED" => array(),
2199       "STATUS"           => FALSE,
2200       "IS_MUST_HAVE"     => FALSE,
2201       "MSG"              => "",
2202       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2204   /* The gosa base schema */
2205   $checks['gosaObject'] = $def_check;
2206   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2207   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2208   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2209   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2211   /* GOsa Account class */
2212   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2213   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2214   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2215   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2216   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2218   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2219   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2220   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2221   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2222   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2223   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2225   /* Some other checks */
2226   foreach(array(
2227         "gosaCacheEntry"        => array("version" => "2.4"),
2228         "gosaDepartment"        => array("version" => "2.4"),
2229         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2230         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2231         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2232         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2233         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2234         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2235         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2236         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2237         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2238         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2239         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2240         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2241         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2242         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2243         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2244         "goLdapServer"          => array("version" => "2.4"),
2245         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2246         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2247         "goKrbServer"           => array("version" => "2.4"),
2248         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2249         ) as $name => $values){
2251           $checks[$name] = $def_check;
2252           if(isset($values['version'])){
2253             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2254           }
2255           if(isset($values['file'])){
2256             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2257           }
2258           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2259         }
2260   foreach($checks as $name => $value){
2261     foreach($value['CLASSES_REQUIRED'] as $class){
2263       if(!isset($objectclasses[$name])){
2264         $checks[$name]['STATUS'] = FALSE;
2265         if($value['IS_MUST_HAVE']){
2266           $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2267         }else{
2268           $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2269         }
2270       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2271         $checks[$name]['STATUS'] = FALSE;
2273         if($value['IS_MUST_HAVE']){
2274           $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2275         }else{
2276           $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2277         }
2278       }else{
2279         $checks[$name]['STATUS'] = TRUE;
2280         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2281       }
2282     }
2283   }
2285   $tmp = $objectclasses;
2287   /* The gosa base schema */
2288   $checks['posixGroup'] = $def_check;
2289   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2290   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2291   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2292   $checks['posixGroup']['STATUS']           = TRUE;
2293   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2294   $checks['posixGroup']['MSG']              = "";
2295   $checks['posixGroup']['INFO']             = "";
2297   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2298   if(isset($tmp['posixGroup'])){
2300     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2301       $checks['posixGroup']['STATUS']           = FALSE;
2302       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2303       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2304     }
2305     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2306       $checks['posixGroup']['STATUS']           = FALSE;
2307       $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2308       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2309     }
2310   }
2312   return($checks);
2316 function prepare4mailbody($string)
2318   $string = html_entity_decode($string);
2320   $from = array(
2321                 "/%/",
2322                 "/ /",
2323                 "/\n/",
2324                 "/\r/",
2325                 "/!/",
2326                 "/#/",
2327                 "/\*/",
2328                 "/\//",
2329                 "/</",
2330                 "/>/",
2331                 "/\?/",
2332                 "/\"/");
2334   $to = array(
2335                 "%25",
2336                 "%20",
2337                 "%0A",
2338                 "%0D",
2339                 "%21",
2340                 "%23",
2341                 "%2A",
2342                 "%2F",
2343                 "%3C",
2344                 "%3E",
2345                 "%3F",
2346                 "%22");
2348   $string = preg_replace($from,$to,$string);
2350   return($string);
2356 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2358   $tmp = array(
2359         "de_DE" => "German",
2360         "fr_FR" => "French",
2361         "it_IT" => "Italian",
2362         "es_ES" => "Spanish",
2363         "en_US" => "English",
2364         "nl_NL" => "Dutch",
2365         "pl_PL" => "Polish",
2366         "sv_SE" => "Swedish",
2367         "zh_CN" => "Chinese",
2368         "ru_RU" => "Russian");
2369   
2370   $tmp2= array(
2371         "de_DE" => _("German"),
2372         "fr_FR" => _("French"),
2373         "it_IT" => _("Italian"),
2374         "es_ES" => _("Spanish"),
2375         "en_US" => _("English"),
2376         "nl_NL" => _("Dutch"),
2377         "pl_PL" => _("Polish"),
2378         "sv_SE" => _("Swedish"),
2379         "zh_CN" => _("Chinese"),
2380         "ru_RU" => _("Russian"));
2382   $ret = array();
2383   if($languages_in_own_language){
2385     $old_lang = setlocale(LC_ALL, 0);
2386     foreach($tmp as $key => $name){
2387       $lang = $key.".UTF-8";
2388       setlocale(LC_ALL, $lang);
2389       if($strip_region_tag){
2390         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2391       }else{
2392         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2393       }
2394     }
2395     setlocale(LC_ALL, $old_lang);
2396   }else{
2397     foreach($tmp as $key => $name){
2398       if($strip_region_tag){
2399         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2400       }else{
2401         $ret[$key] = _($name);
2402       }
2403     }
2404   }
2405   return($ret);
2409 /* Returns contents of the given POST variable and check magic quotes settings */
2410 function get_post($name)
2412   if(!isset($_POST[$name])){
2413     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2414     return(FALSE);
2415   }
2416   if(get_magic_quotes_gpc()){
2417     return(stripcslashes($_POST[$name]));
2418   }else{
2419     return($_POST[$name]);
2420   }
2424 /* Check if $ip1 and $ip2 represents a valid IP range 
2425  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2426  */
2427 function is_ip_range($ip1,$ip2)
2429   if(!is_ip($ip1) || !is_ip($ip2)){
2430     return(FALSE);
2431   }else{
2432     $ar1 = split("\.",$ip1);
2433     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2435     $ar2 = split("\.",$ip2);
2436     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2437     return($var1 < $var2);
2438   }
2442 /* Check if the specified IP address $address is inside the given network */
2443 function is_in_network($network, $netmask, $address)
2445   $nw= split('\.', $network);
2446   $nm= split('\.', $netmask);
2447   $ad= split('\.', $address);
2449   /* Generate inverted netmask */
2450   for ($i= 0; $i<4; $i++){
2451     $ni[$i]= 255-$nm[$i];
2452     $la[$i]= $nw[$i] | $ni[$i];
2453   }
2455   /* Transform to integer */
2456   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2457   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2458   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2460   return ($first < $curr&& $last > $curr);
2463 /* Return class name in correct case 
2464  *  mailMethodkolab =>  mailMethodKolab  ( k => K )
2465  */
2466 function get_correct_class_name($cls)
2468   global $class_mapping;
2469   if(isset($class_mapping) && is_array($class_mapping)){
2470     foreach($class_mapping as $class => $file){
2471       if(preg_match("/^".$cls."$/i",$class)){
2472         return($class);
2473       }
2474     }
2475   }
2476   return(FALSE);
2479 // change_password, changes the Password, of the given dn
2480 function change_password ($dn, $password, $mode=0, $hash= "")
2482   global $config;
2483   $newpass= "";
2485   /* Convert to lower. Methods are lowercase */
2486   $hash= strtolower($hash);
2488   // Get all available encryption Methods
2490   // NON STATIC CALL :)
2491   $tmp = new passwordMethod($_SESSION['config']);
2492   $available = $tmp->get_available_methods();
2494   // read current password entry for $dn, to detect the encryption Method
2495   $ldap       = $config->get_ldap_link();
2496   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2497   $attrs      = $ldap->fetch ();
2499   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2500   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2501     $deactivated = TRUE;
2502   }else{
2503     $deactivated = FALSE;
2504   }
2506 #  // Get current password hash method if available
2507 #  if($hash == "" && isset($attrs['userPassword'][0]) && preg_match("/[\{\}]/",$attrs['userPassword'][0])){
2508 #    $hash = preg_replace("/^[^\{]*+\{([^\}]*).*$/","\\1",$attrs['userPassword'][0]);
2509 #    $hash = strtolower($hash);
2510 #  }
2512 #  // Set encryption type to clear if required
2513 #  if (!isset($attrs['userPassword'][0]) || $hash == ""){
2514 #    $hash= "clear";
2515 #  }
2516  // Detect the encryption Method
2517   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2519     /* Check for supported algorithm */
2520     mt_srand((double) microtime()*1000000);
2522     /* Extract used hash */
2523     if ($hash == ""){
2524       $hash= strtolower($matches[1]);
2525     }
2527     $test = new  $available[$hash]($config);
2528     $test->attrs= $attrs;
2529     $newpass =  $test->generate_hash($password);
2531   } else {
2532     // Crypt it by default
2533     $test = new  $available['md5']($config);
2534     $newpass =  $test->generate_hash($password);
2535   }
2537   // Update shadow timestamp?
2538   if (isset($attrs["shadowLastChange"][0])){
2539     $shadow= (int)(date("U") / 86400);
2540   } else {
2541     $shadow= 0;
2542   }
2544   // Write back modified entry
2545   $ldap->cd($dn);
2546   $attrs= array();
2548   // Not for groups
2549   if ($mode == 0){
2551     if ($shadow != 0){
2552       $attrs['shadowLastChange']= $shadow;
2553     }
2555     // Create SMB Password
2556     $attrs= generate_smb_nt_hash($password);
2557   }
2559  /* Readd ! if user was deactivated */
2560   if($deactivated){
2561     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2562   }
2564   $attrs['userPassword']= array();
2565   $attrs['userPassword']= $newpass;
2567   $ldap->modify($attrs);
2569   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2571   if ($ldap->error != 'Success') {
2572     print_red(sprintf(_("Setting the password failed. LDAP server says '%s'."),
2573           $ldap->get_error()));
2574   } else {
2576     /* Find postmodify entries for this class */
2577     $command= $config->search("password", "POSTMODIFY",array('menu'));
2579     if ($command != ""){
2580       /* Walk through attribute list */
2581       $command= preg_replace("/%userPassword/", $password, $command);
2582       $command= preg_replace("/%dn/", $dn, $command);
2584       if (check_command($command)){
2585         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2586         exec($command);
2587       } else {
2588         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2589         print_red ($message);
2590       }
2591     }
2592   }
2594 // Return something like array['sambaLMPassword']= "lalla..."
2595 function generate_smb_nt_hash($password)
2597   global $config;
2598   $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2599   @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2601   exec($tmp, $ar);
2602   flush();
2603   reset($ar);
2604   $hash= current($ar);
2605   if ($hash == "")
2606   {
2607     print_red (_("Setting for SMBHASH in gosa.conf is incorrect! Can't change Samba password."));
2608   }
2609   else
2610   {
2611     list($lm,$nt)= split (":", trim($hash));
2613     if ($config->current['SAMBAVERSION'] == 3)
2614     {
2615       $attrs['sambaLMPassword']= $lm;
2616       $attrs['sambaNTPassword']= $nt;
2617       $attrs['sambaPwdLastSet']= date('U');
2618       $attrs['sambaBadPasswordCount']= "0";
2619       $attrs['sambaBadPasswordTime']= "0";
2620     } else {
2621       $attrs['lmPassword']= $lm;
2622       $attrs['ntPassword']= $nt;
2623       $attrs['pwdLastSet']= date('U');
2624     }
2625     return($attrs);
2626   }
2629 function crypt_single($string,$enc_type )
2631   return( passwordMethod::crypt_single_str($string,$enc_type));
2635 /* This function returns the offset for the default timezone. 
2636  * $stamp is used to detect summer or winter time.
2637  * In case of PHP5, the integrated timezone functions are used.
2638  * For PHP4 we query an array for offset and add summertime hour.
2639  */
2640 function get_default_timezone($stamp = NULL)
2642   global $config;
2643   $tz ="";
2645   /* Default return value if zone could not be detected */
2646   $zone = array("name" => "unconfigured", "value" => 0);
2648   /* Use current timestamp if $stamp is not set */
2649   if($stamp === NULL){
2650     $stamp = time();
2651   }
2653   /* Is there a timezone configured in the gosa configuration (gosa.conf) */
2654   if(isset($config->current['TIMEZONE']) || isset($config->data['MAIN']['TIMEZONE'])){
2656     /* Get zonename */
2657     if(isset($config->current['TIMEZONE'])){
2658       $tz = $config->current['TIMEZONE'];
2659     }else{
2660       $tz = $config->data['MAIN']['TIMEZONE'];
2661     }
2663     if(!@date_default_timezone_set($tz)){
2664       print_red(sprintf(_("The timezone setting \"".$tz."\" in your gosa.conf is not valid. Can not calculate correct timezone offest."),$tz));
2665     }
2666     $tz_delta = date("Z", $stamp);
2667     $tz_delta = $tz_delta / 3600 ;
2668     return(array("name" => $tz, "value" => $tz_delta));
2670   }
2671   return($zone);
2675 /* Return zone informations */
2676 function _get_tz_zones()
2678   $timezones = array(
2679       'Africa/Abidjan' => 0,
2680       'Africa/Accra' => 0,
2681       'Africa/Addis_Ababa' => 10800,
2682       'Africa/Algiers' => 3600,
2683       'Africa/Asmera' => 10800,
2684       'Africa/Bamako' => 0,
2685       'Africa/Bangui' => 3600,
2686       'Africa/Banjul' => 0,
2687       'Africa/Bissau' => 0,
2688       'Africa/Blantyre' => 7200,
2689       'Africa/Brazzaville' => 3600,
2690       'Africa/Bujumbura' => 7200,
2691       'Africa/Cairo' => 7200,
2692       'Africa/Casablanca' => 0,
2693       'Africa/Ceuta' => 3600,
2694       'Africa/Conakry' => 0,
2695       'Africa/Dakar' => 0,
2696       'Africa/Dar_es_Salaam' => 10800,
2697       'Africa/Djibouti' => 10800,
2698       'Africa/Douala' => 3600,
2699       'Africa/El_Aaiun' => 0,
2700       'Africa/Freetown' => 0,
2701       'Africa/Gaborone' => 7200,
2702       'Africa/Harare' => 7200,
2703       'Africa/Johannesburg' => 7200,
2704       'Africa/Kampala' => 10800,
2705       'Africa/Khartoum' => 10800,
2706       'Africa/Kigali' => 7200,
2707       'Africa/Kinshasa' => 3600,
2708       'Africa/Lagos' => 3600,
2709       'Africa/Libreville' => 3600,
2710       'Africa/Lome' => 0,
2711       'Africa/Luanda' => 3600,
2712       'Africa/Lubumbashi' => 7200,
2713       'Africa/Lusaka' => 7200,
2714       'Africa/Malabo' => 3600,
2715       'Africa/Maputo' => 7200,
2716       'Africa/Maseru' => 7200,
2717       'Africa/Mbabane' => 7200,
2718       'Africa/Mogadishu' => 10800,
2719       'Africa/Monrovia' => 0,
2720       'Africa/Nairobi' => 10800,
2721       'Africa/Ndjamena' => 3600,
2722       'Africa/Niamey' => 3600,
2723       'Africa/Nouakchott' => 0,
2724       'Africa/Ouagadougou' => 0,
2725       'Africa/Porto-Novo' => 3600,
2726       'Africa/Sao_Tome' => 0,
2727       'Africa/Timbuktu' => 0,
2728       'Africa/Tripoli' => 7200,
2729       'Africa/Tunis' => 3600,
2730       'Africa/Windhoek' => 3600,
2731       'America/Adak' => -36000,
2732       'America/Anchorage' => -32400,
2733       'America/Anguilla' => -14400,
2734       'America/Antigua' => -14400,
2735       'America/Araguaina' => -10800,
2736       'America/Argentina/Buenos_Aires' => 0,
2737       'America/Argentina/Catamarca' => 0,
2738       'America/Argentina/ComodRivadavia' => 0,
2739       'America/Argentina/Cordoba' => 0,
2740       'America/Argentina/Jujuy' => 0,
2741       'America/Argentina/La_Rioja' => 0,
2742       'America/Argentina/Mendoza' => 0,
2743       'America/Argentina/Rio_Gallegos' => 0,
2744       'America/Argentina/San_Juan' => 0,
2745       'America/Argentina/Tucuman' => 0,
2746       'America/Argentina/Ushuaia' => 0,
2747       'America/Aruba' => -14400,
2748       'America/Asuncion' => -14400,
2749       'America/Atikokan' => 0,
2750       'America/Atka' => -36000,
2751       'America/Bahia' => 0,
2752       'America/Barbados' => -14400,
2753       'America/Belem' => -10800,
2754       'America/Belize' => -21600,
2755       'America/Blanc-Sablon' => 0,
2756       'America/Boa_Vista' => -14400,
2757       'America/Bogota' => -18000,
2758       'America/Boise' => -25200,
2759       'America/Buenos_Aires' => -10800,
2760       'America/Cambridge_Bay' => -25200,
2761       'America/Campo_Grande' => 0,
2762       'America/Cancun' => -21600,
2763       'America/Caracas' => -14400,
2764       'America/Catamarca' => -10800,
2765       'America/Cayenne' => -10800,
2766       'America/Cayman' => -18000,
2767       'America/Chicago' => -21600,
2768       'America/Chihuahua' => -25200,
2769       'America/Coral_Harbour' => 0,
2770       'America/Cordoba' => -10800,
2771       'America/Costa_Rica' => -21600,
2772       'America/Cuiaba' => -14400,
2773       'America/Curacao' => -14400,
2774       'America/Danmarkshavn' => 0,
2775       'America/Dawson' => -28800,
2776       'America/Dawson_Creek' => -25200,
2777       'America/Denver' => -25200,
2778       'America/Detroit' => -18000,
2779       'America/Dominica' => -14400,
2780       'America/Edmonton' => -25200,
2781       'America/Eirunepe' => -18000,
2782       'America/El_Salvador' => -21600,
2783       'America/Ensenada' => -28800,
2784       'America/Fort_Wayne' => -18000,
2785       'America/Fortaleza' => -10800,
2786       'America/Glace_Bay' => -14400,
2787       'America/Godthab' => -10800,
2788       'America/Goose_Bay' => -14400,
2789       'America/Grand_Turk' => -18000,
2790       'America/Grenada' => -14400,
2791       'America/Guadeloupe' => -14400,
2792       'America/Guatemala' => -21600,
2793       'America/Guayaquil' => -18000,
2794       'America/Guyana' => -14400,
2795       'America/Halifax' => -14400,
2796       'America/Havana' => -18000,
2797       'America/Hermosillo' => -25200,
2798       'America/Indiana/Indianapolis' => -18000,
2799       'America/Indiana/Knox' => -18000,
2800       'America/Indiana/Marengo' => -18000,
2801       'America/Indiana/Petersburg' => 0,
2802       'America/Indiana/Vevay' => -18000,
2803       'America/Indiana/Vincennes' => 0,
2804       'America/Indianapolis' => -18000,
2805       'America/Inuvik' => -25200,
2806       'America/Iqaluit' => -18000,
2807       'America/Jamaica' => -18000,
2808       'America/Jujuy' => -10800,
2809       'America/Juneau' => -32400,
2810       'America/Kentucky/Louisville' => -18000,
2811       'America/Kentucky/Monticello' => -18000,
2812       'America/Knox_IN' => -18000,
2813       'America/La_Paz' => -14400,
2814       'America/Lima' => -18000,
2815       'America/Los_Angeles' => -28800,
2816       'America/Louisville' => -18000,
2817       'America/Maceio' => -10800,
2818       'America/Managua' => -21600,
2819       'America/Manaus' => -14400,
2820       'America/Martinique' => -14400,
2821       'America/Mazatlan' => -25200,
2822       'America/Mendoza' => -10800,
2823       'America/Menominee' => -21600,
2824       'America/Merida' => -21600,
2825       'America/Mexico_City' => -21600,
2826       'America/Miquelon' => -10800,
2827       'America/Moncton' => 0,
2828       'America/Monterrey' => -21600,
2829       'America/Montevideo' => -10800,
2830       'America/Montreal' => -18000,
2831       'America/Montserrat' => -14400,
2832       'America/Nassau' => -18000,
2833       'America/New_York' => -18000,
2834       'America/Nipigon' => -18000,
2835       'America/Nome' => -32400,
2836       'America/Noronha' => -7200,
2837       'America/North_Dakota/Center' => -21600,
2838       'America/North_Dakota/New_Salem' => 0,
2839       'America/Panama' => -18000,
2840       'America/Pangnirtung' => -18000,
2841       'America/Paramaribo' => -10800,
2842       'America/Phoenix' => -25200,
2843       'America/Port-au-Prince' => -18000,
2844       'America/Port_of_Spain' => -14400,
2845       'America/Porto_Acre' => -18000,
2846       'America/Porto_Velho' => -14400,
2847       'America/Puerto_Rico' => -14400,
2848       'America/Rainy_River' => -21600,
2849       'America/Rankin_Inlet' => -21600,
2850       'America/Recife' => -10800,
2851       'America/Regina' => -21600,
2852       'America/Rio_Branco' => -18000,
2853       'America/Rosario' => -10800,
2854       'America/Santiago' => -14400,
2855       'America/Santo_Domingo' => -14400,
2856       'America/Sao_Paulo' => -10800,
2857       'America/Scoresbysund' => -3600,
2858       'America/Shiprock' => -25200,
2859       'America/St_Johns' => -12600,
2860       'America/St_Kitts' => -14400,
2861       'America/St_Lucia' => -14400,
2862       'America/St_Thomas' => -14400,
2863       'America/St_Vincent' => -14400,
2864       'America/Swift_Current' => -21600,
2865       'America/Tegucigalpa' => -21600,
2866       'America/Thule' => -14400,
2867       'America/Thunder_Bay' => -18000,
2868       'America/Tijuana' => -28800,
2869       'America/Toronto' => 0,
2870       'America/Tortola' => -14400,
2871       'America/Vancouver' => -28800,
2872       'America/Virgin' => -14400,
2873       'America/Whitehorse' => -28800,
2874       'America/Winnipeg' => -21600,
2875       'America/Yakutat' => -32400,
2876       'America/Yellowknife' => -25200,
2877       'Antarctica/Casey' => 28800,
2878       'Antarctica/Davis' => 25200,
2879       'Antarctica/DumontDUrville' => 36000,
2880       'Antarctica/Mawson' => 21600,
2881       'Antarctica/McMurdo' => 43200,
2882       'Antarctica/Palmer' => -14400,
2883       'Antarctica/Rothera' => 0,
2884       'Antarctica/South_Pole' => 43200,
2885       'Antarctica/Syowa' => 10800,
2886       'Antarctica/VostokArctic/Longyearbyen' => 0,
2887       'Asia/Aden' => 10800,
2888       'Asia/Almaty' => 21600,
2889       'Asia/Amman' => 7200,
2890       'Asia/Anadyr' => 43200,
2891       'Asia/Aqtau' => 14400,
2892       'Asia/Aqtobe' => 18000,
2893       'Asia/Ashgabat' => 18000,
2894       'Asia/Ashkhabad' => 18000,
2895       'Asia/Baghdad' => 10800,
2896       'Asia/Bahrain' => 10800,
2897       'Asia/Baku' => 14400,
2898       'Asia/Bangkok' => 25200,
2899       'Asia/Beirut' => 7200,
2900       'Asia/Bishkek' => 18000,
2901       'Asia/Brunei' => 28800,
2902       'Asia/Calcutta' => 19800,
2903       'Asia/Choibalsan' => 32400,
2904       'Asia/Chongqing' => 28800,
2905       'Asia/Chungking' => 28800,
2906       'Asia/Colombo' => 21600,
2907       'Asia/Dacca' => 21600,
2908       'Asia/Damascus' => 7200,
2909       'Asia/Dhaka' => 21600,
2910       'Asia/Dili' => 32400,
2911       'Asia/Dubai' => 14400,
2912       'Asia/Dushanbe' => 18000,
2913       'Asia/Gaza' => 7200,
2914       'Asia/Harbin' => 28800,
2915       'Asia/Hong_Kong' => 28800,
2916       'Asia/Hovd' => 25200,
2917       'Asia/Irkutsk' => 28800,
2918       'Asia/Istanbul' => 7200,
2919       'Asia/Jakarta' => 25200,
2920       'Asia/Jayapura' => 32400,
2921       'Asia/Jerusalem' => 7200,
2922       'Asia/Kabul' => 16200,
2923       'Asia/Kamchatka' => 43200,
2924       'Asia/Karachi' => 18000,
2925       'Asia/Kashgar' => 28800,
2926       'Asia/Katmandu' => 20700,
2927       'Asia/Krasnoyarsk' => 25200,
2928       'Asia/Kuala_Lumpur' => 28800,
2929       'Asia/Kuching' => 28800,
2930       'Asia/Kuwait' => 10800,
2931       'Asia/Macao' => 28800,
2932       'Asia/Macau' => 0,
2933       'Asia/Magadan' => 39600,
2934       'Asia/Makassar' => 0,
2935       'Asia/Manila' => 28800,
2936       'Asia/Muscat' => 14400,
2937       'Asia/Nicosia' => 7200,
2938       'Asia/Novosibirsk' => 21600,
2939       'Asia/Omsk' => 21600,
2940       'Asia/Oral' => 0,
2941       'Asia/Phnom_Penh' => 25200,
2942       'Asia/Pontianak' => 25200,
2943       'Asia/Pyongyang' => 32400,
2944       'Asia/Qatar' => 10800,
2945       'Asia/Qyzylorda' => 0,
2946       'Asia/Rangoon' => 23400,
2947       'Asia/Riyadh' => 10800,
2948       'Asia/Saigon' => 25200,
2949       'Asia/Sakhalin' => 36000,
2950       'Asia/Samarkand' => 18000,
2951       'Asia/Seoul' => 32400,
2952       'Asia/Shanghai' => 28800,
2953       'Asia/Singapore' => 28800,
2954       'Asia/Taipei' => 28800,
2955       'Asia/Tashkent' => 18000,
2956       'Asia/Tbilisi' => 14400,
2957       'Asia/Tehran' => 12600,
2958       'Asia/Tel_Aviv' => 7200,
2959       'Asia/Thimbu' => 21600,
2960       'Asia/Thimphu' => 21600,
2961       'Asia/Tokyo' => 32400,
2962       'Asia/Ujung_Pandang' => 28800,
2963       'Asia/Ulaanbaatar' => 28800,
2964       'Asia/Ulan_Bator' => 28800,
2965       'Asia/Urumqi' => 28800,
2966       'Asia/Vientiane' => 25200,
2967       'Asia/Vladivostok' => 36000,
2968       'Asia/Yakutsk' => 32400,
2969       'Asia/Yekaterinburg' => 18000,
2970       'Asia/YerevanAtlantic/Azores' => 0,
2971       'Atlantic/Bermuda' => -14400,
2972       'Atlantic/Canary' => 0,
2973       'Atlantic/Cape_Verde' => -3600,
2974       'Atlantic/Faeroe' => 0,
2975       'Atlantic/Jan_Mayen' => 3600,
2976       'Atlantic/Madeira' => 0,
2977       'Atlantic/Reykjavik' => 0,
2978       'Atlantic/South_Georgia' => -7200,
2979       'Atlantic/St_Helena' => 0,
2980       'Atlantic/Stanley' => -14400,
2981       'Australia/ACT' => 36000,
2982       'Australia/Adelaide' => 34200,
2983       'Australia/Brisbane' => 36000,
2984       'Australia/Broken_Hill' => 34200,
2985       'Australia/Canberra' => 36000,
2986       'Australia/Currie' => 0,
2987       'Australia/Darwin' => 34200,
2988       'Australia/Hobart' => 36000,
2989       'Australia/LHI' => 37800,
2990       'Australia/Lindeman' => 36000,
2991       'Australia/Lord_Howe' => 37800,
2992       'Australia/Melbourne' => 36000,
2993       'Australia/NSW' => 36000,
2994       'Australia/North' => 34200,
2995       'Australia/Perth' => 28800,
2996       'Australia/Queensland' => 36000,
2997       'Australia/South' => 34200,
2998       'Australia/Sydney' => 36000,
2999       'Australia/Tasmania' => 36000,
3000       'Australia/Victoria' => 36000,
3001       'Australia/West' => 28800,
3002       'Australia/Yancowinna' => 34200,
3003       'Europe/Amsterdam' => 3600,
3004       'Europe/Andorra' => 3600,
3005       'Europe/Athens' => 7200,
3006       'Europe/Belfast' => 0,
3007       'Europe/Belgrade' => 3600,
3008       'Europe/Berlin' => 3600,
3009       'Europe/Bratislava' => 3600,
3010       'Europe/Brussels' => 3600,
3011       'Europe/Bucharest' => 7200,
3012       'Europe/Budapest' => 3600,
3013       'Europe/Chisinau' => 7200,
3014       'Europe/Copenhagen' => 3600,
3015       'Europe/Dublin' => 0,
3016       'Europe/Gibraltar' => 3600,
3017       'Europe/Guernsey' => 0,
3018       'Europe/Helsinki' => 7200,
3019       'Europe/Isle_of_Man' => 0,
3020       'Europe/Istanbul' => 7200,
3021       'Europe/Jersey' => 0,
3022       'Europe/Kaliningrad' => 7200,
3023       'Europe/Kiev' => 7200,
3024       'Europe/Lisbon' => 0,
3025       'Europe/Ljubljana' => 3600,
3026       'Europe/London' => 0,
3027       'Europe/Luxembourg' => 3600,
3028       'Europe/Madrid' => 3600,
3029       'Europe/Malta' => 3600,
3030       'Europe/Mariehamn' => 0,
3031       'Europe/Minsk' => 7200,
3032       'Europe/Monaco' => 3600,
3033       'Europe/Moscow' => 10800,
3034       'Europe/Nicosia' => 7200,
3035       'Europe/Oslo' => 3600,
3036       'Europe/Paris' => 3600,
3037       'Europe/Prague' => 3600,
3038       'Europe/Riga' => 7200,
3039       'Europe/Rome' => 3600,
3040       'Europe/Samara' => 14400,
3041       'Europe/San_Marino' => 3600,
3042       'Europe/Sarajevo' => 3600,
3043       'Europe/Simferopol' => 7200,
3044       'Europe/Skopje' => 3600,
3045       'Europe/Sofia' => 7200,
3046       'Europe/Stockholm' => 3600,
3047       'Europe/Tallinn' => 7200,
3048       'Europe/Tirane' => 3600,
3049       'Europe/Tiraspol' => 7200,
3050       'Europe/Uzhgorod' => 7200,
3051       'Europe/Vaduz' => 3600,
3052       'Europe/Vatican' => 3600,
3053       'Europe/Vienna' => 3600,
3054       'Europe/Vilnius' => 7200,
3055       'Europe/Volgograd' => 0,
3056       'Europe/Warsaw' => 3600,
3057       'Europe/Zagreb' => 3600,
3058       'Europe/Zaporozhye' => 7200,
3059       'Europe/Zurich' => 3600,
3060       'Indian/Antananarivo' => 10800,
3061       'Indian/Chagos' => 21600,
3062       'Indian/Christmas' => 25200,
3063       'Indian/Cocos' => 23400,
3064       'Indian/Comoro' => 10800,
3065       'Indian/Kerguelen' => 18000,
3066       'Indian/Mahe' => 14400,
3067       'Indian/Maldives' => 18000,
3068       'Indian/Mauritius' => 14400,
3069       'Indian/Mayotte' => 10800,
3070       'Indian/Reunion' => 14400,
3071       'Pacific/Apia' => -39600,
3072       'Pacific/Auckland' => 43200,
3073       'Pacific/Chatham' => 45900,
3074       'Pacific/Easter' => -21600,
3075       'Pacific/Efate' => 39600,
3076       'Pacific/Enderbury' => 46800,
3077       'Pacific/Fakaofo' => -36000,
3078       'Pacific/Fiji' => 43200,
3079       'Pacific/Funafuti' => 43200,
3080       'Pacific/Galapagos' => -21600,
3081       'Pacific/Gambier' => -32400,
3082       'Pacific/Guadalcanal' => 39600,
3083       'Pacific/Guam' => 36000,
3084       'Pacific/Honolulu' => -36000,
3085       'Pacific/Johnston' => -36000,
3086       'Pacific/Kiritimati' => 50400,
3087       'Pacific/Kosrae' => 39600,
3088       'Pacific/Kwajalein' => 43200,
3089       'Pacific/Majuro' => 43200,
3090       'Pacific/Marquesas' => -34200,
3091       'Pacific/Midway' => -39600,
3092       'Pacific/Nauru' => 43200,
3093       'Pacific/Niue' => -39600,
3094       'Pacific/Norfolk' => 41400,
3095       'Pacific/Noumea' => 39600,
3096       'Pacific/Pago_Pago' => -39600,
3097       'Pacific/Palau' => 32400,
3098       'Pacific/Pitcairn' => -28800,
3099       'Pacific/Ponape' => 39600,
3100       'Pacific/Port_Moresby' => 36000,
3101       'Pacific/Rarotonga' => -36000,
3102       'Pacific/Saipan' => 36000,
3103       'Pacific/Samoa' => -39600,
3104       'Pacific/Tahiti' => -36000,
3105       'Pacific/Tarawa' => 43200,
3106       'Pacific/Tongatapu' => 46800,
3107       'Pacific/Truk' => 36000,
3108       'Pacific/Wake' => 43200,
3109       'Pacific/Wallis' => 43200,
3110       'Pacific/Yap' => 36000 );          
3112   $dst_timezones = array (  
3113       'America/Adak' => 1,
3114       'America/Atka' => 1,
3115       'America/Anchorage' => 1,
3116       'America/Juneau' => 1,
3117       'America/Nome' => 1,
3118       'America/Yakutat' => 1,
3119       'America/Dawson' => 1,
3120       'America/Ensenada' => 1,
3121       'America/Los_Angeles' => 1,
3122       'America/Tijuana' => 1,
3123       'America/Vancouver' => 1,
3124       'America/Whitehorse' => 1,
3125       'America/Boise' => 1,
3126       'America/Cambridge_Bay' => 1,
3127       'America/Chihuahua' => 1,
3128       'America/Denver' => 1,
3129       'America/Edmonton' => 1,
3130       'America/Inuvik' => 1,
3131       'America/Mazatlan' => 1,
3132       'America/Shiprock' => 1,
3133       'America/Yellowknife' => 1,
3134       'America/Cancun' => 1,
3135       'America/Chicago' => 1,
3136       'America/Menominee' => 1,
3137       'America/Merida' => 1,
3138       'America/Monterrey' => 1,
3139       'America/North_Dakota/Center' => 1,
3140       'America/Rainy_River' => 1,
3141       'America/Rankin_Inlet' => 1,
3142       'America/Winnipeg' => 1,
3143       'Pacific/Easter' => 1,
3144       'America/Detroit' => 1,
3145       'America/Grand_Turk' => 1,
3146       'America/Havana' => 1,
3147       'America/Iqaluit' => 1,
3148       'America/Kentucky/Louisville' => 1,
3149       'America/Kentucky/Monticello' => 1,
3150       'America/Louisville' => 1,
3151       'America/Montreal' => 1,
3152       'America/Nassau' => 1,
3153       'America/New_York' => 1,
3154       'America/Nipigon' => 1,
3155       'America/Pangnirtung' => 1,
3156       'America/Thunder_Bay' => 1,
3157       'America/Asuncion' => 1,
3158       'America/Cuiaba' => 1,
3159       'America/Glace_Bay' => 1,
3160       'America/Goose_Bay' => 1,
3161       'America/Halifax' => 1,
3162       'America/Santiago' => 1,
3163       'Antarctica/Palmer' => 1,
3164       'Atlantic/Bermuda' => 1,
3165       'Atlantic/Stanley' => 1,
3166       'America/St_Johns' => 1,
3167       'America/Araguaina' => 1,
3168       'America/Fortaleza' => 1,
3169       'America/Godthab' => 1,
3170       'America/Maceio' => 1,
3171       'America/Miquelon' => 1,
3172       'America/Recife' => 1,
3173       'America/Sao_Paulo' => 1,
3174       'America/Scoresbysund' => 1,
3175       'Atlantic/Canary' => 1,
3176       'Atlantic/Faeroe' => 1,
3177       'Atlantic/Madeira' => 1,
3178       'Europe/Belfast' => 1,
3179       'Europe/Dublin' => 1,
3180       'Europe/Lisbon' => 1,
3181       'Europe/London' => 1,
3182       'Africa/Ceuta' => 1,
3183       'Africa/Windhoek' => 1,
3184       'Atlantic/Jan_Mayen' => 1,
3185       'Europe/Amsterdam' => 1,
3186       'Europe/Andorra' => 1,
3187       'Europe/Belgrade' => 1,
3188       'Europe/Berlin' => 1,
3189       'Europe/Bratislava' => 1,
3190       'Europe/Brussels' => 1,
3191       'Europe/Budapest' => 1,
3192       'Europe/Copenhagen' => 1,
3193       'Europe/Gibraltar' => 1,
3194       'Europe/Ljubljana' => 1,
3195       'Europe/Luxembourg' => 1,
3196       'Europe/Madrid' => 1,
3197       'Europe/Malta' => 1,
3198       'Europe/Monaco' => 1,
3199       'Europe/Oslo' => 1,
3200       'Europe/Paris' => 1,
3201       'Europe/Prague' => 1,
3202       'Europe/Rome' => 1,
3203       'Europe/San_Marino' => 1,
3204       'Europe/Sarajevo' => 1,
3205       'Europe/Skopje' => 1,
3206       'Europe/Stockholm' => 1,
3207       'Europe/Tirane' => 1,
3208       'Europe/Vaduz' => 1,
3209       'Europe/Vatican' => 1,
3210       'Europe/Vienna' => 1,
3211       'Europe/Warsaw' => 1,
3212       'Europe/Zagreb' => 1,
3213       'Europe/Zurich' => 1,
3214       'Africa/Cairo' => 1,
3215       'Asia/Amman' => 1,
3216       'Asia/Beirut' => 1,
3217       'Asia/Damascus' => 1,
3218       'Asia/Gaza' => 1,
3219       'Asia/Istanbul' => 1,
3220       'Asia/Jerusalem' => 1,
3221       'Asia/Nicosia' => 1,
3222       'Asia/Tel_Aviv' => 1,
3223       'Europe/Athens' => 1,
3224       'Europe/Bucharest' => 1,
3225       'Europe/Chisinau' => 1,
3226       'Europe/Helsinki' => 1,
3227       'Europe/Istanbul' => 1,
3228       'Europe/Kaliningrad' => 1,
3229       'Europe/Kiev' => 1,
3230       'Europe/Minsk' => 1,
3231       'Europe/Nicosia' => 1,
3232       'Europe/Riga' => 1,
3233       'Europe/Simferopol' => 1,
3234       'Europe/Sofia' => 1,
3235       'Europe/Tiraspol' => 1,
3236       'Europe/Uzhgorod' => 1,
3237       'Europe/Zaporozhye' => 1,
3238       'Asia/Baghdad' => 1,
3239       'Europe/Moscow' => 1,
3240       'Asia/Tehran' => 1,
3241       'Asia/Aqtau' => 1,
3242       'Asia/Baku' => 1,
3243       'Asia/Tbilisi' => 1,
3244       'Europe/Samara' => 1,
3245       'Asia/Aqtobe' => 1,
3246       'Asia/Bishkek' => 1,
3247       'Asia/Yekaterinburg' => 1,
3248       'Asia/Almaty' => 1,
3249       'Asia/Novosibirsk' => 1,
3250       'Asia/Omsk' => 1,
3251       'Asia/Krasnoyarsk' => 1,
3252       'Asia/Irkutsk' => 1,
3253       'Asia/Yakutsk' => 1,
3254       'Australia/Adelaide' => 1,
3255       'Australia/Broken_Hill' => 1,
3256       'Australia/South' => 1,
3257       'Australia/Yancowinna' => 1,
3258       'Asia/Sakhalin' => 1,
3259       'Asia/Vladivostok' => 1,
3260       'Australia/ACT' => 1,
3261       'Australia/Canberra' => 1,
3262       'Australia/Hobart' => 1,
3263       'Australia/Melbourne' => 1,
3264       'Australia/NSW' => 1,
3265       'Australia/Sydney' => 1,
3266       'Australia/Tasmania' => 1,
3267       'Australia/Victoria' => 1,
3268       'Australia/LHI' => 1,
3269       'Australia/Lord_Howe' => 1,
3270       'Asia/Magadan' => 1,
3271       'Antarctica/McMurdo' => 1,
3272       'Antarctica/South_Pole' => 1,
3273       'Asia/Anadyr' => 1,
3274       'Asia/Kamchatka' => 1,
3275       'Pacific/Auckland' => 1,
3276       'Pacific/Chatham' => 1,
3277       );  
3278   return(array("TIMEZONES" => $timezones, "DST_ZONES" => $dst_timezones));
3280 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3281 ?>