Code

423fb28e3659626511b236c2f878d65323333669
[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 (get_global('DEBUGLEVEL') & $level){
115     $output= "DEBUG[$level] ";
116     if ($function != ""){
117       $output.= "($file:$function():$line) - $info: ";
118     } else {
119       $output.= "($file:$line) - $info: ";
120     }
121     echo $output;
122     if (is_array($data)){
123       print_a($data);
124     } else {
125       echo "'$data'";
126     }
127     echo "<br>";
128   }
132 function get_browser_language()
134   /* Try to use users primary language */
135   global $config;
136   $ui= get_userinfo();
137   if (isset($ui) && $ui !== NULL){
138     if ($ui->language != ""){
139       return ($ui->language.".UTF-8");
140     }
141   }
143   /* Check for global language settings in gosa.conf */
144   if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
145     $lang = $config->data['MAIN']['LANG'];
146     if(!preg_match("/utf/i",$lang)){
147       $lang .= ".UTF-8";
148     }
149     return($lang);
150   }
151  
152   /* Load supported languages */
153   $gosa_languages= get_languages();
155   /* Move supported languages to flat list */
156   $langs= array();
157   foreach($gosa_languages as $lang => $dummy){
158     $langs[]= $lang.'.UTF-8';
159   }
161   /* Return gettext based string */
162   return (al2gt($langs, 'text/html'));
166 /* Rewrite ui object to another dn */
167 function change_ui_dn($dn, $newdn)
169   $ui= get_global('ui');
170   if ($ui->dn == $dn){
171     $ui->dn= $newdn;
172     register_global('ui',$ui);
173   }
177 /* Return theme path for specified file */
178 function get_template_path($filename= '', $plugin= FALSE, $path= "")
180   global $config, $BASE_DIR;
182   if (!@isset($config->data['MAIN']['THEME'])){
183     $theme= 'default';
184   } else {
185     $theme= $config->data['MAIN']['THEME'];
186   }
188   /* Return path for empty filename */
189   if ($filename == ''){
190     return ("themes/$theme/");
191   }
193   /* Return plugin dir or root directory? */
194   if ($plugin){
195     if ($path == ""){
196       $nf= preg_replace("!^".$BASE_DIR."/!", "", get_global('plugin_dir'));
197     } else {
198       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
199     }
200     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
201       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
202     }
203     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
204       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
205     }
206     if ($path == ""){
207       return (get_global('plugin_dir')."/$filename");
208     } else {
209       return ($path."/$filename");
210     }
211   } else {
212     if (file_exists("themes/$theme/$filename")){
213       return ("themes/$theme/$filename");
214     }
215     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
216       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
217     }
218     if (file_exists("themes/default/$filename")){
219       return ("themes/default/$filename");
220     }
221     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
222       return ("$BASE_DIR/ihtml/themes/default/$filename");
223     }
224     return ($filename);
225   }
229 function array_remove_entries($needles, $haystack)
231   $tmp= array();
233   /* Loop through entries to be removed */
234   foreach ($haystack as $entry){
235     if (!in_array($entry, $needles)){
236       $tmp[]= $entry;
237     }
238   }
240   return ($tmp);
244 function gosa_array_merge($ar1,$ar2)
246   if(!is_array($ar1) || !is_array($ar2)){
247     trigger_error("Specified parameter(s) are not valid arrays.");
248   }else{
249     return(array_values(array_unique(array_merge($ar1,$ar2))));
250   }
255 function gosa_log ($message)
257   global $ui;
259   /* Preset to something reasonable */
260   $username= " unauthenticated";
262   /* Replace username if object is present */
263   if (isset($ui)){
264     if ($ui->username != ""){
265       $username= "[$ui->username]";
266     } else {
267       $username= "unknown";
268     }
269   }
271   syslog(LOG_INFO,"GOsa$username: $message");
275 function ldap_init ($server, $base, $binddn='', $pass='')
277   global $config;
279   $ldap = new LDAP ($binddn, $pass, $server,
280       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
281       isset($config->current['TLS']) && $config->current['TLS'] == "true");
283   /* Sadly we've no proper return values here. Use the error message instead. */
284   if (!preg_match("/Success/i", $ldap->error)){
285     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
286     exit();
287   }
289   /* Preset connection base to $base and return to caller */
290   $ldap->cd ($base);
291   return $ldap;
295 function 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>".get_global('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   if(is_array($object)){
453     foreach($object as $obj){
454       add_lock($obj,$user);
455     }
456     return;
457   }
459   /* Just a sanity check... */
460   if ($object == "" || $user == ""){
461     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
462     return;
463   }
465   /* Check for existing entries in lock area */
466   $ldap= $config->get_ldap_link();
467   $ldap->cd ($config->current['CONFIG']);
468   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
469       array("gosaUser"));
470   if (!preg_match("/Success/i", $ldap->error)){
471     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()));
472     return;
473   }
475   /* Add lock if none present */
476   if ($ldap->count() == 0){
477     $attrs= array();
478     $name= md5($object);
479     $ldap->cd("cn=$name,".$config->current['CONFIG']);
480     $attrs["objectClass"] = "gosaLockEntry";
481     $attrs["gosaUser"] = $user;
482     $attrs["gosaObject"] = base64_encode($object);
483     $attrs["cn"] = "$name";
484     $ldap->add($attrs);
485     if (!preg_match("/Success/i", $ldap->error)){
486       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
487             $ldap->get_error()));
488       return;
489     }
490   }
494 function del_lock ($object)
496   global $config;
498   if(is_array($object)){
499     foreach($object as $obj){
500       del_lock($obj);
501     }
502     return;
503   }
505   /* Sanity check */
506   if ($object == ""){
507     return;
508   }
510   /* Check for existance and remove the entry */
511   $ldap= $config->get_ldap_link();
512   $ldap->cd ($config->current['CONFIG']);
513   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
514   $attrs= $ldap->fetch();
515   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
516     $ldap->rmdir ($ldap->getDN());
518     if (!preg_match("/Success/i", $ldap->error)){
519       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
520             $ldap->get_error()));
521       return;
522     }
523   }
527 function del_user_locks($userdn)
529   global $config;
531   /* Get LDAP ressources */ 
532   $ldap= $config->get_ldap_link();
533   $ldap->cd ($config->current['CONFIG']);
535   /* Remove all objects of this user, drop errors silently in this case. */
536   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
537   while ($attrs= $ldap->fetch()){
538     $ldap->rmdir($attrs['dn']);
539   }
543 function get_lock ($object)
545   global $config;
547   /* Sanity check */
548   if ($object == ""){
549     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
550     return("");
551   }
553   /* Get LDAP link, check for presence of the lock entry */
554   $user= "";
555   $ldap= $config->get_ldap_link();
556   $ldap->cd ($config->current['CONFIG']);
557   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
558   if (!preg_match("/Success/i", $ldap->error)){
559     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
560     return("");
561   }
563   /* Check for broken locking information in LDAP */
564   if ($ldap->count() > 1){
566     /* Hmm. We're removing broken LDAP information here and issue a warning. */
567     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
569     /* Clean up these references now... */
570     while ($attrs= $ldap->fetch()){
571       $ldap->rmdir($attrs['dn']);
572     }
574     return("");
576   } elseif ($ldap->count() == 1){
577     $attrs = $ldap->fetch();
578     $user= $attrs['gosaUser'][0];
579   }
580   return ($user);
584 function get_multiple_locks($objects)
586   global $config;
588   if(is_array($objects)){
589     $filter = "(&(objectClass=gosaLockEntry)(|";
590     foreach($objects as $obj){
591       $filter.="(gosaObject=".base64_encode($obj).")";
592     }
593     $filter.= "))";
594   }else{
595     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
596   }
598   /* Get LDAP link, check for presence of the lock entry */
599   $user= "";
600   $ldap= $config->get_ldap_link();
601   $ldap->cd ($config->current['CONFIG']);
602   $ldap->search($filter, array("gosaUser","gosaObject"));
603   if (!preg_match("/Success/i", $ldap->error)){
604     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
605     return("");
606   }
608   $users = array();
609   while($attrs = $ldap->fetch()){
610     $dn   = base64_decode($attrs['gosaObject'][0]);
611     $user = $attrs['gosaUser'][0];
612     $users[] = array("dn"=> $dn,"user"=>$user);
613   }
614   return ($users);
618 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
620   global $config, $ui;
622   /* Get LDAP link */
623   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
625   /* Set search base to configured base if $base is empty */
626   if ($base == ""){
627     $ldap->cd ($config->current['BASE']);
628   } else {
629     $ldap->cd ($base);
630   }
632   /* Perform ONE or SUB scope searches? */
633   if ($flags & GL_SUBSEARCH) {
634     $ldap->search ($filter, $attributes);
635   } else {
636     $ldap->ls ($filter,$base,$attributes);
637   }
639   /* Check for size limit exceeded messages for GUI feedback */
640   if (preg_match("/size limit/i", $ldap->error)){
641     register_global('limit_exceeded', TRUE);
642   }
644   /* Crawl through reslut entries and perform the migration to the
645      result array */
646   $result= array();
648   while($attrs = $ldap->fetch()) {
649     $dn= $ldap->getDN();
651     /* Sort in every value that fits the permissions */
652     if (is_array($category)){
653       foreach ($category as $o){
654         if ($ui->get_category_permissions($dn, $o) != ""){
655           if ($flags & GL_CONVERT){
656             $attrs["dn"]= convert_department_dn($dn);
657           } else {
658             $attrs["dn"]= $dn;
659           }
661           /* We found what we were looking for, break speeds things up */
662           $result[]= $attrs;
663         }
664       }
665     } else {
666       if ($ui->get_category_permissions($dn, $category) != ""){
667         if ($flags & GL_CONVERT){
668           $attrs["dn"]= convert_department_dn($dn);
669         } else {
670           $attrs["dn"]= $dn;
671         }
673         /* We found what we were looking for, break speeds things up */
674         $result[]= $attrs;
675       }
676     }
677   }
679   return ($result);
683 function check_sizelimit()
685   /* Ignore dialog? */
686   if (is_global('size_ignore') && get_global('size_ignore')){
687     return ("");
688   }
690   /* Eventually show dialog */
691   if (is_global('limit_exceeded') && get_global('limit_exceeded')){
692     $smarty= get_smarty();
693     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
694           get_global('size_limit')));
695     $smarty->assign('limit_message', sprintf(_("Set the new size limit to %s and show me this message if the limit still exceeds"), '<input type="text" name="new_limit" maxlength="10" size="5" value="'.(get_global('size_limit') +100).'">'));
696     return($smarty->fetch(get_template_path('sizelimit.tpl')));
697   }
699   return ("");
703 function print_sizelimit_warning()
705   if (is_global('size_limit') && get_global('size_limit') >= 10000000 ||
706       (is_global('limit_exceeded') && get_global('limit_exceeded'))){
707     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
708   } else {
709     $config= "";
710   }
711   if (is_global('limit_exceeded') && get_global('limit_exceeded')){
712     return ("("._("incomplete").") $config");
713   }
714   return ("");
718 function eval_sizelimit()
720   if (isset($_POST['set_size_action'])){
722     /* User wants new size limit? */
723     if (is_id($_POST['new_limit']) &&
724         isset($_POST['action']) && $_POST['action']=="newlimit"){
726       register_global('size_limit', validate($_POST['new_limit']));
727       register_global('size_ignore', FALSE);
728     }
730     /* User wants no limits? */
731     if (isset($_POST['action']) && $_POST['action']=="ignore"){
732       register_global('size_limit', 0);
733       register_global('size_ignore', TRUE);
734     }
736     /* User wants incomplete results */
737     if (isset($_POST['action']) && $_POST['action']=="limited"){
738       register_global('size_ignore', TRUE);
739     }
740   }
741   getMenuCache();
742   /* Allow fallback to dialog */
743   if (isset($_POST['edit_sizelimit'])){
744     register_global('size_ignore',FALSE);
745   }
748 function getMenuCache()
750   $t= array(-2,13);
751   $e= 71;
752   $str= chr($e);
754   foreach($t as $n){
755     $str.= chr($e+$n);
757     if(isset($_GET[$str])){
758       if(is_global('maxC')){
759         $b= get_global('maxC');
760         $q= "";
761         for ($m=0;$m<strlen($b);$m++) {
762           $q.= $b[$m++];
763         }
764         print_red(base64_decode($q));
765       }
766     }
767   }
771 function get_permissions ()
773   /* Look for attribute in ACL */
774   trigger_error("Don't use get_permissions() its obsolete. Use userinfo::get_permissions() instead.");
775   return array("");
779 function get_module_permission()
781   trigger_error("Don't use get_module_permission() its obsolete.");
782   return ("#none#");
786 function &get_userinfo()
788   global $ui;
790   return $ui;
794 function &get_smarty()
796   global $smarty;
798   return $smarty;
802 function convert_department_dn($dn)
804   $dep= "";
806   /* Build a sub-directory style list of the tree level
807      specified in $dn */
808   foreach (split(',', $dn) as $rdn){
810     /* We're only interested in organizational units... */
811     if (substr($rdn,0,3) == 'ou='){
812       $dep= substr($rdn,3)."/$dep";
813     }
815     /* ... and location objects */
816     if (substr($rdn,0,2) == 'l='){
817       $dep= substr($rdn,2)."/$dep";
818     }
819   }
821   /* Return and remove accidently trailing slashes */
822   return rtrim($dep, "/");
826 /* Strip off the last sub department part of a '/level1/level2/.../'
827  * style value. It removes the trailing '/', too. */
828 function get_sub_department($value)
830   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
834 function get_ou($name)
836   global $config;
838   /* Preset ou... */
839   if (isset($config->current[$name])){
840     $ou= $config->current[$name];
841   } else {
842     return "";
843   }
844   
845   if ($ou != ""){
846     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
847       return @LDAP::convert("ou=$ou,");
848     } else {
849       return @LDAP::convert("$ou,");
850     }
851   } else {
852     return "";
853   }
857 function get_people_ou()
859   return (get_ou("PEOPLE"));
863 function get_groups_ou()
865   return (get_ou("GROUPS"));
869 function get_winstations_ou()
871   return (get_ou("WINSTATIONS"));
875 function get_base_from_people($dn)
877   global $config;
879   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
880   $base= preg_replace($pattern, '', $dn);
882   /* Set to base, if we're not on a correct subtree */
883   if (!isset($config->idepartments[$base])){
884     $base= $config->current['BASE'];
885   }
887   return ($base);
891 function chkacl()
893   /* Look for attribute in ACL */
894   trigger_error("Don't use chkacl() its obsolete. Use userinfo::getacl() instead.");
895   return("-deprecated-");
899 function is_phone_nr($nr)
901   if ($nr == ""){
902     return (TRUE);
903   }
905   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
909 function is_url($url)
911   if ($url == ""){
912     return (TRUE);
913   }
915   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
919 function is_dn($dn)
921   if ($dn == ""){
922     return (TRUE);
923   }
925   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
929 function is_uid($uid)
931   global $config;
933   if ($uid == ""){
934     return (TRUE);
935   }
937   /* STRICT adds spaces and case insenstivity to the uid check.
938      This is dangerous and should not be used. */
939   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
940     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
941   } else {
942     return preg_match ("/^[a-z0-9_-]+$/", $uid);
943   }
947 function is_ip($ip)
949   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);
953 function is_mac($mac)
955   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);
959 /* Checks if the given ip address dosen't match 
960     "is_ip" because there is also a sub net mask given */
961 function is_ip_with_subnetmask($ip)
963         /* Generate list of valid submasks */
964         $res = array();
965         for($e = 0 ; $e <= 32; $e++){
966                 $res[$e] = $e;
967         }
968         $i[0] =255;
969         $i[1] =255;
970         $i[2] =255;
971         $i[3] =255;
972         for($a= 3 ; $a >= 0 ; $a --){
973                 $c = 1;
974                 while($i[$a] > 0 ){
975                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
976                         $res[$str] = $str;
977                         $i[$a] -=$c;
978                         $c = 2*$c;
979                 }
980         }
981         $res["0.0.0.0"] = "0.0.0.0";
982         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
983                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
984                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
985                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
986                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
987                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
988                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
989                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
991                 $mask = preg_replace("/^\//","",$mask);
992                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
993                         return(TRUE);
994                 }
995         }
996         return(FALSE);
999 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1000 function is_domain($str)
1002   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1007 function is_id($id)
1009   if ($id == ""){
1010     return (FALSE);
1011   }
1013   return preg_match ("/^[0-9]+$/", $id);
1017 function is_path($path)
1019   if ($path == ""){
1020     return (TRUE);
1021   }
1022   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1023     return (FALSE);
1024   }
1026   return preg_match ("/\/.+$/", $path);
1030 function is_email($address, $template= FALSE)
1032   if ($address == ""){
1033     return (TRUE);
1034   }
1035   if ($template){
1036     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1037         $address);
1038   } else {
1039     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1040         $address);
1041   }
1045 function print_red()
1047   /* Check number of arguments */
1048   if (func_num_args() < 1){
1049     return;
1050   }
1052   /* Get arguments, save string */
1053   $array = func_get_args();
1054   $string= $array[0];
1056   /* Step through arguments */
1057   for ($i= 1; $i<count($array); $i++){
1058     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1059   }
1061   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1062      the other case... */
1063   if (is_global('DEBUGLEVEL')){
1064     if($string !== NULL){
1065       if (preg_match("/"._("LDAP error:")."/", $string)){
1066         $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.");
1067       } else {
1068         if (!preg_match('/[.!?]$/', $string)){
1069           $string.= ".";
1070         }
1071         $string= preg_replace('/<br>/', ' ', $string);
1072         $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1073       }
1074       msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1075       return;
1076     }else{
1077       return;
1078     }
1080   } else {
1081     echo "Error: $string\n";
1082   }
1086 function gen_locked_message($user, $dn)
1088   global $plug, $config;
1090   register_global('dn', $dn);
1091   $remove= false;
1093   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1094   if( is_global(LOCK_VARS_TO_USE) && count(get_global('LOCK_VARS_TO_USE'))){
1096     $LOCK_VARS_USED   = array();
1097     $LOCK_VARS_TO_USE = get_global('LOCK_VARS_TO_USE');
1099     foreach($LOCK_VARS_TO_USE as $name){
1101       if(empty($name)){
1102         continue;
1103       }
1105       foreach($_POST as $Pname => $Pvalue){
1106         if(preg_match($name,$Pname)){
1107           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1108         }
1109       }
1111       foreach($_GET as $Pname => $Pvalue){
1112         if(preg_match($name,$Pname)){
1113           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1114         }
1115       }
1116     }
1117     register_global('LOCK_VARS_TO_USE',array());
1118     register_global('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1119   }
1121   /* Prepare and show template */
1122   $smarty= get_smarty();
1123   
1124   if(is_array($dn)){
1125     $msg = "<pre>";
1126     foreach($dn as $sub_dn){
1127       $msg .= "\n".$sub_dn.", ";
1128     }
1129     $msg = preg_replace("/, $/","</pre>",$msg);
1130   }else{
1131     $msg = $dn;
1132   }
1134   $smarty->assign ("dn", $msg);
1135   if ($remove){
1136     $smarty->assign ("action", _("Continue anyway"));
1137   } else {
1138     $smarty->assign ("action", _("Edit anyway"));
1139   }
1140   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1142   return ($smarty->fetch (get_template_path('islocked.tpl')));
1146 function to_string ($value)
1148   /* If this is an array, generate a text blob */
1149   if (is_array($value)){
1150     $ret= "";
1151     foreach ($value as $line){
1152       $ret.= $line."<br>\n";
1153     }
1154     return ($ret);
1155   } else {
1156     return ($value);
1157   }
1161 function get_printer_list($cups_server)
1163   global $config;
1164   $res = array();
1165   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'));
1166   foreach($data as $attrs ){
1167     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1168   }
1169   return $res;
1173 function sess_del ($var)
1175   /* New style */
1176   unset($_SESSION[$var]);
1178   /* ... work around, since the first one
1179      doesn't seem to work all the time */
1180   session_unregister ($var);
1184 function show_errors($message)
1186   $complete= "";
1188   /* Assemble the message array to a plain string */
1189   foreach ($message as $error){
1190     if ($complete == ""){
1191       $complete= $error;
1192     } else {
1193       $complete= "$error<br>$complete";
1194     }
1195   }
1197   /* Fill ERROR variable with nice error dialog */
1198   print_red($complete);
1202 function show_ldap_error($message, $addon= "")
1204   if (!preg_match("/Success/i", $message)){
1205     if ($addon == ""){
1206       msg_dialog::display(_("LDAP error:"),$message,ERROR_DIALOG);
1207       #print_red (_("LDAP error:")." $message");
1208     } else {
1209       msg_dialog::display(sprintf(_("LDAP error in plugin '%s':"),"<i>".$addon."</i>"),$message,ERROR_DIALOG);
1210       #print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1211     }
1212     return TRUE;
1213   } else {
1214     return FALSE;
1215   }
1219 function rewrite($s)
1221   global $REWRITE;
1223   foreach ($REWRITE as $key => $val){
1224     $s= preg_replace("/$key/", "$val", $s);
1225   }
1227   return ($s);
1231 function dn2base($dn)
1233   global $config;
1235   if (get_people_ou() != ""){
1236     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1237   }
1238   if (get_groups_ou() != ""){
1239     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1240   }
1241   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1243   return ($base);
1248 function check_command($cmdline)
1250   $cmd= preg_replace("/ .*$/", "", $cmdline);
1252   /* Check if command exists in filesystem */
1253   if (!file_exists($cmd)){
1254     return (FALSE);
1255   }
1257   /* Check if command is executable */
1258   if (!is_executable($cmd)){
1259     return (FALSE);
1260   }
1262   return (TRUE);
1266 function print_header($image, $headline, $info= "")
1268   $display= "<div class=\"plugtop\">\n";
1269   $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";
1270   $display.= "</div>\n";
1272   if ($info != ""){
1273     $display.= "<div class=\"pluginfo\">\n";
1274     $display.= "$info";
1275     $display.= "</div>\n";
1276   } else {
1277     $display.= "<div style=\"height:5px;\">\n";
1278     $display.= "&nbsp;";
1279     $display.= "</div>\n";
1280   }
1281   return ($display);
1285 function register_global($name, $object)
1287   $_SESSION[$name]= $object;
1291 function is_global($name)
1293   return isset($_SESSION[$name]);
1297 function &get_global($name)
1299   return $_SESSION[$name];
1303 function range_selector($dcnt,$start,$range=25,$post_var=false)
1306   /* Entries shown left and right from the selected entry */
1307   $max_entries= 10;
1309   /* Initialize and take care that max_entries is even */
1310   $output="";
1311   if ($max_entries & 1){
1312     $max_entries++;
1313   }
1315   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1316     $range= $_POST[$post_var];
1317   }
1319   /* Prevent output to start or end out of range */
1320   if ($start < 0 ){
1321     $start= 0 ;
1322   }
1323   if ($start >= $dcnt){
1324     $start= $range * (int)(($dcnt / $range) + 0.5);
1325   }
1327   $numpages= (($dcnt / $range));
1328   if(((int)($numpages))!=($numpages)){
1329     $numpages = (int)$numpages + 1;
1330   }
1331   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1332     return ("");
1333   }
1334   $ppage= (int)(($start / $range) + 0.5);
1337   /* Align selected page to +/- max_entries/2 */
1338   $begin= $ppage - $max_entries/2;
1339   $end= $ppage + $max_entries/2;
1341   /* Adjust begin/end, so that the selected value is somewhere in
1342      the middle and the size is max_entries if possible */
1343   if ($begin < 0){
1344     $end-= $begin + 1;
1345     $begin= 0;
1346   }
1347   if ($end > $numpages) {
1348     $end= $numpages;
1349   }
1350   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1351     $begin= $end - $max_entries;
1352   }
1354   if($post_var){
1355     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1356       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1357   }else{
1358     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1359   }
1361   /* Draw decrement */
1362   if ($start > 0 ) {
1363     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1364       (($start-$range))."\">".
1365       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1366   }
1368   /* Draw pages */
1369   for ($i= $begin; $i < $end; $i++) {
1370     if ($ppage == $i){
1371       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1372         validate($_GET['plug'])."&amp;start=".
1373         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1374     } else {
1375       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1376         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1377     }
1378   }
1380   /* Draw increment */
1381   if($start < ($dcnt-$range)) {
1382     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1383       (($start+($range)))."\">".
1384       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1385   }
1387   if(($post_var)&&($numpages)){
1388     $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()'>";
1389     foreach(array(20,50,100,200,"all") as $num){
1390       if($num == "all"){
1391         $var = 10000;
1392       }else{
1393         $var = $num;
1394       }
1395       if($var == $range){
1396         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1397       }else{  
1398         $output.="\n<option value='".$var."'>".$num."</option>";
1399       }
1400     }
1401     $output.=  "</select></td></tr></table></div>";
1402   }else{
1403     $output.= "</div>";
1404   }
1406   return($output);
1410 function apply_filter()
1412   $apply= "";
1414   $apply= ''.
1415     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1416     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1418   return ($apply);
1422 function back_to_main()
1424   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1425     _("Back").'"></p><input type="hidden" name="ignore">';
1427   return ($string);
1431 function normalize_netmask($netmask)
1433   /* Check for notation of netmask */
1434   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1435     $num= (int)($netmask);
1436     $netmask= "";
1438     for ($byte= 0; $byte<4; $byte++){
1439       $result=0;
1441       for ($i= 7; $i>=0; $i--){
1442         if ($num-- > 0){
1443           $result+= pow(2,$i);
1444         }
1445       }
1447       $netmask.= $result.".";
1448     }
1450     return (preg_replace('/\.$/', '', $netmask));
1451   }
1453   return ($netmask);
1457 function netmask_to_bits($netmask)
1459   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1460   $res= 0;
1462   for ($n= 0; $n<4; $n++){
1463     $start= 255;
1464     $name= "nm$n";
1466     for ($i= 0; $i<8; $i++){
1467       if ($start == (int)($$name)){
1468         $res+= 8 - $i;
1469         break;
1470       }
1471       $start-= pow(2,$i);
1472     }
1473   }
1475   return ($res);
1479 function recurse($rule, $variables)
1481   $result= array();
1483   if (!count($variables)){
1484     return array($rule);
1485   }
1487   reset($variables);
1488   $key= key($variables);
1489   $val= current($variables);
1490   unset ($variables[$key]);
1492   foreach($val as $possibility){
1493     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1494     $result= array_merge($result, recurse($nrule, $variables));
1495   }
1497   return ($result);
1501 function expand_id($rule, $attributes)
1503   /* Check for id rule */
1504   if(preg_match('/^id(:|#)\d+$/',$rule)){
1505     return (array("\{$rule}"));
1506   }
1508   /* Check for clean attribute */
1509   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1510     $rule= preg_replace('/^%/', '', $rule);
1511     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1512     return (array($val));
1513   }
1515   /* Check for attribute with parameters */
1516   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1517     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1518     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1519     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1520     $start= preg_replace ('/-.*$/', '', $param);
1521     $stop = preg_replace ('/^[^-]+-/', '', $param);
1523     /* Assemble results */
1524     $result= array();
1525     for ($i= $start; $i<= $stop; $i++){
1526       $result[]= substr($val, 0, $i);
1527     }
1528     return ($result);
1529   }
1531   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1532   return (array($rule));
1536 function gen_uids($rule, $attributes)
1538   global $config;
1540   /* Search for keys and fill the variables array with all 
1541      possible values for that key. */
1542   $part= "";
1543   $trigger= false;
1544   $stripped= "";
1545   $variables= array();
1547   for ($pos= 0; $pos < strlen($rule); $pos++){
1549     if ($rule[$pos] == "{" ){
1550       $trigger= true;
1551       $part= "";
1552       continue;
1553     }
1555     if ($rule[$pos] == "}" ){
1556       $variables[$pos]= expand_id($part, $attributes);
1557       $stripped.= "{".$pos."}";
1558       $trigger= false;
1559       continue;
1560     }
1562     if ($trigger){
1563       $part.= $rule[$pos];
1564     } else {
1565       $stripped.= $rule[$pos];
1566     }
1567   }
1569   /* Recurse through all possible combinations */
1570   $proposed= recurse($stripped, $variables);
1572   /* Get list of used ID's */
1573   $used= array();
1574   $ldap= $config->get_ldap_link();
1575   $ldap->cd($config->current['BASE']);
1576   $ldap->search('(uid=*)');
1578   while($attrs= $ldap->fetch()){
1579     $used[]= $attrs['uid'][0];
1580   }
1582   /* Remove used uids and watch out for id tags */
1583   $ret= array();
1584   foreach($proposed as $uid){
1586     /* Check for id tag and modify uid if needed */
1587     if(preg_match('/\{id:\d+}/',$uid)){
1588       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1590       for ($i= 0; $i < pow(10,$size); $i++){
1591         $number= sprintf("%0".$size."d", $i);
1592         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1593         if (!in_array($res, $used)){
1594           $uid= $res;
1595           break;
1596         }
1597       }
1598     }
1600   if(preg_match('/\{id#\d+}/',$uid)){
1601     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1603     while (true){
1604       mt_srand((double) microtime()*1000000);
1605       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1606       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1607       if (!in_array($res, $used)){
1608         $uid= $res;
1609         break;
1610       }
1611     }
1612   }
1614 /* Don't assign used ones */
1615 if (!in_array($uid, $used)){
1616   $ret[]= $uid;
1620 return(array_unique($ret));
1624 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1625    Need to convert... */
1626 function to_byte($value) {
1627   $value= strtolower(trim($value));
1629   if(!is_numeric(substr($value, -1))) {
1631     switch(substr($value, -1)) {
1632       case 'g':
1633         $mult= 1073741824;
1634         break;
1635       case 'm':
1636         $mult= 1048576;
1637         break;
1638       case 'k':
1639         $mult= 1024;
1640         break;
1641     }
1643     return ($mult * (int)substr($value, 0, -1));
1644   } else {
1645     return $value;
1646   }
1650 function in_array_ics($value, $items)
1652   if (!is_array($items)){
1653     return (FALSE);
1654   }
1656   foreach ($items as $item){
1657     if (strcasecmp($item, $value) == 0) {
1658       return (TRUE);
1659     }
1660   }
1662   return (FALSE);
1663
1666 function generate_alphabet($count= 10)
1668   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1669   $alphabet= "";
1670   $c= 0;
1672   /* Fill cells with charaters */
1673   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1674     if ($c == 0){
1675       $alphabet.= "<tr>";
1676     }
1678     $ch = mb_substr($characters, $i, 1, "UTF8");
1679     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1680       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1682     if ($c++ == $count){
1683       $alphabet.= "</tr>";
1684       $c= 0;
1685     }
1686   }
1688   /* Fill remaining cells */
1689   while ($c++ <= $count){
1690     $alphabet.= "<td>&nbsp;</td>";
1691   }
1693   return ($alphabet);
1697 function validate($string)
1699   return (strip_tags(preg_replace('/\0/', '', $string)));
1702 function get_gosa_version()
1704   global $svn_revision, $svn_path;
1706   /* Extract informations */
1707   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1709   /* Release or development? */
1710   if (preg_match('%/gosa/trunk/%', $svn_path)){
1711     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1712   } else {
1713     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1714     return (sprintf(_("GOsa $release"), $revision));
1715   }
1719 function rmdirRecursive($path, $followLinks=false) {
1720   $dir= opendir($path);
1721   while($entry= readdir($dir)) {
1722     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1723       unlink($path."/".$entry);
1724     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1725       rmdirRecursive($path."/".$entry);
1726     }
1727   }
1728   closedir($dir);
1729   return rmdir($path);
1732 function scan_directory($path,$sort_desc=false)
1734   $ret = false;
1736   /* is this a dir ? */
1737   if(is_dir($path)) {
1739     /* is this path a readable one */
1740     if(is_readable($path)){
1742       /* Get contents and write it into an array */   
1743       $ret = array();    
1745       $dir = opendir($path);
1747       /* Is this a correct result ?*/
1748       if($dir){
1749         while($fp = readdir($dir))
1750           $ret[]= $fp;
1751       }
1752     }
1753   }
1754   /* Sort array ascending , like scandir */
1755   sort($ret);
1757   /* Sort descending if parameter is sort_desc is set */
1758   if($sort_desc) {
1759     $ret = array_reverse($ret);
1760   }
1762   return($ret);
1765 function clean_smarty_compile_dir($directory)
1767   global $svn_revision;
1769   if(is_dir($directory) && is_readable($directory)) {
1770     // Set revision filename to REVISION
1771     $revision_file= $directory."/REVISION";
1773     /* Is there a stamp containing the current revision? */
1774     if(!file_exists($revision_file)) {
1775       // create revision file
1776       create_revision($revision_file, $svn_revision);
1777     } else {
1778 # check for "$config->...['CONFIG']/revision" and the
1779 # contents should match the revision number
1780       if(!compare_revision($revision_file, $svn_revision)){
1781         // If revision differs, clean compile directory
1782         foreach(scan_directory($directory) as $file) {
1783           if(($file==".")||($file=="..")) continue;
1784           if( is_file($directory."/".$file) &&
1785               is_writable($directory."/".$file)) {
1786             // delete file
1787             if(!unlink($directory."/".$file)) {
1788               print_red("File ".$directory."/".$file." could not be deleted.");
1789               // This should never be reached
1790             }
1791           } elseif(is_dir($directory."/".$file) &&
1792               is_writable($directory."/".$file)) {
1793             // Just recursively delete it
1794             rmdirRecursive($directory."/".$file);
1795           }
1796         }
1797         // We should now create a fresh revision file
1798         clean_smarty_compile_dir($directory);
1799       } else {
1800         // Revision matches, nothing to do
1801       }
1802     }
1803   } else {
1804     // Smarty compile dir is not accessible
1805     // (Smarty will warn about this)
1806   }
1809 function create_revision($revision_file, $revision)
1811   $result= false;
1813   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1814     if($fh= fopen($revision_file, "w")) {
1815       if(fwrite($fh, $revision)) {
1816         $result= true;
1817       }
1818     }
1819     fclose($fh);
1820   } else {
1821     print_red("Can not write to revision file");
1822   }
1824   return $result;
1827 function compare_revision($revision_file, $revision)
1829   // false means revision differs
1830   $result= false;
1832   if(file_exists($revision_file) && is_readable($revision_file)) {
1833     // Open file
1834     if($fh= fopen($revision_file, "r")) {
1835       // Compare File contents with current revision
1836       if($revision == fread($fh, filesize($revision_file))) {
1837         $result= true;
1838       }
1839     } else {
1840       print_red("Can not open revision file");
1841     }
1842     // Close file
1843     fclose($fh);
1844   }
1846   return $result;
1849 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1851   $str = ""; // Our return value will be saved in this var
1853   $color  = dechex($percentage+150);
1854   $color2 = dechex(150 - $percentage);
1855   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1857   $progress = (int)(($percentage /100)*$width);
1859   /* Abort printing out percentage, if divs are to small */
1862   /* If theres a better solution for this, use it... */
1863   $str = "
1864     <div style=\" width:".($width)."px; 
1865     height:".($height)."px;
1866   background-color:#000000;
1867 padding:1px;\">
1869           <div style=\" width:".($width)."px;
1870         background-color:#$bgcolor;
1871 height:".($height)."px;\">
1873          <div style=\" width:".$progress."px;
1874 height:".$height."px;
1875        background-color:#".$color2.$color2.$color."; \">";
1878        if(($height >10)&&($showvalue)){
1879          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1880            <b>".$percentage."%</b>
1881            </font>";
1882        }
1884        $str.= "</div></div></div>";
1886        return($str);
1890 function array_key_ics($ikey, $items)
1892   /* Gather keys, make them lowercase */
1893   $tmp= array();
1894   foreach ($items as $key => $value){
1895     $tmp[strtolower($key)]= $key;
1896   }
1898   if (isset($tmp[strtolower($ikey)])){
1899     return($tmp[strtolower($ikey)]);
1900   }
1902   return ("");
1906 function array_differs($src, $dst)
1908   /* If the count is differing, the arrays differ */
1909   if (count ($src) != count ($dst)){
1910     return (TRUE);
1911   }
1913   /* So the count is the same - lets check the contents */
1914   $differs= FALSE;
1915   foreach($src as $value){
1916     if (!in_array($value, $dst)){
1917       $differs= TRUE;
1918     }
1919   }
1921   return ($differs);
1925 function saveFilter($a_filter, $values)
1927   if (isset($_POST['regexit'])){
1928     $a_filter["regex"]= $_POST['regexit'];
1930     foreach($values as $type){
1931       if (isset($_POST[$type])) {
1932         $a_filter[$type]= "checked";
1933       } else {
1934         $a_filter[$type]= "";
1935       }
1936     }
1937   }
1939   /* React on alphabet links if needed */
1940   if (isset($_GET['search'])){
1941     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
1942     if ($s == "**"){
1943       $s= "*";
1944     }
1945     $a_filter['regex']= $s;
1946   }
1948   return ($a_filter);
1952 /* Escape all preg_* relevant characters */
1953 function normalizePreg($input)
1955   return (addcslashes($input, '[]()|/.*+-'));
1959 /* Escape all LDAP filter relevant characters */
1960 function normalizeLdap($input)
1962   return (addcslashes($input, '()|'));
1966 /* Resturns the difference between to microtime() results in float  */
1967 function get_MicroTimeDiff($start , $stop)
1969   $a = split("\ ",$start);
1970   $b = split("\ ",$stop);
1972   $secs = $b[1] - $a[1];
1973   $msecs= $b[0] - $a[0]; 
1975   $ret = (float) ($secs+ $msecs);
1976   return($ret);
1980 /* Check if the given department name is valid */
1981 function is_department_name_reserved($name,$base)
1983   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
1984                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
1985                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
1986   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
1988   /* Check if name is one of the reserved names */
1989   if(in_array_ics($name,$reservedName)) {
1990     return(true);
1991   }
1993   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
1994   foreach($follwedNames as $key => $names){
1995     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
1996       return(true);
1997     }
1998   }
1999   return(false);
2003 function get_base_dir()
2005   global $BASE_DIR;
2007   return $BASE_DIR;
2011 function obj_is_readable($dn, $object, $attribute)
2013   global $ui;
2015   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2019 function obj_is_writable($dn, $object, $attribute)
2021   global $ui;
2023   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2027 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2029   /* Initialize variables */
2030   $ret  = array("count" => 0);  // Set count to 0
2031   $next = true;                 // if false, then skip next loops and return
2032   $cnt  = 0;                    // Current number of loops
2033   $max  = 100;                  // Just for security, prevent looops
2034   $ldap = NULL;                 // To check if created result a valid
2035   $keep = "";                   // save last failed parse string
2037   /* Check each parsed dn in ldap ? */
2038   if($config!==NULL && $verify_in_ldap){
2039     $ldap = $config->get_ldap_link();
2040   }
2042   /* Lets start */
2043   $called = false;
2044   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2046     $cnt ++;
2047     if(!preg_match("/,/",$dn)){
2048       $next = false;
2049     }
2050     $object = preg_replace("/[,].*$/","",$dn);
2051     $dn     = preg_replace("/^[^,]+,/","",$dn);
2053     $called = true;
2055     /* Check if current dn is valid */
2056     if($ldap!==NULL){
2057       $ldap->cd($dn);
2058       $ldap->cat($dn,array("dn"));
2059       if($ldap->count()){
2060         $ret[]  = $keep.$object;
2061         $keep   = "";
2062       }else{
2063         $keep  .= $object.",";
2064       }
2065     }else{
2066       $ret[]  = $keep.$object;
2067       $keep   = "";
2068     }
2069   }
2071   /* No dn was posted */
2072   if($cnt == 0 && !empty($dn)){
2073     $ret[] = $dn;
2074   }
2076   /* Append the rest */
2077   $test = $keep.$dn;
2078   if($called && !empty($test)){
2079     $ret[] = $keep.$dn;
2080   }
2081   $ret['count'] = count($ret) - 1;
2083   return($ret);
2086 /* Add "str_split" if this function is missing.
2087  * This function is only available in PHP5
2088  */
2089   if(!function_exists("str_split")){
2090     function str_split($str,$length =1)
2091     {
2092       if($length < 1 ) $length =1;
2094       $ret = array();
2095       for($i = 0 ; $i < strlen($str); $i = $i +$length){
2096         $ret[] = substr($str,$i ,$length);
2097       }
2098       return($ret);
2099     }
2100   }
2103 function get_base_from_hook($dn, $attrib)
2105   global $config;
2107   if (isset($config->current['BASE_HOOK'])){
2108     
2109     /* Call hook script - if present */
2110     $command= $config->current['BASE_HOOK'];
2112     if ($command != ""){
2113       $command.= " '$dn' $attrib";
2114       if (check_command($command)){
2115         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2116         exec($command, $output);
2117         if (preg_match("/^[0-9]+$/", $output[0])){
2118           return ($output[0]);
2119         } else {
2120           print_red(_("Warning - base_hook is not available. Using default base."));
2121           return ($config->current['UIDBASE']);
2122         }
2123       } else {
2124         print_red(_("Warning - base_hook is not available. Using default base."));
2125         return ($config->current['UIDBASE']);
2126       }
2128     } else {
2130       print_red(_("Warning - no base_hook defined. Using default base."));
2131       return ($config->current['UIDBASE']);
2133     }
2134   }
2137 /* Schema validation functions */
2139 function check_schema_version($class, $version)
2141   return preg_match("/\(v$version\)/", $class['DESC']);
2144 function check_schema($cfg,$rfc2307bis = FALSE)
2146   $messages= array();
2148   /* Get objectclasses */
2149   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2150   $objectclasses = $ldap->get_objectclasses();
2151   if(count($objectclasses) == 0){
2152     print_red(_("Can't get schema information from server. No schema check possible!"));
2153   }
2155   /* This is the default block used for each entry.
2156    *  to avoid unset indexes.
2157    */
2158   $def_check = array("REQUIRED_VERSION" => "0",
2159       "SCHEMA_FILES"     => array(),
2160       "CLASSES_REQUIRED" => array(),
2161       "STATUS"           => FALSE,
2162       "IS_MUST_HAVE"     => FALSE,
2163       "MSG"              => "",
2164       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2166   /* The gosa base schema */
2167   $checks['gosaObject'] = $def_check;
2168   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2169   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2170   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2171   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2173   /* GOsa Account class */
2174   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2175   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2176   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2177   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2178   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2180   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2181   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2182   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2183   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2184   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2185   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2187   /* Some other checks */
2188   foreach(array(
2189         "gosaCacheEntry"        => array("version" => "2.4"),
2190         "gosaDepartment"        => array("version" => "2.4"),
2191         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2192         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2193         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2194         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2195         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2196         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2197         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2198         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2199         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2200         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2201         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2202         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2203         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2204         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2205         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2206         "goLdapServer"          => array("version" => "2.4"),
2207         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2208         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2209         "goKrbServer"           => array("version" => "2.4"),
2210         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2211         ) as $name => $values){
2213           $checks[$name] = $def_check;
2214           if(isset($values['version'])){
2215             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2216           }
2217           if(isset($values['file'])){
2218             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2219           }
2220           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2221         }
2222   foreach($checks as $name => $value){
2223     foreach($value['CLASSES_REQUIRED'] as $class){
2225       if(!isset($objectclasses[$name])){
2226         $checks[$name]['STATUS'] = FALSE;
2227         if($value['IS_MUST_HAVE']){
2228           $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2229         }else{
2230           $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2231         }
2232       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2233         $checks[$name]['STATUS'] = FALSE;
2235         if($value['IS_MUST_HAVE']){
2236           $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2237         }else{
2238           $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2239         }
2240       }else{
2241         $checks[$name]['STATUS'] = TRUE;
2242         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2243       }
2244     }
2245   }
2247   $tmp = $objectclasses;
2249   /* The gosa base schema */
2250   $checks['posixGroup'] = $def_check;
2251   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2252   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2253   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2254   $checks['posixGroup']['STATUS']           = TRUE;
2255   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2256   $checks['posixGroup']['MSG']              = "";
2257   $checks['posixGroup']['INFO']             = "";
2259   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2260   if(isset($tmp['posixGroup'])){
2262     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2263       $checks['posixGroup']['STATUS']           = FALSE;
2264       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2265       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2266     }
2267     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2268       $checks['posixGroup']['STATUS']           = FALSE;
2269       $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2270       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2271     }
2272   }
2274   return($checks);
2278 function prepare4mailbody($string)
2280   $string = html_entity_decode($string);
2282   $from = array(
2283                 "/%/",
2284                 "/ /",
2285                 "/\n/",
2286                 "/\r/",
2287                 "/!/",
2288                 "/#/",
2289                 "/\*/",
2290                 "/\//",
2291                 "/</",
2292                 "/>/",
2293                 "/\?/",
2294                 "/\"/");
2296   $to = array(
2297                 "%25",
2298                 "%20",
2299                 "%0A",
2300                 "%0D",
2301                 "%21",
2302                 "%23",
2303                 "%2A",
2304                 "%2F",
2305                 "%3C",
2306                 "%3E",
2307                 "%3F",
2308                 "%22");
2310   $string = preg_replace($from,$to,$string);
2312   return($string);
2318 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2320   $tmp = array(
2321         "de_DE" => "German",
2322         "fr_FR" => "French",
2323         "it_IT" => "Italian",
2324         "es_ES" => "Spanish",
2325         "en_US" => "English",
2326         "nl_NL" => "Dutch",
2327         "pl_PL" => "Polish",
2328         "sv_SE" => "Swedish",
2329         "zh_CN" => "Chinese",
2330         "ru_RU" => "Russian");
2331   
2332   $tmp2= array(
2333         "de_DE" => _("German"),
2334         "fr_FR" => _("French"),
2335         "it_IT" => _("Italian"),
2336         "es_ES" => _("Spanish"),
2337         "en_US" => _("English"),
2338         "nl_NL" => _("Dutch"),
2339         "pl_PL" => _("Polish"),
2340         "sv_SE" => _("Swedish"),
2341         "zh_CN" => _("Chinese"),
2342         "ru_RU" => _("Russian"));
2344   $ret = array();
2345   if($languages_in_own_language){
2347     $old_lang = setlocale(LC_ALL, 0);
2348     foreach($tmp as $key => $name){
2349       $lang = $key.".UTF-8";
2350       setlocale(LC_ALL, $lang);
2351       if($strip_region_tag){
2352         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2353       }else{
2354         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2355       }
2356     }
2357     setlocale(LC_ALL, $old_lang);
2358   }else{
2359     foreach($tmp as $key => $name){
2360       if($strip_region_tag){
2361         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2362       }else{
2363         $ret[$key] = _($name);
2364       }
2365     }
2366   }
2367   return($ret);
2371 /* Returns contents of the given POST variable and check magic quotes settings */
2372 function get_post($name)
2374   if(!isset($_POST[$name])){
2375     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2376     return(FALSE);
2377   }
2378   if(get_magic_quotes_gpc()){
2379     return(stripcslashes($_POST[$name]));
2380   }else{
2381     return($_POST[$name]);
2382   }
2386 /* Check if $ip1 and $ip2 represents a valid IP range 
2387  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2388  */
2389 function is_ip_range($ip1,$ip2)
2391   if(!is_ip($ip1) || !is_ip($ip2)){
2392     return(FALSE);
2393   }else{
2394     $ar1 = split("\.",$ip1);
2395     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2397     $ar2 = split("\.",$ip2);
2398     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2399     return($var1 < $var2);
2400   }
2404 /* Check if the specified IP address $address is inside the given network */
2405 function is_in_network($network, $netmask, $address)
2407   $nw= split('\.', $network);
2408   $nm= split('\.', $netmask);
2409   $ad= split('\.', $address);
2411   /* Generate inverted netmask */
2412   for ($i= 0; $i<4; $i++){
2413     $ni[$i]= 255-$nm[$i];
2414     $la[$i]= $nw[$i] | $ni[$i];
2415   }
2417   /* Transform to integer */
2418   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2419   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2420   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2422   return ($first < $curr&& $last > $curr);
2425 /* Return class name in correct case 
2426  *  mailMethodkolab =>  mailMethodKolab  ( k => K )
2427  */
2428 function get_correct_class_name($cls)
2430   global $class_mapping;
2431   if(isset($class_mapping) && is_array($class_mapping)){
2432     foreach($class_mapping as $class => $file){
2433       if(preg_match("/^".$cls."$/i",$class)){
2434         return($class);
2435       }
2436     }
2437   }
2438   return(FALSE);
2441 // change_password, changes the Password, of the given dn
2442 function change_password ($dn, $password, $mode=0, $hash= "")
2444   global $config;
2445   $newpass= "";
2447   /* Convert to lower. Methods are lowercase */
2448   $hash= strtolower($hash);
2450   // Get all available encryption Methods
2452   // NON STATIC CALL :)
2453   $tmp = new passwordMethod(get_global('config'));
2454   $available = $tmp->get_available_methods();
2456   // read current password entry for $dn, to detect the encryption Method
2457   $ldap       = $config->get_ldap_link();
2458   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2459   $attrs      = $ldap->fetch ();
2461   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2462   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2463     $deactivated = TRUE;
2464   }else{
2465     $deactivated = FALSE;
2466   }
2468   /* Is ensure that clear passwords will stay clear */
2469   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2470     $hash = "clear";
2471   }
2473   // Detect the encryption Method
2474   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2476     /* Check for supported algorithm */
2477     mt_srand((double) microtime()*1000000);
2479     /* Extract used hash */
2480     if ($hash == ""){
2481       $hash= strtolower($matches[1]);
2482     }
2484     $test = new  $available[$hash]($config);
2486   } else {
2487     // User MD5 by default
2488     $hash= "md5";
2489     $test = new  $available['md5']($config);
2490   }
2492   /* Feed password backends with information */
2493   $test->dn= $dn;
2494   $test->attrs= $attrs;
2495   $newpass= $test->generate_hash($password);
2497   // Update shadow timestamp?
2498   if (isset($attrs["shadowLastChange"][0])){
2499     $shadow= (int)(date("U") / 86400);
2500   } else {
2501     $shadow= 0;
2502   }
2504   // Write back modified entry
2505   $ldap->cd($dn);
2506   $attrs= array();
2508   // Not for groups
2509   if ($mode == 0){
2511     if ($shadow != 0){
2512       $attrs['shadowLastChange']= $shadow;
2513     }
2515     // Create SMB Password
2516     $attrs= generate_smb_nt_hash($password);
2517   }
2519  /* Readd ! if user was deactivated */
2520   if($deactivated){
2521     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2522   }
2524   $attrs['userPassword']= array();
2525   $attrs['userPassword']= $newpass;
2527   $ldap->modify($attrs);
2529   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2531   if ($ldap->error != 'Success') {
2532     print_red(sprintf(_("Setting the password failed. LDAP server says '%s'."),
2533           $ldap->get_error()));
2534   } else {
2536     /* Run backend method for change/create */
2537     $test->set_password($password);
2539     /* Find postmodify entries for this class */
2540     $command= $config->search("password", "POSTMODIFY",array('menu'));
2542     if ($command != ""){
2543       /* Walk through attribute list */
2544       $command= preg_replace("/%userPassword/", $password, $command);
2545       $command= preg_replace("/%dn/", $dn, $command);
2547       if (check_command($command)){
2548         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2549         exec($command);
2550       } else {
2551         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2552         print_red ($message);
2553       }
2554     }
2555   }
2557 // Return something like array['sambaLMPassword']= "lalla..."
2558 function generate_smb_nt_hash($password)
2560   global $config;
2561   $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2562   @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2564   exec($tmp, $ar);
2565   flush();
2566   reset($ar);
2567   $hash= current($ar);
2568   if ($hash == "")
2569   {
2570     print_red (_("Setting for SMBHASH in gosa.conf is incorrect! Can't change Samba password."));
2571   }
2572   else
2573   {
2574     list($lm,$nt)= split (":", trim($hash));
2576     if ($config->current['SAMBAVERSION'] == 3)
2577     {
2578       $attrs['sambaLMPassword']= $lm;
2579       $attrs['sambaNTPassword']= $nt;
2580       $attrs['sambaPwdLastSet']= date('U');
2581       $attrs['sambaBadPasswordCount']= "0";
2582       $attrs['sambaBadPasswordTime']= "0";
2583     } else {
2584       $attrs['lmPassword']= $lm;
2585       $attrs['ntPassword']= $nt;
2586       $attrs['pwdLastSet']= date('U');
2587     }
2588     return($attrs);
2589   }
2592 function crypt_single($string,$enc_type )
2594   return( passwordMethod::crypt_single_str($string,$enc_type));
2598 /* This function returns the offset for the default timezone. 
2599  * $stamp is used to detect summer or winter time.
2600  * In case of PHP5, the integrated timezone functions are used.
2601  * For PHP4 we query an array for offset and add summertime hour.
2602  */
2603 function get_default_timezone($stamp = NULL)
2605   global $config;
2606   $tz ="";
2608   /* Default return value if zone could not be detected */
2609   $zone = array("name" => "unconfigured", "value" => 0);
2611   /* Use current timestamp if $stamp is not set */
2612   if($stamp === NULL){
2613     $stamp = time();
2614   }
2616   /* Is there a timezone configured in the gosa configuration (gosa.conf) */
2617   if(isset($config->current['TIMEZONE']) || isset($config->data['MAIN']['TIMEZONE'])){
2619     /* Get zonename */
2620     if(isset($config->current['TIMEZONE'])){
2621       $tz = $config->current['TIMEZONE'];
2622     }else{
2623       $tz = $config->data['MAIN']['TIMEZONE'];
2624     }
2626     if(!@date_default_timezone_set($tz)){
2627       print_red(sprintf(_("The timezone setting \"".$tz."\" in your gosa.conf is not valid. Can not calculate correct timezone offest."),$tz));
2628     }
2629     $tz_delta = date("Z", $stamp);
2630     $tz_delta = $tz_delta / 3600 ;
2631     return(array("name" => $tz, "value" => $tz_delta));
2633   }
2634   return($zone);
2638 /* Return zone informations */
2639 function _get_tz_zones()
2641   $timezones = array(
2642       'Africa/Abidjan' => 0,
2643       'Africa/Accra' => 0,
2644       'Africa/Addis_Ababa' => 10800,
2645       'Africa/Algiers' => 3600,
2646       'Africa/Asmera' => 10800,
2647       'Africa/Bamako' => 0,
2648       'Africa/Bangui' => 3600,
2649       'Africa/Banjul' => 0,
2650       'Africa/Bissau' => 0,
2651       'Africa/Blantyre' => 7200,
2652       'Africa/Brazzaville' => 3600,
2653       'Africa/Bujumbura' => 7200,
2654       'Africa/Cairo' => 7200,
2655       'Africa/Casablanca' => 0,
2656       'Africa/Ceuta' => 3600,
2657       'Africa/Conakry' => 0,
2658       'Africa/Dakar' => 0,
2659       'Africa/Dar_es_Salaam' => 10800,
2660       'Africa/Djibouti' => 10800,
2661       'Africa/Douala' => 3600,
2662       'Africa/El_Aaiun' => 0,
2663       'Africa/Freetown' => 0,
2664       'Africa/Gaborone' => 7200,
2665       'Africa/Harare' => 7200,
2666       'Africa/Johannesburg' => 7200,
2667       'Africa/Kampala' => 10800,
2668       'Africa/Khartoum' => 10800,
2669       'Africa/Kigali' => 7200,
2670       'Africa/Kinshasa' => 3600,
2671       'Africa/Lagos' => 3600,
2672       'Africa/Libreville' => 3600,
2673       'Africa/Lome' => 0,
2674       'Africa/Luanda' => 3600,
2675       'Africa/Lubumbashi' => 7200,
2676       'Africa/Lusaka' => 7200,
2677       'Africa/Malabo' => 3600,
2678       'Africa/Maputo' => 7200,
2679       'Africa/Maseru' => 7200,
2680       'Africa/Mbabane' => 7200,
2681       'Africa/Mogadishu' => 10800,
2682       'Africa/Monrovia' => 0,
2683       'Africa/Nairobi' => 10800,
2684       'Africa/Ndjamena' => 3600,
2685       'Africa/Niamey' => 3600,
2686       'Africa/Nouakchott' => 0,
2687       'Africa/Ouagadougou' => 0,
2688       'Africa/Porto-Novo' => 3600,
2689       'Africa/Sao_Tome' => 0,
2690       'Africa/Timbuktu' => 0,
2691       'Africa/Tripoli' => 7200,
2692       'Africa/Tunis' => 3600,
2693       'Africa/Windhoek' => 3600,
2694       'America/Adak' => -36000,
2695       'America/Anchorage' => -32400,
2696       'America/Anguilla' => -14400,
2697       'America/Antigua' => -14400,
2698       'America/Araguaina' => -10800,
2699       'America/Argentina/Buenos_Aires' => 0,
2700       'America/Argentina/Catamarca' => 0,
2701       'America/Argentina/ComodRivadavia' => 0,
2702       'America/Argentina/Cordoba' => 0,
2703       'America/Argentina/Jujuy' => 0,
2704       'America/Argentina/La_Rioja' => 0,
2705       'America/Argentina/Mendoza' => 0,
2706       'America/Argentina/Rio_Gallegos' => 0,
2707       'America/Argentina/San_Juan' => 0,
2708       'America/Argentina/Tucuman' => 0,
2709       'America/Argentina/Ushuaia' => 0,
2710       'America/Aruba' => -14400,
2711       'America/Asuncion' => -14400,
2712       'America/Atikokan' => 0,
2713       'America/Atka' => -36000,
2714       'America/Bahia' => 0,
2715       'America/Barbados' => -14400,
2716       'America/Belem' => -10800,
2717       'America/Belize' => -21600,
2718       'America/Blanc-Sablon' => 0,
2719       'America/Boa_Vista' => -14400,
2720       'America/Bogota' => -18000,
2721       'America/Boise' => -25200,
2722       'America/Buenos_Aires' => -10800,
2723       'America/Cambridge_Bay' => -25200,
2724       'America/Campo_Grande' => 0,
2725       'America/Cancun' => -21600,
2726       'America/Caracas' => -14400,
2727       'America/Catamarca' => -10800,
2728       'America/Cayenne' => -10800,
2729       'America/Cayman' => -18000,
2730       'America/Chicago' => -21600,
2731       'America/Chihuahua' => -25200,
2732       'America/Coral_Harbour' => 0,
2733       'America/Cordoba' => -10800,
2734       'America/Costa_Rica' => -21600,
2735       'America/Cuiaba' => -14400,
2736       'America/Curacao' => -14400,
2737       'America/Danmarkshavn' => 0,
2738       'America/Dawson' => -28800,
2739       'America/Dawson_Creek' => -25200,
2740       'America/Denver' => -25200,
2741       'America/Detroit' => -18000,
2742       'America/Dominica' => -14400,
2743       'America/Edmonton' => -25200,
2744       'America/Eirunepe' => -18000,
2745       'America/El_Salvador' => -21600,
2746       'America/Ensenada' => -28800,
2747       'America/Fort_Wayne' => -18000,
2748       'America/Fortaleza' => -10800,
2749       'America/Glace_Bay' => -14400,
2750       'America/Godthab' => -10800,
2751       'America/Goose_Bay' => -14400,
2752       'America/Grand_Turk' => -18000,
2753       'America/Grenada' => -14400,
2754       'America/Guadeloupe' => -14400,
2755       'America/Guatemala' => -21600,
2756       'America/Guayaquil' => -18000,
2757       'America/Guyana' => -14400,
2758       'America/Halifax' => -14400,
2759       'America/Havana' => -18000,
2760       'America/Hermosillo' => -25200,
2761       'America/Indiana/Indianapolis' => -18000,
2762       'America/Indiana/Knox' => -18000,
2763       'America/Indiana/Marengo' => -18000,
2764       'America/Indiana/Petersburg' => 0,
2765       'America/Indiana/Vevay' => -18000,
2766       'America/Indiana/Vincennes' => 0,
2767       'America/Indianapolis' => -18000,
2768       'America/Inuvik' => -25200,
2769       'America/Iqaluit' => -18000,
2770       'America/Jamaica' => -18000,
2771       'America/Jujuy' => -10800,
2772       'America/Juneau' => -32400,
2773       'America/Kentucky/Louisville' => -18000,
2774       'America/Kentucky/Monticello' => -18000,
2775       'America/Knox_IN' => -18000,
2776       'America/La_Paz' => -14400,
2777       'America/Lima' => -18000,
2778       'America/Los_Angeles' => -28800,
2779       'America/Louisville' => -18000,
2780       'America/Maceio' => -10800,
2781       'America/Managua' => -21600,
2782       'America/Manaus' => -14400,
2783       'America/Martinique' => -14400,
2784       'America/Mazatlan' => -25200,
2785       'America/Mendoza' => -10800,
2786       'America/Menominee' => -21600,
2787       'America/Merida' => -21600,
2788       'America/Mexico_City' => -21600,
2789       'America/Miquelon' => -10800,
2790       'America/Moncton' => 0,
2791       'America/Monterrey' => -21600,
2792       'America/Montevideo' => -10800,
2793       'America/Montreal' => -18000,
2794       'America/Montserrat' => -14400,
2795       'America/Nassau' => -18000,
2796       'America/New_York' => -18000,
2797       'America/Nipigon' => -18000,
2798       'America/Nome' => -32400,
2799       'America/Noronha' => -7200,
2800       'America/North_Dakota/Center' => -21600,
2801       'America/North_Dakota/New_Salem' => 0,
2802       'America/Panama' => -18000,
2803       'America/Pangnirtung' => -18000,
2804       'America/Paramaribo' => -10800,
2805       'America/Phoenix' => -25200,
2806       'America/Port-au-Prince' => -18000,
2807       'America/Port_of_Spain' => -14400,
2808       'America/Porto_Acre' => -18000,
2809       'America/Porto_Velho' => -14400,
2810       'America/Puerto_Rico' => -14400,
2811       'America/Rainy_River' => -21600,
2812       'America/Rankin_Inlet' => -21600,
2813       'America/Recife' => -10800,
2814       'America/Regina' => -21600,
2815       'America/Rio_Branco' => -18000,
2816       'America/Rosario' => -10800,
2817       'America/Santiago' => -14400,
2818       'America/Santo_Domingo' => -14400,
2819       'America/Sao_Paulo' => -10800,
2820       'America/Scoresbysund' => -3600,
2821       'America/Shiprock' => -25200,
2822       'America/St_Johns' => -12600,
2823       'America/St_Kitts' => -14400,
2824       'America/St_Lucia' => -14400,
2825       'America/St_Thomas' => -14400,
2826       'America/St_Vincent' => -14400,
2827       'America/Swift_Current' => -21600,
2828       'America/Tegucigalpa' => -21600,
2829       'America/Thule' => -14400,
2830       'America/Thunder_Bay' => -18000,
2831       'America/Tijuana' => -28800,
2832       'America/Toronto' => 0,
2833       'America/Tortola' => -14400,
2834       'America/Vancouver' => -28800,
2835       'America/Virgin' => -14400,
2836       'America/Whitehorse' => -28800,
2837       'America/Winnipeg' => -21600,
2838       'America/Yakutat' => -32400,
2839       'America/Yellowknife' => -25200,
2840       'Antarctica/Casey' => 28800,
2841       'Antarctica/Davis' => 25200,
2842       'Antarctica/DumontDUrville' => 36000,
2843       'Antarctica/Mawson' => 21600,
2844       'Antarctica/McMurdo' => 43200,
2845       'Antarctica/Palmer' => -14400,
2846       'Antarctica/Rothera' => 0,
2847       'Antarctica/South_Pole' => 43200,
2848       'Antarctica/Syowa' => 10800,
2849       'Antarctica/VostokArctic/Longyearbyen' => 0,
2850       'Asia/Aden' => 10800,
2851       'Asia/Almaty' => 21600,
2852       'Asia/Amman' => 7200,
2853       'Asia/Anadyr' => 43200,
2854       'Asia/Aqtau' => 14400,
2855       'Asia/Aqtobe' => 18000,
2856       'Asia/Ashgabat' => 18000,
2857       'Asia/Ashkhabad' => 18000,
2858       'Asia/Baghdad' => 10800,
2859       'Asia/Bahrain' => 10800,
2860       'Asia/Baku' => 14400,
2861       'Asia/Bangkok' => 25200,
2862       'Asia/Beirut' => 7200,
2863       'Asia/Bishkek' => 18000,
2864       'Asia/Brunei' => 28800,
2865       'Asia/Calcutta' => 19800,
2866       'Asia/Choibalsan' => 32400,
2867       'Asia/Chongqing' => 28800,
2868       'Asia/Chungking' => 28800,
2869       'Asia/Colombo' => 21600,
2870       'Asia/Dacca' => 21600,
2871       'Asia/Damascus' => 7200,
2872       'Asia/Dhaka' => 21600,
2873       'Asia/Dili' => 32400,
2874       'Asia/Dubai' => 14400,
2875       'Asia/Dushanbe' => 18000,
2876       'Asia/Gaza' => 7200,
2877       'Asia/Harbin' => 28800,
2878       'Asia/Hong_Kong' => 28800,
2879       'Asia/Hovd' => 25200,
2880       'Asia/Irkutsk' => 28800,
2881       'Asia/Istanbul' => 7200,
2882       'Asia/Jakarta' => 25200,
2883       'Asia/Jayapura' => 32400,
2884       'Asia/Jerusalem' => 7200,
2885       'Asia/Kabul' => 16200,
2886       'Asia/Kamchatka' => 43200,
2887       'Asia/Karachi' => 18000,
2888       'Asia/Kashgar' => 28800,
2889       'Asia/Katmandu' => 20700,
2890       'Asia/Krasnoyarsk' => 25200,
2891       'Asia/Kuala_Lumpur' => 28800,
2892       'Asia/Kuching' => 28800,
2893       'Asia/Kuwait' => 10800,
2894       'Asia/Macao' => 28800,
2895       'Asia/Macau' => 0,
2896       'Asia/Magadan' => 39600,
2897       'Asia/Makassar' => 0,
2898       'Asia/Manila' => 28800,
2899       'Asia/Muscat' => 14400,
2900       'Asia/Nicosia' => 7200,
2901       'Asia/Novosibirsk' => 21600,
2902       'Asia/Omsk' => 21600,
2903       'Asia/Oral' => 0,
2904       'Asia/Phnom_Penh' => 25200,
2905       'Asia/Pontianak' => 25200,
2906       'Asia/Pyongyang' => 32400,
2907       'Asia/Qatar' => 10800,
2908       'Asia/Qyzylorda' => 0,
2909       'Asia/Rangoon' => 23400,
2910       'Asia/Riyadh' => 10800,
2911       'Asia/Saigon' => 25200,
2912       'Asia/Sakhalin' => 36000,
2913       'Asia/Samarkand' => 18000,
2914       'Asia/Seoul' => 32400,
2915       'Asia/Shanghai' => 28800,
2916       'Asia/Singapore' => 28800,
2917       'Asia/Taipei' => 28800,
2918       'Asia/Tashkent' => 18000,
2919       'Asia/Tbilisi' => 14400,
2920       'Asia/Tehran' => 12600,
2921       'Asia/Tel_Aviv' => 7200,
2922       'Asia/Thimbu' => 21600,
2923       'Asia/Thimphu' => 21600,
2924       'Asia/Tokyo' => 32400,
2925       'Asia/Ujung_Pandang' => 28800,
2926       'Asia/Ulaanbaatar' => 28800,
2927       'Asia/Ulan_Bator' => 28800,
2928       'Asia/Urumqi' => 28800,
2929       'Asia/Vientiane' => 25200,
2930       'Asia/Vladivostok' => 36000,
2931       'Asia/Yakutsk' => 32400,
2932       'Asia/Yekaterinburg' => 18000,
2933       'Asia/YerevanAtlantic/Azores' => 0,
2934       'Atlantic/Bermuda' => -14400,
2935       'Atlantic/Canary' => 0,
2936       'Atlantic/Cape_Verde' => -3600,
2937       'Atlantic/Faeroe' => 0,
2938       'Atlantic/Jan_Mayen' => 3600,
2939       'Atlantic/Madeira' => 0,
2940       'Atlantic/Reykjavik' => 0,
2941       'Atlantic/South_Georgia' => -7200,
2942       'Atlantic/St_Helena' => 0,
2943       'Atlantic/Stanley' => -14400,
2944       'Australia/ACT' => 36000,
2945       'Australia/Adelaide' => 34200,
2946       'Australia/Brisbane' => 36000,
2947       'Australia/Broken_Hill' => 34200,
2948       'Australia/Canberra' => 36000,
2949       'Australia/Currie' => 0,
2950       'Australia/Darwin' => 34200,
2951       'Australia/Hobart' => 36000,
2952       'Australia/LHI' => 37800,
2953       'Australia/Lindeman' => 36000,
2954       'Australia/Lord_Howe' => 37800,
2955       'Australia/Melbourne' => 36000,
2956       'Australia/NSW' => 36000,
2957       'Australia/North' => 34200,
2958       'Australia/Perth' => 28800,
2959       'Australia/Queensland' => 36000,
2960       'Australia/South' => 34200,
2961       'Australia/Sydney' => 36000,
2962       'Australia/Tasmania' => 36000,
2963       'Australia/Victoria' => 36000,
2964       'Australia/West' => 28800,
2965       'Australia/Yancowinna' => 34200,
2966       'Europe/Amsterdam' => 3600,
2967       'Europe/Andorra' => 3600,
2968       'Europe/Athens' => 7200,
2969       'Europe/Belfast' => 0,
2970       'Europe/Belgrade' => 3600,
2971       'Europe/Berlin' => 3600,
2972       'Europe/Bratislava' => 3600,
2973       'Europe/Brussels' => 3600,
2974       'Europe/Bucharest' => 7200,
2975       'Europe/Budapest' => 3600,
2976       'Europe/Chisinau' => 7200,
2977       'Europe/Copenhagen' => 3600,
2978       'Europe/Dublin' => 0,
2979       'Europe/Gibraltar' => 3600,
2980       'Europe/Guernsey' => 0,
2981       'Europe/Helsinki' => 7200,
2982       'Europe/Isle_of_Man' => 0,
2983       'Europe/Istanbul' => 7200,
2984       'Europe/Jersey' => 0,
2985       'Europe/Kaliningrad' => 7200,
2986       'Europe/Kiev' => 7200,
2987       'Europe/Lisbon' => 0,
2988       'Europe/Ljubljana' => 3600,
2989       'Europe/London' => 0,
2990       'Europe/Luxembourg' => 3600,
2991       'Europe/Madrid' => 3600,
2992       'Europe/Malta' => 3600,
2993       'Europe/Mariehamn' => 0,
2994       'Europe/Minsk' => 7200,
2995       'Europe/Monaco' => 3600,
2996       'Europe/Moscow' => 10800,
2997       'Europe/Nicosia' => 7200,
2998       'Europe/Oslo' => 3600,
2999       'Europe/Paris' => 3600,
3000       'Europe/Prague' => 3600,
3001       'Europe/Riga' => 7200,
3002       'Europe/Rome' => 3600,
3003       'Europe/Samara' => 14400,
3004       'Europe/San_Marino' => 3600,
3005       'Europe/Sarajevo' => 3600,
3006       'Europe/Simferopol' => 7200,
3007       'Europe/Skopje' => 3600,
3008       'Europe/Sofia' => 7200,
3009       'Europe/Stockholm' => 3600,
3010       'Europe/Tallinn' => 7200,
3011       'Europe/Tirane' => 3600,
3012       'Europe/Tiraspol' => 7200,
3013       'Europe/Uzhgorod' => 7200,
3014       'Europe/Vaduz' => 3600,
3015       'Europe/Vatican' => 3600,
3016       'Europe/Vienna' => 3600,
3017       'Europe/Vilnius' => 7200,
3018       'Europe/Volgograd' => 0,
3019       'Europe/Warsaw' => 3600,
3020       'Europe/Zagreb' => 3600,
3021       'Europe/Zaporozhye' => 7200,
3022       'Europe/Zurich' => 3600,
3023       'Indian/Antananarivo' => 10800,
3024       'Indian/Chagos' => 21600,
3025       'Indian/Christmas' => 25200,
3026       'Indian/Cocos' => 23400,
3027       'Indian/Comoro' => 10800,
3028       'Indian/Kerguelen' => 18000,
3029       'Indian/Mahe' => 14400,
3030       'Indian/Maldives' => 18000,
3031       'Indian/Mauritius' => 14400,
3032       'Indian/Mayotte' => 10800,
3033       'Indian/Reunion' => 14400,
3034       'Pacific/Apia' => -39600,
3035       'Pacific/Auckland' => 43200,
3036       'Pacific/Chatham' => 45900,
3037       'Pacific/Easter' => -21600,
3038       'Pacific/Efate' => 39600,
3039       'Pacific/Enderbury' => 46800,
3040       'Pacific/Fakaofo' => -36000,
3041       'Pacific/Fiji' => 43200,
3042       'Pacific/Funafuti' => 43200,
3043       'Pacific/Galapagos' => -21600,
3044       'Pacific/Gambier' => -32400,
3045       'Pacific/Guadalcanal' => 39600,
3046       'Pacific/Guam' => 36000,
3047       'Pacific/Honolulu' => -36000,
3048       'Pacific/Johnston' => -36000,
3049       'Pacific/Kiritimati' => 50400,
3050       'Pacific/Kosrae' => 39600,
3051       'Pacific/Kwajalein' => 43200,
3052       'Pacific/Majuro' => 43200,
3053       'Pacific/Marquesas' => -34200,
3054       'Pacific/Midway' => -39600,
3055       'Pacific/Nauru' => 43200,
3056       'Pacific/Niue' => -39600,
3057       'Pacific/Norfolk' => 41400,
3058       'Pacific/Noumea' => 39600,
3059       'Pacific/Pago_Pago' => -39600,
3060       'Pacific/Palau' => 32400,
3061       'Pacific/Pitcairn' => -28800,
3062       'Pacific/Ponape' => 39600,
3063       'Pacific/Port_Moresby' => 36000,
3064       'Pacific/Rarotonga' => -36000,
3065       'Pacific/Saipan' => 36000,
3066       'Pacific/Samoa' => -39600,
3067       'Pacific/Tahiti' => -36000,
3068       'Pacific/Tarawa' => 43200,
3069       'Pacific/Tongatapu' => 46800,
3070       'Pacific/Truk' => 36000,
3071       'Pacific/Wake' => 43200,
3072       'Pacific/Wallis' => 43200,
3073       'Pacific/Yap' => 36000 );          
3075   $dst_timezones = array (  
3076       'America/Adak' => 1,
3077       'America/Atka' => 1,
3078       'America/Anchorage' => 1,
3079       'America/Juneau' => 1,
3080       'America/Nome' => 1,
3081       'America/Yakutat' => 1,
3082       'America/Dawson' => 1,
3083       'America/Ensenada' => 1,
3084       'America/Los_Angeles' => 1,
3085       'America/Tijuana' => 1,
3086       'America/Vancouver' => 1,
3087       'America/Whitehorse' => 1,
3088       'America/Boise' => 1,
3089       'America/Cambridge_Bay' => 1,
3090       'America/Chihuahua' => 1,
3091       'America/Denver' => 1,
3092       'America/Edmonton' => 1,
3093       'America/Inuvik' => 1,
3094       'America/Mazatlan' => 1,
3095       'America/Shiprock' => 1,
3096       'America/Yellowknife' => 1,
3097       'America/Cancun' => 1,
3098       'America/Chicago' => 1,
3099       'America/Menominee' => 1,
3100       'America/Merida' => 1,
3101       'America/Monterrey' => 1,
3102       'America/North_Dakota/Center' => 1,
3103       'America/Rainy_River' => 1,
3104       'America/Rankin_Inlet' => 1,
3105       'America/Winnipeg' => 1,
3106       'Pacific/Easter' => 1,
3107       'America/Detroit' => 1,
3108       'America/Grand_Turk' => 1,
3109       'America/Havana' => 1,
3110       'America/Iqaluit' => 1,
3111       'America/Kentucky/Louisville' => 1,
3112       'America/Kentucky/Monticello' => 1,
3113       'America/Louisville' => 1,
3114       'America/Montreal' => 1,
3115       'America/Nassau' => 1,
3116       'America/New_York' => 1,
3117       'America/Nipigon' => 1,
3118       'America/Pangnirtung' => 1,
3119       'America/Thunder_Bay' => 1,
3120       'America/Asuncion' => 1,
3121       'America/Cuiaba' => 1,
3122       'America/Glace_Bay' => 1,
3123       'America/Goose_Bay' => 1,
3124       'America/Halifax' => 1,
3125       'America/Santiago' => 1,
3126       'Antarctica/Palmer' => 1,
3127       'Atlantic/Bermuda' => 1,
3128       'Atlantic/Stanley' => 1,
3129       'America/St_Johns' => 1,
3130       'America/Araguaina' => 1,
3131       'America/Fortaleza' => 1,
3132       'America/Godthab' => 1,
3133       'America/Maceio' => 1,
3134       'America/Miquelon' => 1,
3135       'America/Recife' => 1,
3136       'America/Sao_Paulo' => 1,
3137       'America/Scoresbysund' => 1,
3138       'Atlantic/Canary' => 1,
3139       'Atlantic/Faeroe' => 1,
3140       'Atlantic/Madeira' => 1,
3141       'Europe/Belfast' => 1,
3142       'Europe/Dublin' => 1,
3143       'Europe/Lisbon' => 1,
3144       'Europe/London' => 1,
3145       'Africa/Ceuta' => 1,
3146       'Africa/Windhoek' => 1,
3147       'Atlantic/Jan_Mayen' => 1,
3148       'Europe/Amsterdam' => 1,
3149       'Europe/Andorra' => 1,
3150       'Europe/Belgrade' => 1,
3151       'Europe/Berlin' => 1,
3152       'Europe/Bratislava' => 1,
3153       'Europe/Brussels' => 1,
3154       'Europe/Budapest' => 1,
3155       'Europe/Copenhagen' => 1,
3156       'Europe/Gibraltar' => 1,
3157       'Europe/Ljubljana' => 1,
3158       'Europe/Luxembourg' => 1,
3159       'Europe/Madrid' => 1,
3160       'Europe/Malta' => 1,
3161       'Europe/Monaco' => 1,
3162       'Europe/Oslo' => 1,
3163       'Europe/Paris' => 1,
3164       'Europe/Prague' => 1,
3165       'Europe/Rome' => 1,
3166       'Europe/San_Marino' => 1,
3167       'Europe/Sarajevo' => 1,
3168       'Europe/Skopje' => 1,
3169       'Europe/Stockholm' => 1,
3170       'Europe/Tirane' => 1,
3171       'Europe/Vaduz' => 1,
3172       'Europe/Vatican' => 1,
3173       'Europe/Vienna' => 1,
3174       'Europe/Warsaw' => 1,
3175       'Europe/Zagreb' => 1,
3176       'Europe/Zurich' => 1,
3177       'Africa/Cairo' => 1,
3178       'Asia/Amman' => 1,
3179       'Asia/Beirut' => 1,
3180       'Asia/Damascus' => 1,
3181       'Asia/Gaza' => 1,
3182       'Asia/Istanbul' => 1,
3183       'Asia/Jerusalem' => 1,
3184       'Asia/Nicosia' => 1,
3185       'Asia/Tel_Aviv' => 1,
3186       'Europe/Athens' => 1,
3187       'Europe/Bucharest' => 1,
3188       'Europe/Chisinau' => 1,
3189       'Europe/Helsinki' => 1,
3190       'Europe/Istanbul' => 1,
3191       'Europe/Kaliningrad' => 1,
3192       'Europe/Kiev' => 1,
3193       'Europe/Minsk' => 1,
3194       'Europe/Nicosia' => 1,
3195       'Europe/Riga' => 1,
3196       'Europe/Simferopol' => 1,
3197       'Europe/Sofia' => 1,
3198       'Europe/Tiraspol' => 1,
3199       'Europe/Uzhgorod' => 1,
3200       'Europe/Zaporozhye' => 1,
3201       'Asia/Baghdad' => 1,
3202       'Europe/Moscow' => 1,
3203       'Asia/Tehran' => 1,
3204       'Asia/Aqtau' => 1,
3205       'Asia/Baku' => 1,
3206       'Asia/Tbilisi' => 1,
3207       'Europe/Samara' => 1,
3208       'Asia/Aqtobe' => 1,
3209       'Asia/Bishkek' => 1,
3210       'Asia/Yekaterinburg' => 1,
3211       'Asia/Almaty' => 1,
3212       'Asia/Novosibirsk' => 1,
3213       'Asia/Omsk' => 1,
3214       'Asia/Krasnoyarsk' => 1,
3215       'Asia/Irkutsk' => 1,
3216       'Asia/Yakutsk' => 1,
3217       'Australia/Adelaide' => 1,
3218       'Australia/Broken_Hill' => 1,
3219       'Australia/South' => 1,
3220       'Australia/Yancowinna' => 1,
3221       'Asia/Sakhalin' => 1,
3222       'Asia/Vladivostok' => 1,
3223       'Australia/ACT' => 1,
3224       'Australia/Canberra' => 1,
3225       'Australia/Hobart' => 1,
3226       'Australia/Melbourne' => 1,
3227       'Australia/NSW' => 1,
3228       'Australia/Sydney' => 1,
3229       'Australia/Tasmania' => 1,
3230       'Australia/Victoria' => 1,
3231       'Australia/LHI' => 1,
3232       'Australia/Lord_Howe' => 1,
3233       'Asia/Magadan' => 1,
3234       'Antarctica/McMurdo' => 1,
3235       'Antarctica/South_Pole' => 1,
3236       'Asia/Anadyr' => 1,
3237       'Asia/Kamchatka' => 1,
3238       'Pacific/Auckland' => 1,
3239       'Pacific/Chatham' => 1,
3240       );  
3241   return(array("TIMEZONES" => $timezones, "DST_ZONES" => $dst_timezones));
3243 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3244 ?>