Code

Udpated message handling
[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 DEBUGLEVEL is set, we're in web mode, use textual output in
1015      the other case... */
1016   if (isset($_SESSION['DEBUGLEVEL'])){
1017     if($string !== NULL){
1018       if (preg_match("/"._("LDAP error:")."/", $string)){
1019         $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.");
1020       } else {
1021         if (!preg_match('/[.!?]$/', $string)){
1022           $string.= ".";
1023         }
1024         $string= preg_replace('/<br>/', ' ', $string);
1025         $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1026       }
1027       msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1028       return;
1029     }else{
1030       return;
1031     }
1033   } else {
1034     echo "Error: $string\n";
1035   }
1039 function gen_locked_message($user, $dn)
1041   global $plug, $config;
1043   $_SESSION['dn']= $dn;
1044   $ldap= $config->get_ldap_link();
1045   $ldap->cat ($user, array('uid', 'cn'));
1046   $attrs= $ldap->fetch();
1048   /* Stop if we have no user here... */
1049   if (count($attrs)){
1050     $uid= $attrs["uid"][0];
1051     $cn= $attrs["cn"][0];
1052   } else {
1053     $uid= $attrs["uid"][0];
1054     $cn= $attrs["cn"][0];
1055   }
1056   
1057   $remove= false;
1059   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1060   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1061     $_SESSION['LOCK_VARS_USED']  =array();
1062     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1064       if(empty($name)) continue;
1065       foreach($_POST as $Pname => $Pvalue){
1066         if(preg_match($name,$Pname)){
1067           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1068         }
1069       }
1071       foreach($_GET as $Pname => $Pvalue){
1072         if(preg_match($name,$Pname)){
1073           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1074         }
1075       }
1076     }
1077     $_SESSION['LOCK_VARS_TO_USE'] =array();
1078   }
1080   /* Prepare and show template */
1081   $smarty= get_smarty();
1082   $smarty->assign ("dn", $dn);
1083   if ($remove){
1084     $smarty->assign ("action", _("Continue anyway"));
1085   } else {
1086     $smarty->assign ("action", _("Edit anyway"));
1087   }
1088   $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>"));
1090   return ($smarty->fetch (get_template_path('islocked.tpl')));
1094 function to_string ($value)
1096   /* If this is an array, generate a text blob */
1097   if (is_array($value)){
1098     $ret= "";
1099     foreach ($value as $line){
1100       $ret.= $line."<br>\n";
1101     }
1102     return ($ret);
1103   } else {
1104     return ($value);
1105   }
1109 function get_printer_list($cups_server)
1111   global $config;
1112   $res = array();
1113   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'));
1114   foreach($data as $attrs ){
1115     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1116   }
1117   return $res;
1121 function sess_del ($var)
1123   /* New style */
1124   unset ($_SESSION[$var]);
1126   /* ... work around, since the first one
1127      doesn't seem to work all the time */
1128   session_unregister ($var);
1132 function show_errors($message)
1134   $complete= "";
1136   /* Assemble the message array to a plain string */
1137   foreach ($message as $error){
1138     if ($complete == ""){
1139       $complete= $error;
1140     } else {
1141       $complete= "$error<br>$complete";
1142     }
1143   }
1145   /* Fill ERROR variable with nice error dialog */
1146   print_red($complete);
1150 function show_ldap_error($message, $addon= "")
1152   if (!preg_match("/Success/i", $message)){
1153     if ($addon == ""){
1154       msg_dialog::display(_("LDAP error:"),$message,ERROR_DIALOG);
1155       #print_red (_("LDAP error:")." $message");
1156     } else {
1157       msg_dialog::display(sprintf(_("LDAP error in plugin '%s':"),"<i>".$addon."</i>"),$message,ERROR_DIALOG);
1158       #print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1159     }
1160     return TRUE;
1161   } else {
1162     return FALSE;
1163   }
1167 function rewrite($s)
1169   global $REWRITE;
1171   foreach ($REWRITE as $key => $val){
1172     $s= preg_replace("/$key/", "$val", $s);
1173   }
1175   return ($s);
1179 function dn2base($dn)
1181   global $config;
1183   if (get_people_ou() != ""){
1184     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1185   }
1186   if (get_groups_ou() != ""){
1187     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1188   }
1189   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1191   return ($base);
1196 function check_command($cmdline)
1198   $cmd= preg_replace("/ .*$/", "", $cmdline);
1200   /* Check if command exists in filesystem */
1201   if (!file_exists($cmd)){
1202     return (FALSE);
1203   }
1205   /* Check if command is executable */
1206   if (!is_executable($cmd)){
1207     return (FALSE);
1208   }
1210   return (TRUE);
1214 function print_header($image, $headline, $info= "")
1216   $display= "<div class=\"plugtop\">\n";
1217   $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";
1218   $display.= "</div>\n";
1220   if ($info != ""){
1221     $display.= "<div class=\"pluginfo\">\n";
1222     $display.= "$info";
1223     $display.= "</div>\n";
1224   } else {
1225     $display.= "<div style=\"height:5px;\">\n";
1226     $display.= "&nbsp;";
1227     $display.= "</div>\n";
1228   }
1229 #  if (isset($_SESSION['errors'])){
1230 #    $display.= $_SESSION['errors'];
1231 #  }
1233   return ($display);
1237 function register_global($name, $object)
1239   $_SESSION[$name]= $object;
1243 function is_global($name)
1245   return isset($_SESSION[$name]);
1249 function &get_global($name)
1251   return $_SESSION[$name];
1255 function range_selector($dcnt,$start,$range=25,$post_var=false)
1258   /* Entries shown left and right from the selected entry */
1259   $max_entries= 10;
1261   /* Initialize and take care that max_entries is even */
1262   $output="";
1263   if ($max_entries & 1){
1264     $max_entries++;
1265   }
1267   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1268     $range= $_POST[$post_var];
1269   }
1271   /* Prevent output to start or end out of range */
1272   if ($start < 0 ){
1273     $start= 0 ;
1274   }
1275   if ($start >= $dcnt){
1276     $start= $range * (int)(($dcnt / $range) + 0.5);
1277   }
1279   $numpages= (($dcnt / $range));
1280   if(((int)($numpages))!=($numpages)){
1281     $numpages = (int)$numpages + 1;
1282   }
1283   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1284     return ("");
1285   }
1286   $ppage= (int)(($start / $range) + 0.5);
1289   /* Align selected page to +/- max_entries/2 */
1290   $begin= $ppage - $max_entries/2;
1291   $end= $ppage + $max_entries/2;
1293   /* Adjust begin/end, so that the selected value is somewhere in
1294      the middle and the size is max_entries if possible */
1295   if ($begin < 0){
1296     $end-= $begin + 1;
1297     $begin= 0;
1298   }
1299   if ($end > $numpages) {
1300     $end= $numpages;
1301   }
1302   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1303     $begin= $end - $max_entries;
1304   }
1306   if($post_var){
1307     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1308       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1309   }else{
1310     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1311   }
1313   /* Draw decrement */
1314   if ($start > 0 ) {
1315     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1316       (($start-$range))."\">".
1317       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1318   }
1320   /* Draw pages */
1321   for ($i= $begin; $i < $end; $i++) {
1322     if ($ppage == $i){
1323       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1324         validate($_GET['plug'])."&amp;start=".
1325         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1326     } else {
1327       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1328         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1329     }
1330   }
1332   /* Draw increment */
1333   if($start < ($dcnt-$range)) {
1334     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1335       (($start+($range)))."\">".
1336       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1337   }
1339   if(($post_var)&&($numpages)){
1340     $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()'>";
1341     foreach(array(20,50,100,200,"all") as $num){
1342       if($num == "all"){
1343         $var = 10000;
1344       }else{
1345         $var = $num;
1346       }
1347       if($var == $range){
1348         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1349       }else{  
1350         $output.="\n<option value='".$var."'>".$num."</option>";
1351       }
1352     }
1353     $output.=  "</select></td></tr></table></div>";
1354   }else{
1355     $output.= "</div>";
1356   }
1358   return($output);
1362 function apply_filter()
1364   $apply= "";
1366   $apply= ''.
1367     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1368     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1370   return ($apply);
1374 function back_to_main()
1376   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1377     _("Back").'"></p><input type="hidden" name="ignore">';
1379   return ($string);
1383 function normalize_netmask($netmask)
1385   /* Check for notation of netmask */
1386   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1387     $num= (int)($netmask);
1388     $netmask= "";
1390     for ($byte= 0; $byte<4; $byte++){
1391       $result=0;
1393       for ($i= 7; $i>=0; $i--){
1394         if ($num-- > 0){
1395           $result+= pow(2,$i);
1396         }
1397       }
1399       $netmask.= $result.".";
1400     }
1402     return (preg_replace('/\.$/', '', $netmask));
1403   }
1405   return ($netmask);
1409 function netmask_to_bits($netmask)
1411   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1412   $res= 0;
1414   for ($n= 0; $n<4; $n++){
1415     $start= 255;
1416     $name= "nm$n";
1418     for ($i= 0; $i<8; $i++){
1419       if ($start == (int)($$name)){
1420         $res+= 8 - $i;
1421         break;
1422       }
1423       $start-= pow(2,$i);
1424     }
1425   }
1427   return ($res);
1431 function recurse($rule, $variables)
1433   $result= array();
1435   if (!count($variables)){
1436     return array($rule);
1437   }
1439   reset($variables);
1440   $key= key($variables);
1441   $val= current($variables);
1442   unset ($variables[$key]);
1444   foreach($val as $possibility){
1445     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1446     $result= array_merge($result, recurse($nrule, $variables));
1447   }
1449   return ($result);
1453 function expand_id($rule, $attributes)
1455   /* Check for id rule */
1456   if(preg_match('/^id(:|#)\d+$/',$rule)){
1457     return (array("\{$rule}"));
1458   }
1460   /* Check for clean attribute */
1461   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1462     $rule= preg_replace('/^%/', '', $rule);
1463     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1464     return (array($val));
1465   }
1467   /* Check for attribute with parameters */
1468   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1469     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1470     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1471     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1472     $start= preg_replace ('/-.*$/', '', $param);
1473     $stop = preg_replace ('/^[^-]+-/', '', $param);
1475     /* Assemble results */
1476     $result= array();
1477     for ($i= $start; $i<= $stop; $i++){
1478       $result[]= substr($val, 0, $i);
1479     }
1480     return ($result);
1481   }
1483   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1484   return (array($rule));
1488 function gen_uids($rule, $attributes)
1490   global $config;
1492   /* Search for keys and fill the variables array with all 
1493      possible values for that key. */
1494   $part= "";
1495   $trigger= false;
1496   $stripped= "";
1497   $variables= array();
1499   for ($pos= 0; $pos < strlen($rule); $pos++){
1501     if ($rule[$pos] == "{" ){
1502       $trigger= true;
1503       $part= "";
1504       continue;
1505     }
1507     if ($rule[$pos] == "}" ){
1508       $variables[$pos]= expand_id($part, $attributes);
1509       $stripped.= "{".$pos."}";
1510       $trigger= false;
1511       continue;
1512     }
1514     if ($trigger){
1515       $part.= $rule[$pos];
1516     } else {
1517       $stripped.= $rule[$pos];
1518     }
1519   }
1521   /* Recurse through all possible combinations */
1522   $proposed= recurse($stripped, $variables);
1524   /* Get list of used ID's */
1525   $used= array();
1526   $ldap= $config->get_ldap_link();
1527   $ldap->cd($config->current['BASE']);
1528   $ldap->search('(uid=*)');
1530   while($attrs= $ldap->fetch()){
1531     $used[]= $attrs['uid'][0];
1532   }
1534   /* Remove used uids and watch out for id tags */
1535   $ret= array();
1536   foreach($proposed as $uid){
1538     /* Check for id tag and modify uid if needed */
1539     if(preg_match('/\{id:\d+}/',$uid)){
1540       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1542       for ($i= 0; $i < pow(10,$size); $i++){
1543         $number= sprintf("%0".$size."d", $i);
1544         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1545         if (!in_array($res, $used)){
1546           $uid= $res;
1547           break;
1548         }
1549       }
1550     }
1552   if(preg_match('/\{id#\d+}/',$uid)){
1553     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1555     while (true){
1556       mt_srand((double) microtime()*1000000);
1557       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1558       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1559       if (!in_array($res, $used)){
1560         $uid= $res;
1561         break;
1562       }
1563     }
1564   }
1566 /* Don't assign used ones */
1567 if (!in_array($uid, $used)){
1568   $ret[]= $uid;
1572 return(array_unique($ret));
1576 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1577    Need to convert... */
1578 function to_byte($value) {
1579   $value= strtolower(trim($value));
1581   if(!is_numeric(substr($value, -1))) {
1583     switch(substr($value, -1)) {
1584       case 'g':
1585         $mult= 1073741824;
1586         break;
1587       case 'm':
1588         $mult= 1048576;
1589         break;
1590       case 'k':
1591         $mult= 1024;
1592         break;
1593     }
1595     return ($mult * (int)substr($value, 0, -1));
1596   } else {
1597     return $value;
1598   }
1602 function in_array_ics($value, $items)
1604   if (!is_array($items)){
1605     return (FALSE);
1606   }
1608   foreach ($items as $item){
1609     if (strcasecmp($item, $value) == 0) {
1610       return (TRUE);
1611     }
1612   }
1614   return (FALSE);
1615
1618 function generate_alphabet($count= 10)
1620   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1621   $alphabet= "";
1622   $c= 0;
1624   /* Fill cells with charaters */
1625   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1626     if ($c == 0){
1627       $alphabet.= "<tr>";
1628     }
1630     $ch = mb_substr($characters, $i, 1, "UTF8");
1631     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1632       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1634     if ($c++ == $count){
1635       $alphabet.= "</tr>";
1636       $c= 0;
1637     }
1638   }
1640   /* Fill remaining cells */
1641   while ($c++ <= $count){
1642     $alphabet.= "<td>&nbsp;</td>";
1643   }
1645   return ($alphabet);
1649 function validate($string)
1651   return (strip_tags(preg_replace('/\0/', '', $string)));
1654 function get_gosa_version()
1656   global $svn_revision, $svn_path;
1658   /* Extract informations */
1659   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1661   /* Release or development? */
1662   if (preg_match('%/gosa/trunk/%', $svn_path)){
1663     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1664   } else {
1665     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1666     return (sprintf(_("GOsa $release"), $revision));
1667   }
1671 function rmdirRecursive($path, $followLinks=false) {
1672   $dir= opendir($path);
1673   while($entry= readdir($dir)) {
1674     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1675       unlink($path."/".$entry);
1676     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1677       rmdirRecursive($path."/".$entry);
1678     }
1679   }
1680   closedir($dir);
1681   return rmdir($path);
1684 function scan_directory($path,$sort_desc=false)
1686   $ret = false;
1688   /* is this a dir ? */
1689   if(is_dir($path)) {
1691     /* is this path a readable one */
1692     if(is_readable($path)){
1694       /* Get contents and write it into an array */   
1695       $ret = array();    
1697       $dir = opendir($path);
1699       /* Is this a correct result ?*/
1700       if($dir){
1701         while($fp = readdir($dir))
1702           $ret[]= $fp;
1703       }
1704     }
1705   }
1706   /* Sort array ascending , like scandir */
1707   sort($ret);
1709   /* Sort descending if parameter is sort_desc is set */
1710   if($sort_desc) {
1711     $ret = array_reverse($ret);
1712   }
1714   return($ret);
1717 function clean_smarty_compile_dir($directory)
1719   global $svn_revision;
1721   if(is_dir($directory) && is_readable($directory)) {
1722     // Set revision filename to REVISION
1723     $revision_file= $directory."/REVISION";
1725     /* Is there a stamp containing the current revision? */
1726     if(!file_exists($revision_file)) {
1727       // create revision file
1728       create_revision($revision_file, $svn_revision);
1729     } else {
1730 # check for "$config->...['CONFIG']/revision" and the
1731 # contents should match the revision number
1732       if(!compare_revision($revision_file, $svn_revision)){
1733         // If revision differs, clean compile directory
1734         foreach(scan_directory($directory) as $file) {
1735           if(($file==".")||($file=="..")) continue;
1736           if( is_file($directory."/".$file) &&
1737               is_writable($directory."/".$file)) {
1738             // delete file
1739             if(!unlink($directory."/".$file)) {
1740               print_red("File ".$directory."/".$file." could not be deleted.");
1741               // This should never be reached
1742             }
1743           } elseif(is_dir($directory."/".$file) &&
1744               is_writable($directory."/".$file)) {
1745             // Just recursively delete it
1746             rmdirRecursive($directory."/".$file);
1747           }
1748         }
1749         // We should now create a fresh revision file
1750         clean_smarty_compile_dir($directory);
1751       } else {
1752         // Revision matches, nothing to do
1753       }
1754     }
1755   } else {
1756     // Smarty compile dir is not accessible
1757     // (Smarty will warn about this)
1758   }
1761 function create_revision($revision_file, $revision)
1763   $result= false;
1765   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1766     if($fh= fopen($revision_file, "w")) {
1767       if(fwrite($fh, $revision)) {
1768         $result= true;
1769       }
1770     }
1771     fclose($fh);
1772   } else {
1773     print_red("Can not write to revision file");
1774   }
1776   return $result;
1779 function compare_revision($revision_file, $revision)
1781   // false means revision differs
1782   $result= false;
1784   if(file_exists($revision_file) && is_readable($revision_file)) {
1785     // Open file
1786     if($fh= fopen($revision_file, "r")) {
1787       // Compare File contents with current revision
1788       if($revision == fread($fh, filesize($revision_file))) {
1789         $result= true;
1790       }
1791     } else {
1792       print_red("Can not open revision file");
1793     }
1794     // Close file
1795     fclose($fh);
1796   }
1798   return $result;
1801 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1803   $str = ""; // Our return value will be saved in this var
1805   $color  = dechex($percentage+150);
1806   $color2 = dechex(150 - $percentage);
1807   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1809   $progress = (int)(($percentage /100)*$width);
1811   /* Abort printing out percentage, if divs are to small */
1814   /* If theres a better solution for this, use it... */
1815   $str = "
1816     <div style=\" width:".($width)."px; 
1817     height:".($height)."px;
1818   background-color:#000000;
1819 padding:1px;\">
1821           <div style=\" width:".($width)."px;
1822         background-color:#$bgcolor;
1823 height:".($height)."px;\">
1825          <div style=\" width:".$progress."px;
1826 height:".$height."px;
1827        background-color:#".$color2.$color2.$color."; \">";
1830        if(($height >10)&&($showvalue)){
1831          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1832            <b>".$percentage."%</b>
1833            </font>";
1834        }
1836        $str.= "</div></div></div>";
1838        return($str);
1842 function array_key_ics($ikey, $items)
1844   /* Gather keys, make them lowercase */
1845   $tmp= array();
1846   foreach ($items as $key => $value){
1847     $tmp[strtolower($key)]= $key;
1848   }
1850   if (isset($tmp[strtolower($ikey)])){
1851     return($tmp[strtolower($ikey)]);
1852   }
1854   return ("");
1858 function array_differs($src, $dst)
1860   /* If the count is differing, the arrays differ */
1861   if (count ($src) != count ($dst)){
1862     return (TRUE);
1863   }
1865   /* So the count is the same - lets check the contents */
1866   $differs= FALSE;
1867   foreach($src as $value){
1868     if (!in_array($value, $dst)){
1869       $differs= TRUE;
1870     }
1871   }
1873   return ($differs);
1877 function saveFilter($a_filter, $values)
1879   if (isset($_POST['regexit'])){
1880     $a_filter["regex"]= $_POST['regexit'];
1882     foreach($values as $type){
1883       if (isset($_POST[$type])) {
1884         $a_filter[$type]= "checked";
1885       } else {
1886         $a_filter[$type]= "";
1887       }
1888     }
1889   }
1891   /* React on alphabet links if needed */
1892   if (isset($_GET['search'])){
1893     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
1894     if ($s == "**"){
1895       $s= "*";
1896     }
1897     $a_filter['regex']= $s;
1898   }
1900   return ($a_filter);
1904 /* Escape all preg_* relevant characters */
1905 function normalizePreg($input)
1907   return (addcslashes($input, '[]()|/.*+-'));
1911 /* Escape all LDAP filter relevant characters */
1912 function normalizeLdap($input)
1914   return (addcslashes($input, '()|'));
1918 /* Resturns the difference between to microtime() results in float  */
1919 function get_MicroTimeDiff($start , $stop)
1921   $a = split("\ ",$start);
1922   $b = split("\ ",$stop);
1924   $secs = $b[1] - $a[1];
1925   $msecs= $b[0] - $a[0]; 
1927   $ret = (float) ($secs+ $msecs);
1928   return($ret);
1932 /* Check if the given department name is valid */
1933 function is_department_name_reserved($name,$base)
1935   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
1936                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
1937                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
1938   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
1940   /* Check if name is one of the reserved names */
1941   if(in_array_ics($name,$reservedName)) {
1942     return(true);
1943   }
1945   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
1946   foreach($follwedNames as $key => $names){
1947     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
1948       return(true);
1949     }
1950   }
1951   return(false);
1955 function get_base_dir()
1957   global $BASE_DIR;
1959   return $BASE_DIR;
1963 function obj_is_readable($dn, $object, $attribute)
1965   global $ui;
1967   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
1971 function obj_is_writable($dn, $object, $attribute)
1973   global $ui;
1975   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
1979 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
1981   /* Initialize variables */
1982   $ret  = array("count" => 0);  // Set count to 0
1983   $next = true;                 // if false, then skip next loops and return
1984   $cnt  = 0;                    // Current number of loops
1985   $max  = 100;                  // Just for security, prevent looops
1986   $ldap = NULL;                 // To check if created result a valid
1987   $keep = "";                   // save last failed parse string
1989   /* Check each parsed dn in ldap ? */
1990   if($config!==NULL && $verify_in_ldap){
1991     $ldap = $config->get_ldap_link();
1992   }
1994   /* Lets start */
1995   $called = false;
1996   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
1998     $cnt ++;
1999     if(!preg_match("/,/",$dn)){
2000       $next = false;
2001     }
2002     $object = preg_replace("/[,].*$/","",$dn);
2003     $dn     = preg_replace("/^[^,]+,/","",$dn);
2005     $called = true;
2007     /* Check if current dn is valid */
2008     if($ldap!==NULL){
2009       $ldap->cd($dn);
2010       $ldap->cat($dn,array("dn"));
2011       if($ldap->count()){
2012         $ret[]  = $keep.$object;
2013         $keep   = "";
2014       }else{
2015         $keep  .= $object.",";
2016       }
2017     }else{
2018       $ret[]  = $keep.$object;
2019       $keep   = "";
2020     }
2021   }
2023   /* No dn was posted */
2024   if($cnt == 0 && !empty($dn)){
2025     $ret[] = $dn;
2026   }
2028   /* Append the rest */
2029   $test = $keep.$dn;
2030   if($called && !empty($test)){
2031     $ret[] = $keep.$dn;
2032   }
2033   $ret['count'] = count($ret) - 1;
2035   return($ret);
2038 /* Add "str_split" if this function is missing.
2039  * This function is only available in PHP5
2040  */
2041   if(!function_exists("str_split")){
2042     function str_split($str,$length =1)
2043     {
2044       if($length < 1 ) $length =1;
2046       $ret = array();
2047       for($i = 0 ; $i < strlen($str); $i = $i +$length){
2048         $ret[] = substr($str,$i ,$length);
2049       }
2050       return($ret);
2051     }
2052   }
2055 function get_base_from_hook($dn, $attrib)
2057   global $config;
2059   if (isset($config->current['BASE_HOOK'])){
2060     
2061     /* Call hook script - if present */
2062     $command= $config->current['BASE_HOOK'];
2064     if ($command != ""){
2065       $command.= " '$dn' $attrib";
2066       if (check_command($command)){
2067         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2068         exec($command, $output);
2069         if (preg_match("/^[0-9]+$/", $output[0])){
2070           return ($output[0]);
2071         } else {
2072           print_red(_("Warning - base_hook is not available. Using default base."));
2073           return ($config->current['UIDBASE']);
2074         }
2075       } else {
2076         print_red(_("Warning - base_hook is not available. Using default base."));
2077         return ($config->current['UIDBASE']);
2078       }
2080     } else {
2082       print_red(_("Warning - no base_hook defined. Using default base."));
2083       return ($config->current['UIDBASE']);
2085     }
2086   }
2089 /* Schema validation functions */
2091 function check_schema_version($class, $version)
2093   return preg_match("/\(v$version\)/", $class['DESC']);
2096 function check_schema($cfg,$rfc2307bis = FALSE)
2098   $messages= array();
2100   /* Get objectclasses */
2101   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2102   $objectclasses = $ldap->get_objectclasses();
2103   if(count($objectclasses) == 0){
2104     print_red(_("Can't get schema information from server. No schema check possible!"));
2105   }
2107   /* This is the default block used for each entry.
2108    *  to avoid unset indexes.
2109    */
2110   $def_check = array("REQUIRED_VERSION" => "0",
2111       "SCHEMA_FILES"     => array(),
2112       "CLASSES_REQUIRED" => array(),
2113       "STATUS"           => FALSE,
2114       "IS_MUST_HAVE"     => FALSE,
2115       "MSG"              => "",
2116       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2118   /* The gosa base schema */
2119   $checks['gosaObject'] = $def_check;
2120   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2121   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2122   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2123   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2125   /* GOsa Account class */
2126   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2127   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2128   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2129   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2130   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2132   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2133   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2134   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2135   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2136   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2137   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2139   /* Some other checks */
2140   foreach(array(
2141         "gosaCacheEntry"        => array("version" => "2.4"),
2142         "gosaDepartment"        => array("version" => "2.4"),
2143         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2144         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2145         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2146         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2147         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2148         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2149         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2150         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2151         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2152         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2153         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2154         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2155         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2156         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2157         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2158         "goLdapServer"          => array("version" => "2.4"),
2159         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2160         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2161         "goKrbServer"           => array("version" => "2.4"),
2162         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2163         ) as $name => $values){
2165           $checks[$name] = $def_check;
2166           if(isset($values['version'])){
2167             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2168           }
2169           if(isset($values['file'])){
2170             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2171           }
2172           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2173         }
2174   foreach($checks as $name => $value){
2175     foreach($value['CLASSES_REQUIRED'] as $class){
2177       if(!isset($objectclasses[$name])){
2178         $checks[$name]['STATUS'] = FALSE;
2179         if($value['IS_MUST_HAVE']){
2180           $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2181         }else{
2182           $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2183         }
2184       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2185         $checks[$name]['STATUS'] = FALSE;
2187         if($value['IS_MUST_HAVE']){
2188           $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2189         }else{
2190           $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2191         }
2192       }else{
2193         $checks[$name]['STATUS'] = TRUE;
2194         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2195       }
2196     }
2197   }
2199   $tmp = $objectclasses;
2201   /* The gosa base schema */
2202   $checks['posixGroup'] = $def_check;
2203   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2204   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2205   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2206   $checks['posixGroup']['STATUS']           = TRUE;
2207   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2208   $checks['posixGroup']['MSG']              = "";
2209   $checks['posixGroup']['INFO']             = "";
2211   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2212   if(isset($tmp['posixGroup'])){
2214     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2215       $checks['posixGroup']['STATUS']           = FALSE;
2216       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2217       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2218     }
2219     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2220       $checks['posixGroup']['STATUS']           = FALSE;
2221       $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2222       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2223     }
2224   }
2226   return($checks);
2230 function prepare4mailbody($string)
2232   $string = html_entity_decode($string);
2234   $from = array(
2235                 "/%/",
2236                 "/ /",
2237                 "/\n/",
2238                 "/\r/",
2239                 "/!/",
2240                 "/#/",
2241                 "/\*/",
2242                 "/\//",
2243                 "/</",
2244                 "/>/",
2245                 "/\?/",
2246                 "/\"/");
2248   $to = array(
2249                 "%25",
2250                 "%20",
2251                 "%0A",
2252                 "%0D",
2253                 "%21",
2254                 "%23",
2255                 "%2A",
2256                 "%2F",
2257                 "%3C",
2258                 "%3E",
2259                 "%3F",
2260                 "%22");
2262   $string = preg_replace($from,$to,$string);
2264   return($string);
2270 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2272   $tmp = array(
2273         "de_DE" => "German",
2274         "fr_FR" => "French",
2275         "it_IT" => "Italian",
2276         "es_ES" => "Spanish",
2277         "en_US" => "English",
2278         "nl_NL" => "Dutch",
2279         "pl_PL" => "Polish",
2280         "sv_SE" => "Swedish",
2281         "zh_CN" => "Chinese",
2282         "ru_RU" => "Russian");
2283   
2284   $tmp2= array(
2285         "de_DE" => _("German"),
2286         "fr_FR" => _("French"),
2287         "it_IT" => _("Italian"),
2288         "es_ES" => _("Spanish"),
2289         "en_US" => _("English"),
2290         "nl_NL" => _("Dutch"),
2291         "pl_PL" => _("Polish"),
2292         "sv_SE" => _("Swedish"),
2293         "zh_CN" => _("Chinese"),
2294         "ru_RU" => _("Russian"));
2296   $ret = array();
2297   if($languages_in_own_language){
2299     $old_lang = setlocale(LC_ALL, 0);
2300     foreach($tmp as $key => $name){
2301       $lang = $key.".UTF-8";
2302       setlocale(LC_ALL, $lang);
2303       if($strip_region_tag){
2304         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2305       }else{
2306         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2307       }
2308     }
2309     setlocale(LC_ALL, $old_lang);
2310   }else{
2311     foreach($tmp as $key => $name){
2312       if($strip_region_tag){
2313         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2314       }else{
2315         $ret[$key] = _($name);
2316       }
2317     }
2318   }
2319   return($ret);
2323 /* Returns contents of the given POST variable and check magic quotes settings */
2324 function get_post($name)
2326   if(!isset($_POST[$name])){
2327     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2328     return(FALSE);
2329   }
2330   if(get_magic_quotes_gpc()){
2331     return(stripcslashes($_POST[$name]));
2332   }else{
2333     return($_POST[$name]);
2334   }
2338 /* Check if $ip1 and $ip2 represents a valid IP range 
2339  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2340  */
2341 function is_ip_range($ip1,$ip2)
2343   if(!is_ip($ip1) || !is_ip($ip2)){
2344     return(FALSE);
2345   }else{
2346     $ar1 = split("\.",$ip1);
2347     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2349     $ar2 = split("\.",$ip2);
2350     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2351     return($var1 < $var2);
2352   }
2356 /* Check if the specified IP address $address is inside the given network */
2357 function is_in_network($network, $netmask, $address)
2359   $nw= split('\.', $network);
2360   $nm= split('\.', $netmask);
2361   $ad= split('\.', $address);
2363   /* Generate inverted netmask */
2364   for ($i= 0; $i<4; $i++){
2365     $ni[$i]= 255-$nm[$i];
2366     $la[$i]= $nw[$i] | $ni[$i];
2367   }
2369   /* Transform to integer */
2370   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2371   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2372   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2374   return ($first < $curr&& $last > $curr);
2377 /* Return class name in correct case 
2378  *  mailMethodkolab =>  mailMethodKolab  ( k => K )
2379  */
2380 function get_correct_class_name($cls)
2382   global $class_mapping;
2383   if(isset($class_mapping) && is_array($class_mapping)){
2384     foreach($class_mapping as $class => $file){
2385       if(preg_match("/^".$cls."$/i",$class)){
2386         return($class);
2387       }
2388     }
2389   }
2390   return(FALSE);
2393 // change_password, changes the Password, of the given dn
2394 function change_password ($dn, $password, $mode=0, $hash= "")
2396   global $config;
2397   $newpass= "";
2399   /* Convert to lower. Methods are lowercase */
2400   $hash= strtolower($hash);
2402   // Get all available encryption Methods
2404   // NON STATIC CALL :)
2405   $tmp = new passwordMethod($_SESSION['config']);
2406   $available = $tmp->get_available_methods();
2408   // read current password entry for $dn, to detect the encryption Method
2409   $ldap       = $config->get_ldap_link();
2410   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2411   $attrs      = $ldap->fetch ();
2413   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2414   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2415     $deactivated = TRUE;
2416   }else{
2417     $deactivated = FALSE;
2418   }
2420 #  // Get current password hash method if available
2421 #  if($hash == "" && isset($attrs['userPassword'][0]) && preg_match("/[\{\}]/",$attrs['userPassword'][0])){
2422 #    $hash = preg_replace("/^[^\{]*+\{([^\}]*).*$/","\\1",$attrs['userPassword'][0]);
2423 #    $hash = strtolower($hash);
2424 #  }
2426 #  // Set encryption type to clear if required
2427 #  if (!isset($attrs['userPassword'][0]) || $hash == ""){
2428 #    $hash= "clear";
2429 #  }
2430  // Detect the encryption Method
2431   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2433     /* Check for supported algorithm */
2434     mt_srand((double) microtime()*1000000);
2436     /* Extract used hash */
2437     if ($hash == ""){
2438       $hash= strtolower($matches[1]);
2439     }
2441     $test = new  $available[$hash]($config);
2442     $test->attrs= $attrs;
2443     $newpass =  $test->generate_hash($password);
2445   } else {
2446     // Crypt it by default
2447     $test = new  $available['md5']($config);
2448     $newpass =  $test->generate_hash($password);
2449   }
2451   // Update shadow timestamp?
2452   if (isset($attrs["shadowLastChange"][0])){
2453     $shadow= (int)(date("U") / 86400);
2454   } else {
2455     $shadow= 0;
2456   }
2458   // Write back modified entry
2459   $ldap->cd($dn);
2460   $attrs= array();
2462   // Not for groups
2463   if ($mode == 0){
2465     if ($shadow != 0){
2466       $attrs['shadowLastChange']= $shadow;
2467     }
2469     // Create SMB Password
2470     $attrs= generate_smb_nt_hash($password);
2471   }
2473  /* Readd ! if user was deactivated */
2474   if($deactivated){
2475     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2476   }
2478   $attrs['userPassword']= array();
2479   $attrs['userPassword']= $newpass;
2481   $ldap->modify($attrs);
2483   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2485   if ($ldap->error != 'Success') {
2486     print_red(sprintf(_("Setting the password failed. LDAP server says '%s'."),
2487           $ldap->get_error()));
2488   } else {
2490     /* Find postmodify entries for this class */
2491     $command= $config->search("password", "POSTMODIFY",array('menu'));
2493     if ($command != ""){
2494       /* Walk through attribute list */
2495       $command= preg_replace("/%userPassword/", $password, $command);
2496       $command= preg_replace("/%dn/", $dn, $command);
2498       if (check_command($command)){
2499         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2500         exec($command);
2501       } else {
2502         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2503         print_red ($message);
2504       }
2505     }
2506   }
2508 // Return something like array['sambaLMPassword']= "lalla..."
2509 function generate_smb_nt_hash($password)
2511   global $config;
2512   $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2513   @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2515   exec($tmp, $ar);
2516   flush();
2517   reset($ar);
2518   $hash= current($ar);
2519   if ($hash == "")
2520   {
2521     print_red (_("Setting for SMBHASH in gosa.conf is incorrect! Can't change Samba password."));
2522   }
2523   else
2524   {
2525     list($lm,$nt)= split (":", trim($hash));
2527     if ($config->current['SAMBAVERSION'] == 3)
2528     {
2529       $attrs['sambaLMPassword']= $lm;
2530       $attrs['sambaNTPassword']= $nt;
2531       $attrs['sambaPwdLastSet']= date('U');
2532       $attrs['sambaBadPasswordCount']= "0";
2533       $attrs['sambaBadPasswordTime']= "0";
2534     } else {
2535       $attrs['lmPassword']= $lm;
2536       $attrs['ntPassword']= $nt;
2537       $attrs['pwdLastSet']= date('U');
2538     }
2539     return($attrs);
2540   }
2543 function crypt_single($string,$enc_type )
2545   return( passwordMethod::crypt_single_str($string,$enc_type));
2549 /* This function returns the offset for the default timezone. 
2550  * $stamp is used to detect summer or winter time.
2551  * In case of PHP5, the integrated timezone functions are used.
2552  * For PHP4 we query an array for offset and add summertime hour.
2553  */
2554 function get_default_timezone($stamp = NULL)
2556   global $config;
2557   $tz ="";
2559   /* Default return value if zone could not be detected */
2560   $zone = array("name" => "unconfigured", "value" => 0);
2562   /* Use current timestamp if $stamp is not set */
2563   if($stamp === NULL){
2564     $stamp = time();
2565   }
2567   /* Is there a timezone configured in the gosa configuration (gosa.conf) */
2568   if(isset($config->current['TIMEZONE']) || isset($config->data['MAIN']['TIMEZONE'])){
2570     /* Get zonename */
2571     if(isset($config->current['TIMEZONE'])){
2572       $tz = $config->current['TIMEZONE'];
2573     }else{
2574       $tz = $config->data['MAIN']['TIMEZONE'];
2575     }
2577     if(!@date_default_timezone_set($tz)){
2578       print_red(sprintf(_("The timezone setting \"".$tz."\" in your gosa.conf is not valid. Can not calculate correct timezone offest."),$tz));
2579     }
2580     $tz_delta = date("Z", $stamp);
2581     $tz_delta = $tz_delta / 3600 ;
2582     return(array("name" => $tz, "value" => $tz_delta));
2584   }
2585   return($zone);
2589 /* Return zone informations */
2590 function _get_tz_zones()
2592   $timezones = array(
2593       'Africa/Abidjan' => 0,
2594       'Africa/Accra' => 0,
2595       'Africa/Addis_Ababa' => 10800,
2596       'Africa/Algiers' => 3600,
2597       'Africa/Asmera' => 10800,
2598       'Africa/Bamako' => 0,
2599       'Africa/Bangui' => 3600,
2600       'Africa/Banjul' => 0,
2601       'Africa/Bissau' => 0,
2602       'Africa/Blantyre' => 7200,
2603       'Africa/Brazzaville' => 3600,
2604       'Africa/Bujumbura' => 7200,
2605       'Africa/Cairo' => 7200,
2606       'Africa/Casablanca' => 0,
2607       'Africa/Ceuta' => 3600,
2608       'Africa/Conakry' => 0,
2609       'Africa/Dakar' => 0,
2610       'Africa/Dar_es_Salaam' => 10800,
2611       'Africa/Djibouti' => 10800,
2612       'Africa/Douala' => 3600,
2613       'Africa/El_Aaiun' => 0,
2614       'Africa/Freetown' => 0,
2615       'Africa/Gaborone' => 7200,
2616       'Africa/Harare' => 7200,
2617       'Africa/Johannesburg' => 7200,
2618       'Africa/Kampala' => 10800,
2619       'Africa/Khartoum' => 10800,
2620       'Africa/Kigali' => 7200,
2621       'Africa/Kinshasa' => 3600,
2622       'Africa/Lagos' => 3600,
2623       'Africa/Libreville' => 3600,
2624       'Africa/Lome' => 0,
2625       'Africa/Luanda' => 3600,
2626       'Africa/Lubumbashi' => 7200,
2627       'Africa/Lusaka' => 7200,
2628       'Africa/Malabo' => 3600,
2629       'Africa/Maputo' => 7200,
2630       'Africa/Maseru' => 7200,
2631       'Africa/Mbabane' => 7200,
2632       'Africa/Mogadishu' => 10800,
2633       'Africa/Monrovia' => 0,
2634       'Africa/Nairobi' => 10800,
2635       'Africa/Ndjamena' => 3600,
2636       'Africa/Niamey' => 3600,
2637       'Africa/Nouakchott' => 0,
2638       'Africa/Ouagadougou' => 0,
2639       'Africa/Porto-Novo' => 3600,
2640       'Africa/Sao_Tome' => 0,
2641       'Africa/Timbuktu' => 0,
2642       'Africa/Tripoli' => 7200,
2643       'Africa/Tunis' => 3600,
2644       'Africa/Windhoek' => 3600,
2645       'America/Adak' => -36000,
2646       'America/Anchorage' => -32400,
2647       'America/Anguilla' => -14400,
2648       'America/Antigua' => -14400,
2649       'America/Araguaina' => -10800,
2650       'America/Argentina/Buenos_Aires' => 0,
2651       'America/Argentina/Catamarca' => 0,
2652       'America/Argentina/ComodRivadavia' => 0,
2653       'America/Argentina/Cordoba' => 0,
2654       'America/Argentina/Jujuy' => 0,
2655       'America/Argentina/La_Rioja' => 0,
2656       'America/Argentina/Mendoza' => 0,
2657       'America/Argentina/Rio_Gallegos' => 0,
2658       'America/Argentina/San_Juan' => 0,
2659       'America/Argentina/Tucuman' => 0,
2660       'America/Argentina/Ushuaia' => 0,
2661       'America/Aruba' => -14400,
2662       'America/Asuncion' => -14400,
2663       'America/Atikokan' => 0,
2664       'America/Atka' => -36000,
2665       'America/Bahia' => 0,
2666       'America/Barbados' => -14400,
2667       'America/Belem' => -10800,
2668       'America/Belize' => -21600,
2669       'America/Blanc-Sablon' => 0,
2670       'America/Boa_Vista' => -14400,
2671       'America/Bogota' => -18000,
2672       'America/Boise' => -25200,
2673       'America/Buenos_Aires' => -10800,
2674       'America/Cambridge_Bay' => -25200,
2675       'America/Campo_Grande' => 0,
2676       'America/Cancun' => -21600,
2677       'America/Caracas' => -14400,
2678       'America/Catamarca' => -10800,
2679       'America/Cayenne' => -10800,
2680       'America/Cayman' => -18000,
2681       'America/Chicago' => -21600,
2682       'America/Chihuahua' => -25200,
2683       'America/Coral_Harbour' => 0,
2684       'America/Cordoba' => -10800,
2685       'America/Costa_Rica' => -21600,
2686       'America/Cuiaba' => -14400,
2687       'America/Curacao' => -14400,
2688       'America/Danmarkshavn' => 0,
2689       'America/Dawson' => -28800,
2690       'America/Dawson_Creek' => -25200,
2691       'America/Denver' => -25200,
2692       'America/Detroit' => -18000,
2693       'America/Dominica' => -14400,
2694       'America/Edmonton' => -25200,
2695       'America/Eirunepe' => -18000,
2696       'America/El_Salvador' => -21600,
2697       'America/Ensenada' => -28800,
2698       'America/Fort_Wayne' => -18000,
2699       'America/Fortaleza' => -10800,
2700       'America/Glace_Bay' => -14400,
2701       'America/Godthab' => -10800,
2702       'America/Goose_Bay' => -14400,
2703       'America/Grand_Turk' => -18000,
2704       'America/Grenada' => -14400,
2705       'America/Guadeloupe' => -14400,
2706       'America/Guatemala' => -21600,
2707       'America/Guayaquil' => -18000,
2708       'America/Guyana' => -14400,
2709       'America/Halifax' => -14400,
2710       'America/Havana' => -18000,
2711       'America/Hermosillo' => -25200,
2712       'America/Indiana/Indianapolis' => -18000,
2713       'America/Indiana/Knox' => -18000,
2714       'America/Indiana/Marengo' => -18000,
2715       'America/Indiana/Petersburg' => 0,
2716       'America/Indiana/Vevay' => -18000,
2717       'America/Indiana/Vincennes' => 0,
2718       'America/Indianapolis' => -18000,
2719       'America/Inuvik' => -25200,
2720       'America/Iqaluit' => -18000,
2721       'America/Jamaica' => -18000,
2722       'America/Jujuy' => -10800,
2723       'America/Juneau' => -32400,
2724       'America/Kentucky/Louisville' => -18000,
2725       'America/Kentucky/Monticello' => -18000,
2726       'America/Knox_IN' => -18000,
2727       'America/La_Paz' => -14400,
2728       'America/Lima' => -18000,
2729       'America/Los_Angeles' => -28800,
2730       'America/Louisville' => -18000,
2731       'America/Maceio' => -10800,
2732       'America/Managua' => -21600,
2733       'America/Manaus' => -14400,
2734       'America/Martinique' => -14400,
2735       'America/Mazatlan' => -25200,
2736       'America/Mendoza' => -10800,
2737       'America/Menominee' => -21600,
2738       'America/Merida' => -21600,
2739       'America/Mexico_City' => -21600,
2740       'America/Miquelon' => -10800,
2741       'America/Moncton' => 0,
2742       'America/Monterrey' => -21600,
2743       'America/Montevideo' => -10800,
2744       'America/Montreal' => -18000,
2745       'America/Montserrat' => -14400,
2746       'America/Nassau' => -18000,
2747       'America/New_York' => -18000,
2748       'America/Nipigon' => -18000,
2749       'America/Nome' => -32400,
2750       'America/Noronha' => -7200,
2751       'America/North_Dakota/Center' => -21600,
2752       'America/North_Dakota/New_Salem' => 0,
2753       'America/Panama' => -18000,
2754       'America/Pangnirtung' => -18000,
2755       'America/Paramaribo' => -10800,
2756       'America/Phoenix' => -25200,
2757       'America/Port-au-Prince' => -18000,
2758       'America/Port_of_Spain' => -14400,
2759       'America/Porto_Acre' => -18000,
2760       'America/Porto_Velho' => -14400,
2761       'America/Puerto_Rico' => -14400,
2762       'America/Rainy_River' => -21600,
2763       'America/Rankin_Inlet' => -21600,
2764       'America/Recife' => -10800,
2765       'America/Regina' => -21600,
2766       'America/Rio_Branco' => -18000,
2767       'America/Rosario' => -10800,
2768       'America/Santiago' => -14400,
2769       'America/Santo_Domingo' => -14400,
2770       'America/Sao_Paulo' => -10800,
2771       'America/Scoresbysund' => -3600,
2772       'America/Shiprock' => -25200,
2773       'America/St_Johns' => -12600,
2774       'America/St_Kitts' => -14400,
2775       'America/St_Lucia' => -14400,
2776       'America/St_Thomas' => -14400,
2777       'America/St_Vincent' => -14400,
2778       'America/Swift_Current' => -21600,
2779       'America/Tegucigalpa' => -21600,
2780       'America/Thule' => -14400,
2781       'America/Thunder_Bay' => -18000,
2782       'America/Tijuana' => -28800,
2783       'America/Toronto' => 0,
2784       'America/Tortola' => -14400,
2785       'America/Vancouver' => -28800,
2786       'America/Virgin' => -14400,
2787       'America/Whitehorse' => -28800,
2788       'America/Winnipeg' => -21600,
2789       'America/Yakutat' => -32400,
2790       'America/Yellowknife' => -25200,
2791       'Antarctica/Casey' => 28800,
2792       'Antarctica/Davis' => 25200,
2793       'Antarctica/DumontDUrville' => 36000,
2794       'Antarctica/Mawson' => 21600,
2795       'Antarctica/McMurdo' => 43200,
2796       'Antarctica/Palmer' => -14400,
2797       'Antarctica/Rothera' => 0,
2798       'Antarctica/South_Pole' => 43200,
2799       'Antarctica/Syowa' => 10800,
2800       'Antarctica/VostokArctic/Longyearbyen' => 0,
2801       'Asia/Aden' => 10800,
2802       'Asia/Almaty' => 21600,
2803       'Asia/Amman' => 7200,
2804       'Asia/Anadyr' => 43200,
2805       'Asia/Aqtau' => 14400,
2806       'Asia/Aqtobe' => 18000,
2807       'Asia/Ashgabat' => 18000,
2808       'Asia/Ashkhabad' => 18000,
2809       'Asia/Baghdad' => 10800,
2810       'Asia/Bahrain' => 10800,
2811       'Asia/Baku' => 14400,
2812       'Asia/Bangkok' => 25200,
2813       'Asia/Beirut' => 7200,
2814       'Asia/Bishkek' => 18000,
2815       'Asia/Brunei' => 28800,
2816       'Asia/Calcutta' => 19800,
2817       'Asia/Choibalsan' => 32400,
2818       'Asia/Chongqing' => 28800,
2819       'Asia/Chungking' => 28800,
2820       'Asia/Colombo' => 21600,
2821       'Asia/Dacca' => 21600,
2822       'Asia/Damascus' => 7200,
2823       'Asia/Dhaka' => 21600,
2824       'Asia/Dili' => 32400,
2825       'Asia/Dubai' => 14400,
2826       'Asia/Dushanbe' => 18000,
2827       'Asia/Gaza' => 7200,
2828       'Asia/Harbin' => 28800,
2829       'Asia/Hong_Kong' => 28800,
2830       'Asia/Hovd' => 25200,
2831       'Asia/Irkutsk' => 28800,
2832       'Asia/Istanbul' => 7200,
2833       'Asia/Jakarta' => 25200,
2834       'Asia/Jayapura' => 32400,
2835       'Asia/Jerusalem' => 7200,
2836       'Asia/Kabul' => 16200,
2837       'Asia/Kamchatka' => 43200,
2838       'Asia/Karachi' => 18000,
2839       'Asia/Kashgar' => 28800,
2840       'Asia/Katmandu' => 20700,
2841       'Asia/Krasnoyarsk' => 25200,
2842       'Asia/Kuala_Lumpur' => 28800,
2843       'Asia/Kuching' => 28800,
2844       'Asia/Kuwait' => 10800,
2845       'Asia/Macao' => 28800,
2846       'Asia/Macau' => 0,
2847       'Asia/Magadan' => 39600,
2848       'Asia/Makassar' => 0,
2849       'Asia/Manila' => 28800,
2850       'Asia/Muscat' => 14400,
2851       'Asia/Nicosia' => 7200,
2852       'Asia/Novosibirsk' => 21600,
2853       'Asia/Omsk' => 21600,
2854       'Asia/Oral' => 0,
2855       'Asia/Phnom_Penh' => 25200,
2856       'Asia/Pontianak' => 25200,
2857       'Asia/Pyongyang' => 32400,
2858       'Asia/Qatar' => 10800,
2859       'Asia/Qyzylorda' => 0,
2860       'Asia/Rangoon' => 23400,
2861       'Asia/Riyadh' => 10800,
2862       'Asia/Saigon' => 25200,
2863       'Asia/Sakhalin' => 36000,
2864       'Asia/Samarkand' => 18000,
2865       'Asia/Seoul' => 32400,
2866       'Asia/Shanghai' => 28800,
2867       'Asia/Singapore' => 28800,
2868       'Asia/Taipei' => 28800,
2869       'Asia/Tashkent' => 18000,
2870       'Asia/Tbilisi' => 14400,
2871       'Asia/Tehran' => 12600,
2872       'Asia/Tel_Aviv' => 7200,
2873       'Asia/Thimbu' => 21600,
2874       'Asia/Thimphu' => 21600,
2875       'Asia/Tokyo' => 32400,
2876       'Asia/Ujung_Pandang' => 28800,
2877       'Asia/Ulaanbaatar' => 28800,
2878       'Asia/Ulan_Bator' => 28800,
2879       'Asia/Urumqi' => 28800,
2880       'Asia/Vientiane' => 25200,
2881       'Asia/Vladivostok' => 36000,
2882       'Asia/Yakutsk' => 32400,
2883       'Asia/Yekaterinburg' => 18000,
2884       'Asia/YerevanAtlantic/Azores' => 0,
2885       'Atlantic/Bermuda' => -14400,
2886       'Atlantic/Canary' => 0,
2887       'Atlantic/Cape_Verde' => -3600,
2888       'Atlantic/Faeroe' => 0,
2889       'Atlantic/Jan_Mayen' => 3600,
2890       'Atlantic/Madeira' => 0,
2891       'Atlantic/Reykjavik' => 0,
2892       'Atlantic/South_Georgia' => -7200,
2893       'Atlantic/St_Helena' => 0,
2894       'Atlantic/Stanley' => -14400,
2895       'Australia/ACT' => 36000,
2896       'Australia/Adelaide' => 34200,
2897       'Australia/Brisbane' => 36000,
2898       'Australia/Broken_Hill' => 34200,
2899       'Australia/Canberra' => 36000,
2900       'Australia/Currie' => 0,
2901       'Australia/Darwin' => 34200,
2902       'Australia/Hobart' => 36000,
2903       'Australia/LHI' => 37800,
2904       'Australia/Lindeman' => 36000,
2905       'Australia/Lord_Howe' => 37800,
2906       'Australia/Melbourne' => 36000,
2907       'Australia/NSW' => 36000,
2908       'Australia/North' => 34200,
2909       'Australia/Perth' => 28800,
2910       'Australia/Queensland' => 36000,
2911       'Australia/South' => 34200,
2912       'Australia/Sydney' => 36000,
2913       'Australia/Tasmania' => 36000,
2914       'Australia/Victoria' => 36000,
2915       'Australia/West' => 28800,
2916       'Australia/Yancowinna' => 34200,
2917       'Europe/Amsterdam' => 3600,
2918       'Europe/Andorra' => 3600,
2919       'Europe/Athens' => 7200,
2920       'Europe/Belfast' => 0,
2921       'Europe/Belgrade' => 3600,
2922       'Europe/Berlin' => 3600,
2923       'Europe/Bratislava' => 3600,
2924       'Europe/Brussels' => 3600,
2925       'Europe/Bucharest' => 7200,
2926       'Europe/Budapest' => 3600,
2927       'Europe/Chisinau' => 7200,
2928       'Europe/Copenhagen' => 3600,
2929       'Europe/Dublin' => 0,
2930       'Europe/Gibraltar' => 3600,
2931       'Europe/Guernsey' => 0,
2932       'Europe/Helsinki' => 7200,
2933       'Europe/Isle_of_Man' => 0,
2934       'Europe/Istanbul' => 7200,
2935       'Europe/Jersey' => 0,
2936       'Europe/Kaliningrad' => 7200,
2937       'Europe/Kiev' => 7200,
2938       'Europe/Lisbon' => 0,
2939       'Europe/Ljubljana' => 3600,
2940       'Europe/London' => 0,
2941       'Europe/Luxembourg' => 3600,
2942       'Europe/Madrid' => 3600,
2943       'Europe/Malta' => 3600,
2944       'Europe/Mariehamn' => 0,
2945       'Europe/Minsk' => 7200,
2946       'Europe/Monaco' => 3600,
2947       'Europe/Moscow' => 10800,
2948       'Europe/Nicosia' => 7200,
2949       'Europe/Oslo' => 3600,
2950       'Europe/Paris' => 3600,
2951       'Europe/Prague' => 3600,
2952       'Europe/Riga' => 7200,
2953       'Europe/Rome' => 3600,
2954       'Europe/Samara' => 14400,
2955       'Europe/San_Marino' => 3600,
2956       'Europe/Sarajevo' => 3600,
2957       'Europe/Simferopol' => 7200,
2958       'Europe/Skopje' => 3600,
2959       'Europe/Sofia' => 7200,
2960       'Europe/Stockholm' => 3600,
2961       'Europe/Tallinn' => 7200,
2962       'Europe/Tirane' => 3600,
2963       'Europe/Tiraspol' => 7200,
2964       'Europe/Uzhgorod' => 7200,
2965       'Europe/Vaduz' => 3600,
2966       'Europe/Vatican' => 3600,
2967       'Europe/Vienna' => 3600,
2968       'Europe/Vilnius' => 7200,
2969       'Europe/Volgograd' => 0,
2970       'Europe/Warsaw' => 3600,
2971       'Europe/Zagreb' => 3600,
2972       'Europe/Zaporozhye' => 7200,
2973       'Europe/Zurich' => 3600,
2974       'Indian/Antananarivo' => 10800,
2975       'Indian/Chagos' => 21600,
2976       'Indian/Christmas' => 25200,
2977       'Indian/Cocos' => 23400,
2978       'Indian/Comoro' => 10800,
2979       'Indian/Kerguelen' => 18000,
2980       'Indian/Mahe' => 14400,
2981       'Indian/Maldives' => 18000,
2982       'Indian/Mauritius' => 14400,
2983       'Indian/Mayotte' => 10800,
2984       'Indian/Reunion' => 14400,
2985       'Pacific/Apia' => -39600,
2986       'Pacific/Auckland' => 43200,
2987       'Pacific/Chatham' => 45900,
2988       'Pacific/Easter' => -21600,
2989       'Pacific/Efate' => 39600,
2990       'Pacific/Enderbury' => 46800,
2991       'Pacific/Fakaofo' => -36000,
2992       'Pacific/Fiji' => 43200,
2993       'Pacific/Funafuti' => 43200,
2994       'Pacific/Galapagos' => -21600,
2995       'Pacific/Gambier' => -32400,
2996       'Pacific/Guadalcanal' => 39600,
2997       'Pacific/Guam' => 36000,
2998       'Pacific/Honolulu' => -36000,
2999       'Pacific/Johnston' => -36000,
3000       'Pacific/Kiritimati' => 50400,
3001       'Pacific/Kosrae' => 39600,
3002       'Pacific/Kwajalein' => 43200,
3003       'Pacific/Majuro' => 43200,
3004       'Pacific/Marquesas' => -34200,
3005       'Pacific/Midway' => -39600,
3006       'Pacific/Nauru' => 43200,
3007       'Pacific/Niue' => -39600,
3008       'Pacific/Norfolk' => 41400,
3009       'Pacific/Noumea' => 39600,
3010       'Pacific/Pago_Pago' => -39600,
3011       'Pacific/Palau' => 32400,
3012       'Pacific/Pitcairn' => -28800,
3013       'Pacific/Ponape' => 39600,
3014       'Pacific/Port_Moresby' => 36000,
3015       'Pacific/Rarotonga' => -36000,
3016       'Pacific/Saipan' => 36000,
3017       'Pacific/Samoa' => -39600,
3018       'Pacific/Tahiti' => -36000,
3019       'Pacific/Tarawa' => 43200,
3020       'Pacific/Tongatapu' => 46800,
3021       'Pacific/Truk' => 36000,
3022       'Pacific/Wake' => 43200,
3023       'Pacific/Wallis' => 43200,
3024       'Pacific/Yap' => 36000 );          
3026   $dst_timezones = array (  
3027       'America/Adak' => 1,
3028       'America/Atka' => 1,
3029       'America/Anchorage' => 1,
3030       'America/Juneau' => 1,
3031       'America/Nome' => 1,
3032       'America/Yakutat' => 1,
3033       'America/Dawson' => 1,
3034       'America/Ensenada' => 1,
3035       'America/Los_Angeles' => 1,
3036       'America/Tijuana' => 1,
3037       'America/Vancouver' => 1,
3038       'America/Whitehorse' => 1,
3039       'America/Boise' => 1,
3040       'America/Cambridge_Bay' => 1,
3041       'America/Chihuahua' => 1,
3042       'America/Denver' => 1,
3043       'America/Edmonton' => 1,
3044       'America/Inuvik' => 1,
3045       'America/Mazatlan' => 1,
3046       'America/Shiprock' => 1,
3047       'America/Yellowknife' => 1,
3048       'America/Cancun' => 1,
3049       'America/Chicago' => 1,
3050       'America/Menominee' => 1,
3051       'America/Merida' => 1,
3052       'America/Monterrey' => 1,
3053       'America/North_Dakota/Center' => 1,
3054       'America/Rainy_River' => 1,
3055       'America/Rankin_Inlet' => 1,
3056       'America/Winnipeg' => 1,
3057       'Pacific/Easter' => 1,
3058       'America/Detroit' => 1,
3059       'America/Grand_Turk' => 1,
3060       'America/Havana' => 1,
3061       'America/Iqaluit' => 1,
3062       'America/Kentucky/Louisville' => 1,
3063       'America/Kentucky/Monticello' => 1,
3064       'America/Louisville' => 1,
3065       'America/Montreal' => 1,
3066       'America/Nassau' => 1,
3067       'America/New_York' => 1,
3068       'America/Nipigon' => 1,
3069       'America/Pangnirtung' => 1,
3070       'America/Thunder_Bay' => 1,
3071       'America/Asuncion' => 1,
3072       'America/Cuiaba' => 1,
3073       'America/Glace_Bay' => 1,
3074       'America/Goose_Bay' => 1,
3075       'America/Halifax' => 1,
3076       'America/Santiago' => 1,
3077       'Antarctica/Palmer' => 1,
3078       'Atlantic/Bermuda' => 1,
3079       'Atlantic/Stanley' => 1,
3080       'America/St_Johns' => 1,
3081       'America/Araguaina' => 1,
3082       'America/Fortaleza' => 1,
3083       'America/Godthab' => 1,
3084       'America/Maceio' => 1,
3085       'America/Miquelon' => 1,
3086       'America/Recife' => 1,
3087       'America/Sao_Paulo' => 1,
3088       'America/Scoresbysund' => 1,
3089       'Atlantic/Canary' => 1,
3090       'Atlantic/Faeroe' => 1,
3091       'Atlantic/Madeira' => 1,
3092       'Europe/Belfast' => 1,
3093       'Europe/Dublin' => 1,
3094       'Europe/Lisbon' => 1,
3095       'Europe/London' => 1,
3096       'Africa/Ceuta' => 1,
3097       'Africa/Windhoek' => 1,
3098       'Atlantic/Jan_Mayen' => 1,
3099       'Europe/Amsterdam' => 1,
3100       'Europe/Andorra' => 1,
3101       'Europe/Belgrade' => 1,
3102       'Europe/Berlin' => 1,
3103       'Europe/Bratislava' => 1,
3104       'Europe/Brussels' => 1,
3105       'Europe/Budapest' => 1,
3106       'Europe/Copenhagen' => 1,
3107       'Europe/Gibraltar' => 1,
3108       'Europe/Ljubljana' => 1,
3109       'Europe/Luxembourg' => 1,
3110       'Europe/Madrid' => 1,
3111       'Europe/Malta' => 1,
3112       'Europe/Monaco' => 1,
3113       'Europe/Oslo' => 1,
3114       'Europe/Paris' => 1,
3115       'Europe/Prague' => 1,
3116       'Europe/Rome' => 1,
3117       'Europe/San_Marino' => 1,
3118       'Europe/Sarajevo' => 1,
3119       'Europe/Skopje' => 1,
3120       'Europe/Stockholm' => 1,
3121       'Europe/Tirane' => 1,
3122       'Europe/Vaduz' => 1,
3123       'Europe/Vatican' => 1,
3124       'Europe/Vienna' => 1,
3125       'Europe/Warsaw' => 1,
3126       'Europe/Zagreb' => 1,
3127       'Europe/Zurich' => 1,
3128       'Africa/Cairo' => 1,
3129       'Asia/Amman' => 1,
3130       'Asia/Beirut' => 1,
3131       'Asia/Damascus' => 1,
3132       'Asia/Gaza' => 1,
3133       'Asia/Istanbul' => 1,
3134       'Asia/Jerusalem' => 1,
3135       'Asia/Nicosia' => 1,
3136       'Asia/Tel_Aviv' => 1,
3137       'Europe/Athens' => 1,
3138       'Europe/Bucharest' => 1,
3139       'Europe/Chisinau' => 1,
3140       'Europe/Helsinki' => 1,
3141       'Europe/Istanbul' => 1,
3142       'Europe/Kaliningrad' => 1,
3143       'Europe/Kiev' => 1,
3144       'Europe/Minsk' => 1,
3145       'Europe/Nicosia' => 1,
3146       'Europe/Riga' => 1,
3147       'Europe/Simferopol' => 1,
3148       'Europe/Sofia' => 1,
3149       'Europe/Tiraspol' => 1,
3150       'Europe/Uzhgorod' => 1,
3151       'Europe/Zaporozhye' => 1,
3152       'Asia/Baghdad' => 1,
3153       'Europe/Moscow' => 1,
3154       'Asia/Tehran' => 1,
3155       'Asia/Aqtau' => 1,
3156       'Asia/Baku' => 1,
3157       'Asia/Tbilisi' => 1,
3158       'Europe/Samara' => 1,
3159       'Asia/Aqtobe' => 1,
3160       'Asia/Bishkek' => 1,
3161       'Asia/Yekaterinburg' => 1,
3162       'Asia/Almaty' => 1,
3163       'Asia/Novosibirsk' => 1,
3164       'Asia/Omsk' => 1,
3165       'Asia/Krasnoyarsk' => 1,
3166       'Asia/Irkutsk' => 1,
3167       'Asia/Yakutsk' => 1,
3168       'Australia/Adelaide' => 1,
3169       'Australia/Broken_Hill' => 1,
3170       'Australia/South' => 1,
3171       'Australia/Yancowinna' => 1,
3172       'Asia/Sakhalin' => 1,
3173       'Asia/Vladivostok' => 1,
3174       'Australia/ACT' => 1,
3175       'Australia/Canberra' => 1,
3176       'Australia/Hobart' => 1,
3177       'Australia/Melbourne' => 1,
3178       'Australia/NSW' => 1,
3179       'Australia/Sydney' => 1,
3180       'Australia/Tasmania' => 1,
3181       'Australia/Victoria' => 1,
3182       'Australia/LHI' => 1,
3183       'Australia/Lord_Howe' => 1,
3184       'Asia/Magadan' => 1,
3185       'Antarctica/McMurdo' => 1,
3186       'Antarctica/South_Pole' => 1,
3187       'Asia/Anadyr' => 1,
3188       'Asia/Kamchatka' => 1,
3189       'Pacific/Auckland' => 1,
3190       'Pacific/Chatham' => 1,
3191       );  
3192   return(array("TIMEZONES" => $timezones, "DST_ZONES" => $dst_timezones));
3194 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3195 ?>