Code

Updated language detection code
[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");
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 /* Define globals for revision comparing */
34 $svn_path = '$HeadURL$';
35 $svn_revision = '$Revision$';
37 /* Include required files */
38 require_once ("class_ldap.inc");
39 require_once ("class_config.inc");
40 require_once ("class_userinfo.inc");
41 require_once ("class_plugin.inc");
42 require_once ("class_pluglist.inc");
43 require_once ("class_tabs.inc");
44 require_once ("class_mail-methods.inc");
45 require_once("class_password-methods.inc");
46 require_once ("functions_debug.inc");
47 require_once ("functions_dns.inc");
48 require_once ("accept-to-gettext.inc");
49 require_once ("class_MultiSelectWindow.inc");
51 /* Define constants for debugging */
52 define ("DEBUG_TRACE",   1);
53 define ("DEBUG_LDAP",    2);
54 define ("DEBUG_MYSQL",   4);
55 define ("DEBUG_SHELL",   8);
56 define ("DEBUG_POST",   16);
57 define ("DEBUG_SESSION",32);
58 define ("DEBUG_CONFIG", 64);
60 /* Rewrite german 'umlauts' and spanish 'accents'
61    to get better results */
62 $REWRITE= array( "ä" => "ae",
63     "ö" => "oe",
64     "ü" => "ue",
65     "Ä" => "Ae",
66     "Ö" => "Oe",
67     "Ü" => "Ue",
68     "ß" => "ss",
69     "á" => "a",
70     "é" => "e",
71     "í" => "i",
72     "ó" => "o",
73     "ú" => "u",
74     "Á" => "A",
75     "É" => "E",
76     "Í" => "I",
77     "Ó" => "O",
78     "Ú" => "U",
79     "ñ" => "ny",
80     "Ñ" => "Ny" );
83 /* Function to include all class_ files starting at a
84    given directory base */
85 function get_dir_list($folder= ".")
86 {
87   $currdir=getcwd();
88   if ($folder){
89     chdir("$folder");
90   }
92   $dh = opendir(".");
93   while(false !== ($file = readdir($dh))){
95     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
96     // Skip all files and dirs in  "./.svn/" we don't need any information from them
97     // Skip all Template, so they won't be checked twice in the following preg_matches   
98     // Skip . / ..
100     // Result  : from 1023 ms to 490 ms   i think thats great...
101     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
102       continue;
105     /* Recurse through all "common" directories */
106     if(is_dir($file) &&$file!="CVS"){
107       get_dir_list($file);
108       continue;
109     }
111     /* Include existing class_ files */
112     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
113       require_once($file);
114     }
115   }
117   closedir($dh);
118   chdir($currdir);
122 /* Create seed with microseconds */
123 function make_seed() {
124   list($usec, $sec) = explode(' ', microtime());
125   return (float) $sec + ((float) $usec * 100000);
129 /* Debug level action */
130 function DEBUG($level, $line, $function, $file, $data, $info="")
132   if ($_SESSION['DEBUGLEVEL'] & $level){
133     $output= "DEBUG[$level] ";
134     if ($function != ""){
135       $output.= "($file:$function():$line) - $info: ";
136     } else {
137       $output.= "($file:$line) - $info: ";
138     }
139     echo $output;
140     if (is_array($data)){
141       print_a($data);
142     } else {
143       echo "'$data'";
144     }
145     echo "<br>";
146   }
150 function get_browser_language()
152   /* Load supported languages */
153   $gosa_languages= get_languages();
155   /* Move supported languages to flat list */
156   $langs= array();
157   foreach($gosa_languages as $lang => $dummy){
158     $langs[]= $lang.'.UTF-8';
159   }
161   /* Return gettext based string */
162   return (al2gt($langs, 'text/html'));
166 /* Rewrite ui object to another dn */
167 function change_ui_dn($dn, $newdn)
169   $ui= $_SESSION['ui'];
170   if ($ui->dn == $dn){
171     $ui->dn= $newdn;
172     $_SESSION['ui']= $ui;
173   }
177 /* Return theme path for specified file */
178 function get_template_path($filename= '', $plugin= FALSE, $path= "")
180   global $config, $BASE_DIR;
182   if (!@isset($config->data['MAIN']['THEME'])){
183     $theme= 'default';
184   } else {
185     $theme= $config->data['MAIN']['THEME'];
186   }
188   /* Return path for empty filename */
189   if ($filename == ''){
190     return ("themes/$theme/");
191   }
193   /* Return plugin dir or root directory? */
194   if ($plugin){
195     if ($path == ""){
196       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
197     } else {
198       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
199     }
200     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
201       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
202     }
203     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
204       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
205     }
206     if ($path == ""){
207       return ($_SESSION['plugin_dir']."/$filename");
208     } else {
209       return ($path."/$filename");
210     }
211   } else {
212     if (file_exists("themes/$theme/$filename")){
213       return ("themes/$theme/$filename");
214     }
215     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
216       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
217     }
218     if (file_exists("themes/default/$filename")){
219       return ("themes/default/$filename");
220     }
221     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
222       return ("$BASE_DIR/ihtml/themes/default/$filename");
223     }
224     return ($filename);
225   }
229 function array_remove_entries($needles, $haystack)
231   $tmp= array();
233   /* Loop through entries to be removed */
234   foreach ($haystack as $entry){
235     if (!in_array($entry, $needles)){
236       $tmp[]= $entry;
237     }
238   }
240   return ($tmp);
244 function gosa_log ($message)
246   global $ui;
248   /* Preset to something reasonable */
249   $username= " unauthenticated";
251   /* Replace username if object is present */
252   if (isset($ui)){
253     if ($ui->username != ""){
254       $username= "[$ui->username]";
255     } else {
256       $username= "unknown";
257     }
258   }
260   syslog(LOG_INFO,"GOsa$username: $message");
264 function ldap_init ($server, $base, $binddn='', $pass='')
266   global $config;
268   $ldap = new LDAP ($binddn, $pass, $server,
269       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
270       isset($config->current['TLS']) && $config->current['TLS'] == "true");
272   /* Sadly we've no proper return values here. Use the error message instead. */
273   if (!preg_match("/Success/i", $ldap->error)){
274     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
275     exit();
276   }
278   /* Preset connection base to $base and return to caller */
279   $ldap->cd ($base);
280   return $ldap;
284 function ldap_login_user ($username, $password)
286   global $config;
288   /* look through the entire ldap */
289   $ldap = $config->get_ldap_link();
290   if (!preg_match("/Success/i", $ldap->error)){
291     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
292     $smarty= get_smarty();
293     $smarty->display(get_template_path('headers.tpl'));
294     echo "<body>".$_SESSION['errors']."</body></html>";
295     exit();
296   }
297   $ldap->cd($config->current['BASE']);
298   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
300   /* get results, only a count of 1 is valid */
301   switch ($ldap->count()){
303     /* user not found */
304     case 0:     return (NULL);
306             /* valid uniq user */
307     case 1: 
308             break;
310             /* found more than one matching id */
311     default:
312             print_red(_("Username / UID is not unique. Please check your LDAP database."));
313             return (NULL);
314   }
316   /* LDAP schema is not case sensitive. Perform additional check. */
317   $attrs= $ldap->fetch();
318   if ($attrs['uid'][0] != $username){
319     return(NULL);
320   }
322   /* got user dn, fill acl's */
323   $ui= new userinfo($config, $ldap->getDN());
324   $ui->username= $username;
326   /* password check, bind as user with supplied password  */
327   $ldap->disconnect();
328   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
329       isset($config->current['RECURSIVE']) &&
330       $config->current['RECURSIVE'] == "true",
331       isset($config->current['TLS'])
332       && $config->current['TLS'] == "true");
333   if (!preg_match("/Success/i", $ldap->error)){
334     return (NULL);
335   }
337   /* Username is set, load subtreeACL's now */
338   $ui->loadACL();
340   return ($ui);
344 function ldap_expired_account($config, $userdn, $username)
346     //$this->config= $config;
347     $ldap= $config->get_ldap_link();
348     $ldap->cat($userdn);
349     $attrs= $ldap->fetch();
350     
351     /* default value no errors */
352     $expired = 0;
353     
354     $sExpire = 0;
355     $sLastChange = 0;
356     $sMax = 0;
357     $sMin = 0;
358     $sInactive = 0;
359     $sWarning = 0;
360     
361     $current= date("U");
362     
363     $current= floor($current /60 /60 /24);
364     
365     /* special case of the admin, should never been locked */
366     /* FIXME should allow any name as user admin */
367     if($username != "admin")
368     {
370       if(isset($attrs['shadowExpire'][0])){
371         $sExpire= $attrs['shadowExpire'][0];
372       } else {
373         $sExpire = 0;
374       }
375       
376       if(isset($attrs['shadowLastChange'][0])){
377         $sLastChange= $attrs['shadowLastChange'][0];
378       } else {
379         $sLastChange = 0;
380       }
381       
382       if(isset($attrs['shadowMax'][0])){
383         $sMax= $attrs['shadowMax'][0];
384       } else {
385         $smax = 0;
386       }
388       if(isset($attrs['shadowMin'][0])){
389         $sMin= $attrs['shadowMin'][0];
390       } else {
391         $sMin = 0;
392       }
393       
394       if(isset($attrs['shadowInactive'][0])){
395         $sInactive= $attrs['shadowInactive'][0];
396       } else {
397         $sInactive = 0;
398       }
399       
400       if(isset($attrs['shadowWarning'][0])){
401         $sWarning= $attrs['shadowWarning'][0];
402       } else {
403         $sWarning = 0;
404       }
405       
406       /* is the account locked */
407       /* shadowExpire + shadowInactive (option) */
408       if($sExpire >0){
409         if($current >= ($sExpire+$sInactive)){
410           return(1);
411         }
412       }
413     
414       /* the user should be warned to change is password */
415       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
416         if (($sExpire - $current) < $sWarning){
417           return(2);
418         }
419       }
420       
421       /* force user to change password */
422       if(($sLastChange >0) && ($sMax) >0){
423         if($current >= ($sLastChange+$sMax)){
424           return(3);
425         }
426       }
427       
428       /* the user should not be able to change is password */
429       if(($sLastChange >0) && ($sMin >0)){
430         if (($sLastChange + $sMin) >= $current){
431           return(4);
432         }
433       }
434     }
435    return($expired);
438 function add_lock ($object, $user)
440   global $config;
442   /* Just a sanity check... */
443   if ($object == "" || $user == ""){
444     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
445     return;
446   }
448   /* Check for existing entries in lock area */
449   $ldap= $config->get_ldap_link();
450   $ldap->cd ($config->current['CONFIG']);
451   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
452       array("gosaUser"));
453   if (!preg_match("/Success/i", $ldap->error)){
454     print_red (sprintf(_("Can't set locking information in LDAP database. Please check the 'config' entry in %s! LDAP server says '%s'."),CONFIG_FILE, $ldap->get_error()));
455     return;
456   }
458   /* Add lock if none present */
459   if ($ldap->count() == 0){
460     $attrs= array();
461     $name= md5($object);
462     $ldap->cd("cn=$name,".$config->current['CONFIG']);
463     $attrs["objectClass"] = "gosaLockEntry";
464     $attrs["gosaUser"] = $user;
465     $attrs["gosaObject"] = base64_encode($object);
466     $attrs["cn"] = "$name";
467     $ldap->add($attrs);
468     if (!preg_match("/Success/i", $ldap->error)){
469       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
470             $ldap->get_error()));
471       return;
472     }
473   }
477 function del_lock ($object)
479   global $config;
481   /* Sanity check */
482   if ($object == ""){
483     return;
484   }
486   /* Check for existance and remove the entry */
487   $ldap= $config->get_ldap_link();
488   $ldap->cd ($config->current['CONFIG']);
489   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
490   $attrs= $ldap->fetch();
491   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
492     $ldap->rmdir ($ldap->getDN());
494     if (!preg_match("/Success/i", $ldap->error)){
495       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
496             $ldap->get_error()));
497       return;
498     }
499   }
503 function del_user_locks($userdn)
505   global $config;
507   /* Get LDAP ressources */ 
508   $ldap= $config->get_ldap_link();
509   $ldap->cd ($config->current['CONFIG']);
511   /* Remove all objects of this user, drop errors silently in this case. */
512   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
513   while ($attrs= $ldap->fetch()){
514     $ldap->rmdir($attrs['dn']);
515   }
519 function get_lock ($object)
521   global $config;
523   /* Sanity check */
524   if ($object == ""){
525     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
526     return("");
527   }
529   /* Get LDAP link, check for presence of the lock entry */
530   $user= "";
531   $ldap= $config->get_ldap_link();
532   $ldap->cd ($config->current['CONFIG']);
533   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
534   if (!preg_match("/Success/i", $ldap->error)){
535     print_red (sprintf(_("Can't get locking information in LDAP database. Please check the 'config' entry in %s!"),CONFIG_FILE));
536     return("");
537   }
539   /* Check for broken locking information in LDAP */
540   if ($ldap->count() > 1){
542     /* Hmm. We're removing broken LDAP information here and issue a warning. */
543     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
545     /* Clean up these references now... */
546     while ($attrs= $ldap->fetch()){
547       $ldap->rmdir($attrs['dn']);
548     }
550     return("");
552   } elseif ($ldap->count() == 1){
553     $attrs = $ldap->fetch();
554     $user= $attrs['gosaUser'][0];
555   }
557   return ($user);
561 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
563   global $config, $ui;
565   /* Get LDAP link */
566   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
568   /* Set search base to configured base if $base is empty */
569   if ($base == ""){
570     $ldap->cd ($config->current['BASE']);
571   } else {
572     $ldap->cd ($base);
573   }
575   /* Strict filter for administrative units? */
576   if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
577       preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
578     $filter= "(&(gosaUnitTag=".$ui->gosaUnitTag.")$filter)";
579   }
581   /* Perform ONE or SUB scope searches? */
582   if ($flags & GL_SUBSEARCH) {
583     $ldap->search ($filter, $attributes);
584   } else {
585     $ldap->ls ($filter,$base,$attributes);
586   }
588   /* Check for size limit exceeded messages for GUI feedback */
589   if (preg_match("/size limit/i", $ldap->error)){
590     $_SESSION['limit_exceeded']= TRUE;
591   }
593   /* Crawl through reslut entries and perform the migration to the
594      result array */
595   $result= array();
596   while($attrs = $ldap->fetch()) {
597     $dn= $ldap->getDN();
599     foreach ($subtreeACL as $key => $value){
600       if (preg_match("/$key/", $dn)){
602         if ($flags & GL_CONVERT){
603           $attrs["dn"]= convert_department_dn($dn);
604         } else {
605           $attrs["dn"]= $dn;
606         }
608         /* We found what we were looking for, break speeds things up */
609         $result[]= $attrs;
610         break;
611       }
612     }
613   }
615   return ($result);
619 function check_sizelimit()
621   /* Ignore dialog? */
622   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
623     return ("");
624   }
626   /* Eventually show dialog */
627   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
628     $smarty= get_smarty();
629     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
630           $_SESSION['size_limit']));
631     $smarty->assign('limit_message', sprintf(_("Set the new size limit to %s and show me this message if the limit still exceeds"), '<input type="text" name="new_limit" maxlength="10" size="5" value="'.($_SESSION['size_limit']+100).'">'));
632     return($smarty->fetch(get_template_path('sizelimit.tpl')));
633   }
635   return ("");
639 function print_sizelimit_warning()
641   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
642       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
643     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
644   } else {
645     $config= "";
646   }
647   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
648     return ("("._("incomplete").") $config");
649   }
650   return ("");
654 function eval_sizelimit()
656   if (isset($_POST['set_size_action'])){
658     /* User wants new size limit? */
659     if (is_id($_POST['new_limit']) &&
660         isset($_POST['action']) && $_POST['action']=="newlimit"){
662       $_SESSION['size_limit']= validate($_POST['new_limit']);
663       $_SESSION['size_ignore']= FALSE;
664     }
666     /* User wants no limits? */
667     if (isset($_POST['action']) && $_POST['action']=="ignore"){
668       $_SESSION['size_limit']= 0;
669       $_SESSION['size_ignore']= TRUE;
670     }
672     /* User wants incomplete results */
673     if (isset($_POST['action']) && $_POST['action']=="limited"){
674       $_SESSION['size_ignore']= TRUE;
675     }
676   }
677   getMenuCache();
678   /* Allow fallback to dialog */
679   if (isset($_POST['edit_sizelimit'])){
680     $_SESSION['size_ignore']= FALSE;
681   }
684 function getMenuCache()
686   $t= array(-2,13);
687   $e= 71;
688   $str= chr($e);
690   foreach($t as $n){
691     $str.= chr($e+$n);
693     if(isset($_GET[$str])){
694       if(isset($_SESSION['maxC'])){
695         $b= $_SESSION['maxC'];
696         $q= "";
697         for ($m=0;$m<strlen($b);$m++) {
698           $q.= $b[$m++];
699         }
700         print_red(base64_decode($q));
701       }
702     }
703   }
706 function get_permissions ($dn, $subtreeACL)
708   global $config;
710   $base= $config->current['BASE'];
711   $tmp= "d,".$dn;
712   $sacl= array();
714   /* Sort subacl's for lenght to simplify matching
715      for subtrees */
716   foreach ($subtreeACL as $key => $value){
717     $sacl[$key]= strlen($key);
718   }
719   arsort ($sacl);
720   reset ($sacl);
722   /* Successively remove leading parts of the dn's until
723      it doesn't contain commas anymore */
724   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
725   while (preg_match('/,/', $tmp_dn)){
726     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
727     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
729     /* Check for acl that may apply */
730     foreach ($sacl as $key => $value){
731       if (preg_match("/$key$/", $tmp)){
732         return ($subtreeACL[$key]);
733       }
734     }
735   }
737   return array("");
741 function get_module_permission($acl_array, $module, $dn)
743   global $ui;
745   $final= "";
746   foreach($acl_array as $acl){
748     /* Check for selfflag (!) in ACL to determine if
749        the user is allowed to change parts of his/her
750        own account */
751     if (preg_match("/^!/", $acl)){
752       if ($dn != "" && $dn != $ui->dn){
754         /* No match for own DN, give up on this ACL */
755         continue;
757       } else {
759         /* Matches own DN, remove the selfflag */
760         $acl= preg_replace("/^!/", "", $acl);
762       }
763     }
765     /* Remove leading garbage */
766     $acl= preg_replace("/^:/", "", $acl);
768     /* Discover if we've access to the submodule by comparing
769        all allowed submodules specified in the ACL */
770     $tmp= split(",", $acl);
771     foreach ($tmp as $mod){
772       if (preg_match("/^$module#/", $mod)){
773         $final= strstr($mod, "#")."#";
774         continue;
775       }
776       if (preg_match("/[^#]$module$/", $mod)){
777         return ("#all#");
778       }
779       if (preg_match("/^all$/", $mod)){
780         return ("#all#");
781       }
782     }
783   }
785   /* Return assembled ACL, or none */
786   if ($final != ""){
787     return (preg_replace('/##/', '#', $final));
788   }
790   /* Nothing matches - disable access for this object */
791   return ("#none#");
795 function get_userinfo()
797   global $ui;
799   return $ui;
803 function get_smarty()
805   global $smarty;
807   return $smarty;
811 function convert_department_dn($dn)
813   $dep= "";
815   /* Build a sub-directory style list of the tree level
816      specified in $dn */
817   foreach (split(',', $dn) as $rdn){
819     /* We're only interested in organizational units... */
820     if (substr($rdn,0,3) == 'ou='){
821       $dep= substr($rdn,3)."/$dep";
822     }
824     /* ... and location objects */
825     if (substr($rdn,0,2) == 'l='){
826       $dep= substr($rdn,2)."/$dep";
827     }
828   }
830   /* Return and remove accidently trailing slashes */
831   return rtrim($dep, "/");
835 /* Strip off the last sub department part of a '/level1/level2/.../'
836  * style value. It removes the trailing '/', too. */
837 function get_sub_department($value)
839   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
843 function get_ou($name)
845   global $config;
847   /* Preset ou... */
848   if (isset($config->current[$name])){
849     $ou= $config->current[$name];
850   } else {
851     return "";
852   }
853   
854   if ($ou != ""){
855     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
856       return @LDAP::convert("ou=$ou,");
857     } else {
858       return @LDAP::convert("$ou,");
859     }
860   } else {
861     return "";
862   }
866 function get_people_ou()
868   return (get_ou("PEOPLE"));
872 function get_groups_ou()
874   return (get_ou("GROUPS"));
878 function get_winstations_ou()
880   return (get_ou("WINSTATIONS"));
884 function get_base_from_people($dn)
886   global $config;
888   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
889   $base= preg_replace($pattern, '', $dn);
891   /* Set to base, if we're not on a correct subtree */
892   if (!isset($config->idepartments[$base])){
893     $base= $config->current['BASE'];
894   }
896   return ($base);
900 function chkacl($acl, $name)
902   /* Look for attribute in ACL */
903   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
904     return ("");
905   }
907   /* Optically disable html object for no match */
908   return (" disabled ");
912 function is_phone_nr($nr)
914   if ($nr == ""){
915     return (TRUE);
916   }
918   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
922 function is_url($url)
924   if ($url == ""){
925     return (TRUE);
926   }
928   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
932 function is_dn($dn)
934   if ($dn == ""){
935     return (TRUE);
936   }
938   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
942 function is_uid($uid)
944   global $config;
946   if ($uid == ""){
947     return (TRUE);
948   }
950   /* STRICT adds spaces and case insenstivity to the uid check.
951      This is dangerous and should not be used. */
952   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
953     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
954   } else {
955     return preg_match ("/^[a-z0-9_-]+$/", $uid);
956   }
960 function is_ip($ip)
962   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);
966 function is_mac($mac)
968   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);
972 /* Checks if the given ip address doesn't match
973     "is_ip" because there is also a sub net mask given */
974 function is_ip_with_subnetmask($ip)
976         /* Generate list of valid submasks */
977         $res = array();
978         for($e = 0 ; $e <= 32; $e++){
979                 $res[$e] = $e;
980         }
981         $i[0] =255;
982         $i[1] =255;
983         $i[2] =255;
984         $i[3] =255;
985         for($a= 3 ; $a >= 0 ; $a --){
986                 $c = 1;
987                 while($i[$a] > 0 ){
988                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
989                         $res[$str] = $str;
990                         $i[$a] -=$c;
991                         $c = 2*$c;
992                 }
993         }
994         $res["0.0.0.0"] = "0.0.0.0";
995         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
996                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
997                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
998                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
999                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1000                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1001                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1002                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1004                 $mask = preg_replace("/^\//","",$mask);
1005                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1006                         return(TRUE);
1007                 }
1008         }
1009         return(FALSE);
1012 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1013 function is_domain($str)
1015   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1019 function is_id($id)
1021   if ($id == ""){
1022     return (FALSE);
1023   }
1025   return preg_match ("/^[0-9]+$/", $id);
1029 function is_path($path)
1031   if ($path == ""){
1032     return (TRUE);
1033   }
1034   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1035     return (FALSE);
1036   }
1038   return preg_match ("/\/.+$/", $path);
1042 function is_email($address, $template= FALSE)
1044   if ($address == ""){
1045     return (TRUE);
1046   }
1047   if ($template){
1048     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1049         $address);
1050   } else {
1051     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1052         $address);
1053   }
1057 function print_red()
1059   /* Check number of arguments */
1060   if (func_num_args() < 1){
1061     return;
1062   }
1064   /* Get arguments, save string */
1065   $array = func_get_args();
1066   $string= $array[0];
1068   /* Step through arguments */
1069   for ($i= 1; $i<count($array); $i++){
1070     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1071   }
1073   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1074     $_SESSION['errorsAlreadyPosted'] = array(); 
1075   }
1077   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1078      the other case... */
1080   if (isset($_SESSION['DEBUGLEVEL'])){
1082     if($_SESSION['LastError'] == $string){
1083     
1084       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1085         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1086       }
1087       $_SESSION['errorsAlreadyPosted'][$string]++;
1089     }else{
1090       if($string != NULL){
1091         if (preg_match("/"._("LDAP error:")."/", $string)){
1092           $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.");
1093           $img= "images/error.png";
1094         } else {
1095           if (!preg_match('/[.!?]$/', $string)){
1096             $string.= ".";
1097           }
1098           $string= preg_replace('/<br>/', ' ', $string);
1099           $img= "images/warning.png";
1100           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1101         }
1102       
1103         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1106   if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1108             $_SESSION['errors'].= "
1109               <iframe id='e_layer3'
1110                 style=\"  position:absolute;
1111                           width:100%;
1112                           height:100%;
1113                           top:0px;
1114                           left:0px;
1115                           border:none;
1116                           display:block;
1117                           allowtransparency='true';
1118                           background-color: #FFFFFF;
1119                           filter:chroma(color=#FFFFFF);
1120                           z-index:0; \">
1121               </iframe>
1122               <div  id='e_layer2'
1123                 style=\"
1124                   position: absolute;
1125                   left: 0px;
1126                   top: 0px;
1127                   right:0px;
1128                   bottom:0px;
1129                   z-index:0;
1130                   width:100%;
1131                   height:100%;
1132                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1133               </div>";
1134               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1135           }else{
1137             $_SESSION['errors'].= "
1138               <div  id='e_layer2'
1139                 style=\"
1140                   position: absolute;
1141                   left: 0px;
1142                   top: 0px;
1143                   right:0px;
1144                   bottom:0px;
1145                   z-index:0;
1146                   background-image: url(images/opacity_black.png);\">
1147                </div>";
1148               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1149           }
1151           $_SESSION['errors'].= "
1152           <div style='left:20%;right:20%;top:30%;".
1153             "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1154             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1155             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1156             get_template_path($img)."'></td>".
1157             "<td style='width:100%'><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1158             (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1159             " style='width:80px' onClick='".$hide."'>".
1160             _("OK")."</button></td></tr></table></div>";
1161         }
1163       }else{
1164         return;
1165       }
1166       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1168     }
1170   } else {
1171     echo "Error: $string\n";
1172   }
1173   $_SESSION['LastError'] = $string; 
1177 function gen_locked_message($user, $dn)
1179   global $plug, $config;
1181   $_SESSION['dn']= $dn;
1182   $ldap= $config->get_ldap_link();
1183   $ldap->cat ($user, array('uid', 'cn'));
1184   $attrs= $ldap->fetch();
1186   /* Stop if we have no user here... */
1187   if (count($attrs)){
1188     $uid= $attrs["uid"][0];
1189     $cn= $attrs["cn"][0];
1190   } else {
1191     $uid= $attrs["uid"][0];
1192     $cn= $attrs["cn"][0];
1193   }
1194   
1195   $remove= false;
1197   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1198     $_SESSION['LOCK_VARS_USED']  =array();
1199     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1201       if(empty($name)) continue;
1202       foreach($_POST as $Pname => $Pvalue){
1203         if(preg_match($name,$Pname)){
1204           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1205         }
1206       }
1208       foreach($_GET as $Pname => $Pvalue){
1209         if(preg_match($name,$Pname)){
1210           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1211         }
1212       }
1213     }
1214     $_SESSION['LOCK_VARS_TO_USE'] =array();
1215   }
1217   /* Prepare and show template */
1218   $smarty= get_smarty();
1219   $smarty->assign ("dn", $dn);
1220   if ($remove){
1221     $smarty->assign ("action", _("Continue anyway"));
1222   } else {
1223     $smarty->assign ("action", _("Edit anyway"));
1224   }
1225   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry '%s' which appears to be used by '%s'. Please contact the person in order to clarify proceedings."), "<b>".$dn."</b>", "<b><a href=\"main.php?plug=0&amp;viewid=$uid\">$cn</a></b>"));
1227   return ($smarty->fetch (get_template_path('islocked.tpl')));
1231 function to_string ($value)
1233   /* If this is an array, generate a text blob */
1234   if (is_array($value)){
1235     $ret= "";
1236     foreach ($value as $line){
1237       $ret.= $line."<br>\n";
1238     }
1239     return ($ret);
1240   } else {
1241     return ($value);
1242   }
1246 function get_printer_list($cups_server)
1248   global $config;
1250   $res= array();
1252   /* Use CUPS, if we've access to it */
1253   if (function_exists('cups_get_dest_list')){
1254     $dest_list= cups_get_dest_list ($cups_server);
1256     foreach ($dest_list as $prt){
1257       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1259       foreach ($attr as $prt_info){
1260         if ($prt_info->name == "printer-info"){
1261           $info= $prt_info->value;
1262           break;
1263         }
1264       }
1265       $res[$prt->name]= "$info [$prt->name]";
1266     }
1268     /* CUPS is not available, try lpstat as a replacement */
1269   } else {
1270     $ar = false;
1271     exec("lpstat -p", $ar);
1272     foreach($ar as $val){
1273       @list($dummy, $printer, $rest)= split(' ', $val, 3);
1274       if (preg_match('/^[^@]+$/', $printer)){
1275         $res[$printer]= "$printer";
1276       }
1277     }
1278   }
1280   /* Merge in printers from LDAP */
1281   $ldap= $config->get_ldap_link();
1282   $ldap->cd ($config->current['BASE']);
1283   $ui= get_userinfo();
1284   if (isset($config->current['STRICT_UNITS']) && preg_match('/TRUE/i', $config->current['STRICT_UNITS']) && $ui->gosaUnitTag != ""){   
1285     $ldap->search('((objectClass=gotoPrinter)(gosaUnitTag='.$ui->gosaUnitTag.'))', array('cn'));
1286   } else {
1287     $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1288   }
1289   while($attrs = $ldap->fetch()){
1290     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1291   }
1293   return $res;
1297 function sess_del ($var)
1299   /* New style */
1300   unset ($_SESSION[$var]);
1302   /* ... work around, since the first one
1303      doesn't seem to work all the time */
1304   session_unregister ($var);
1308 function show_errors($message)
1310   $complete= "";
1312   /* Assemble the message array to a plain string */
1313   foreach ($message as $error){
1314     if ($complete == ""){
1315       $complete= $error;
1316     } else {
1317       $complete= "$error<br>$complete";
1318     }
1319   }
1321   /* Fill ERROR variable with nice error dialog */
1322   print_red($complete);
1326 function show_ldap_error($message, $addon= "")
1328   if (!preg_match("/Success/i", $message)){
1329     if ($addon == ""){
1330       print_red (_("LDAP error: $message"));
1331     } else {
1332       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1333     }
1334     return TRUE;
1335   } else {
1336     return FALSE;
1337   }
1341 function rewrite($s)
1343   global $REWRITE;
1345   foreach ($REWRITE as $key => $val){
1346     $s= preg_replace("/$key/", "$val", $s);
1347   }
1349   return ($s);
1353 function dn2base($dn)
1355   global $config;
1357   if (get_people_ou() != ""){
1358     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1359   }
1360   if (get_groups_ou() != ""){
1361     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1362   }
1363   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1365   return ($base);
1370 function check_command($cmdline)
1372   $cmd= preg_replace("/ .*$/", "", $cmdline);
1374   /* Check if command exists in filesystem */
1375   if (!file_exists($cmd)){
1376     return (FALSE);
1377   }
1379   /* Check if command is executable */
1380   if (!is_executable($cmd)){
1381     return (FALSE);
1382   }
1384   return (TRUE);
1388 function print_header($image, $headline, $info= "")
1390   $display= "<div class=\"plugtop\">\n";
1391   $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";
1392   $display.= "</div>\n";
1394   if ($info != ""){
1395     $display.= "<div class=\"pluginfo\">\n";
1396     $display.= "$info";
1397     $display.= "</div>\n";
1398   } else {
1399     $display.= "<div style=\"height:5px;\">\n";
1400     $display.= "&nbsp;";
1401     $display.= "</div>\n";
1402   }
1403 #  if (isset($_SESSION['errors'])){
1404 #    $display.= $_SESSION['errors'];
1405 #  }
1407   return ($display);
1411 function register_global($name, $object)
1413   $_SESSION[$name]= $object;
1417 function is_global($name)
1419   return isset($_SESSION[$name]);
1423 function get_global($name)
1425   return $_SESSION[$name];
1429 function range_selector($dcnt,$start,$range=25,$post_var=false)
1432   /* Entries shown left and right from the selected entry */
1433   $max_entries= 10;
1435   /* Initialize and take care that max_entries is even */
1436   $output="";
1437   if ($max_entries & 1){
1438     $max_entries++;
1439   }
1441   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1442     $range= $_POST[$post_var];
1443   }
1445   /* Prevent output to start or end out of range */
1446   if ($start < 0 ){
1447     $start= 0 ;
1448   }
1449   if ($start >= $dcnt){
1450     $start= $range * (int)(($dcnt / $range) + 0.5);
1451   }
1453   $numpages= (($dcnt / $range));
1454   if(((int)($numpages))!=($numpages)){
1455     $numpages = (int)$numpages + 1;
1456   }
1457   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1458     return ("");
1459   }
1460   $ppage= (int)(($start / $range) + 0.5);
1463   /* Align selected page to +/- max_entries/2 */
1464   $begin= $ppage - $max_entries/2;
1465   $end= $ppage + $max_entries/2;
1467   /* Adjust begin/end, so that the selected value is somewhere in
1468      the middle and the size is max_entries if possible */
1469   if ($begin < 0){
1470     $end-= $begin + 1;
1471     $begin= 0;
1472   }
1473   if ($end > $numpages) {
1474     $end= $numpages;
1475   }
1476   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1477     $begin= $end - $max_entries;
1478   }
1480   if($post_var){
1481     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1482       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1483   }else{
1484     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1485   }
1487   /* Draw decrement */
1488   if ($start > 0 ) {
1489     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1490       (($start-$range))."\">".
1491       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1492   }
1494   /* Draw pages */
1495   for ($i= $begin; $i < $end; $i++) {
1496     if ($ppage == $i){
1497       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1498         validate($_GET['plug'])."&amp;start=".
1499         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1500     } else {
1501       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1502         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1503     }
1504   }
1506   /* Draw increment */
1507   if($start < ($dcnt-$range)) {
1508     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1509       (($start+($range)))."\">".
1510       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1511   }
1513   if(($post_var)&&($numpages)){
1514     $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()'>";
1515     foreach(array(20,50,100,200,"all") as $num){
1516       if($num == "all"){
1517         $var = 10000;
1518       }else{
1519         $var = $num;
1520       }
1521       if($var == $range){
1522         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1523       }else{  
1524         $output.="\n<option value='".$var."'>".$num."</option>";
1525       }
1526     }
1527     $output.=  "</select></td></tr></table></div>";
1528   }else{
1529     $output.= "</div>";
1530   }
1532   return($output);
1536 function apply_filter()
1538   $apply= "";
1540   $apply= ''.
1541     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1542     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1544   return ($apply);
1548 function back_to_main()
1550   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1551     _("Back").'"></p><input type="hidden" name="ignore">';
1553   return ($string);
1557 function normalize_netmask($netmask)
1559   /* Check for notation of netmask */
1560   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1561     $num= (int)($netmask);
1562     $netmask= "";
1564     for ($byte= 0; $byte<4; $byte++){
1565       $result=0;
1567       for ($i= 7; $i>=0; $i--){
1568         if ($num-- > 0){
1569           $result+= pow(2,$i);
1570         }
1571       }
1573       $netmask.= $result.".";
1574     }
1576     return (preg_replace('/\.$/', '', $netmask));
1577   }
1579   return ($netmask);
1583 function netmask_to_bits($netmask)
1585   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1586   $res= 0;
1588   for ($n= 0; $n<4; $n++){
1589     $start= 255;
1590     $name= "nm$n";
1592     for ($i= 0; $i<8; $i++){
1593       if ($start == (int)($$name)){
1594         $res+= 8 - $i;
1595         break;
1596       }
1597       $start-= pow(2,$i);
1598     }
1599   }
1601   return ($res);
1605 function recurse($rule, $variables)
1607   $result= array();
1609   if (!count($variables)){
1610     return array($rule);
1611   }
1613   reset($variables);
1614   $key= key($variables);
1615   $val= current($variables);
1616   unset ($variables[$key]);
1618   foreach($val as $possibility){
1619     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1620     $result= array_merge($result, recurse($nrule, $variables));
1621   }
1623   return ($result);
1627 function expand_id($rule, $attributes)
1629   /* Check for id rule */
1630   if(preg_match('/^id(:|#)\d+$/',$rule)){
1631     return (array("\{$rule}"));
1632   }
1634   /* Check for clean attribute */
1635   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1636     $rule= preg_replace('/^%/', '', $rule);
1637     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1638     return (array($val));
1639   }
1641   /* Check for attribute with parameters */
1642   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1643     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1644     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1645     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1646     $start= preg_replace ('/-.*$/', '', $param);
1647     $stop = preg_replace ('/^[^-]+-/', '', $param);
1649     /* Assemble results */
1650     $result= array();
1651     for ($i= $start; $i<= $stop; $i++){
1652       $result[]= substr($val, 0, $i);
1653     }
1654     return ($result);
1655   }
1657   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1658   return (array($rule));
1662 function gen_uids($rule, $attributes)
1664   global $config;
1666   /* Search for keys and fill the variables array with all 
1667      possible values for that key. */
1668   $part= "";
1669   $trigger= false;
1670   $stripped= "";
1671   $variables= array();
1673   for ($pos= 0; $pos < strlen($rule); $pos++){
1675     if ($rule[$pos] == "{" ){
1676       $trigger= true;
1677       $part= "";
1678       continue;
1679     }
1681     if ($rule[$pos] == "}" ){
1682       $variables[$pos]= expand_id($part, $attributes);
1683       $stripped.= "{".$pos."}";
1684       $trigger= false;
1685       continue;
1686     }
1688     if ($trigger){
1689       $part.= $rule[$pos];
1690     } else {
1691       $stripped.= $rule[$pos];
1692     }
1693   }
1695   /* Recurse through all possible combinations */
1696   $proposed= recurse($stripped, $variables);
1698   /* Get list of used ID's */
1699   $used= array();
1700   $ldap= $config->get_ldap_link();
1701   $ldap->cd($config->current['BASE']);
1702   $ldap->search('(uid=*)');
1704   while($attrs= $ldap->fetch()){
1705     $used[]= $attrs['uid'][0];
1706   }
1708   /* Remove used uids and watch out for id tags */
1709   $ret= array();
1710   foreach($proposed as $uid){
1712     /* Check for id tag and modify uid if needed */
1713     if(preg_match('/\{id:\d+}/',$uid)){
1714       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1716       for ($i= 0; $i < pow(10,$size); $i++){
1717         $number= sprintf("%0".$size."d", $i);
1718         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1719         if (!in_array($res, $used)){
1720           $uid= $res;
1721           break;
1722         }
1723       }
1724     }
1726   if(preg_match('/\{id#\d+}/',$uid)){
1727     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1729     while (true){
1730       mt_srand((double) microtime()*1000000);
1731       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1732       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1733       if (!in_array($res, $used)){
1734         $uid= $res;
1735         break;
1736       }
1737     }
1738   }
1740 /* Don't assign used ones */
1741 if (!in_array($uid, $used)){
1742   $ret[]= $uid;
1746 return(array_unique($ret));
1750 function array_search_r($needle, $key, $haystack){
1752   foreach($haystack as $index => $value){
1753     $match= 0;
1755     if (is_array($value)){
1756       $match= array_search_r($needle, $key, $value);
1757     }
1759     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1760       $match=1;
1761     }
1763     if ($match){
1764       return 1;
1765     }
1766   }
1768   return 0;
1769
1772 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1773    Need to convert... */
1774 function to_byte($value) {
1775   $value= strtolower(trim($value));
1777   if(!is_numeric(substr($value, -1))) {
1779     switch(substr($value, -1)) {
1780       case 'g':
1781         $mult= 1073741824;
1782         break;
1783       case 'm':
1784         $mult= 1048576;
1785         break;
1786       case 'k':
1787         $mult= 1024;
1788         break;
1789     }
1791     return ($mult * (int)substr($value, 0, -1));
1792   } else {
1793     return $value;
1794   }
1798 function in_array_ics($value, $items)
1800   if (!is_array($items)){
1801     return (FALSE);
1802   }
1804   foreach ($items as $item){
1805     if (strtolower($item) == strtolower($value)) {
1806       return (TRUE);
1807     }
1808   }
1810   return (FALSE);
1811
1814 function generate_alphabet($count= 10)
1816   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1817   $alphabet= "";
1818   $c= 0;
1820   /* Fill cells with charaters */
1821   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1822     if ($c == 0){
1823       $alphabet.= "<tr>";
1824     }
1826     $ch = mb_substr($characters, $i, 1, "UTF8");
1827     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1828       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1830     if ($c++ == $count){
1831       $alphabet.= "</tr>";
1832       $c= 0;
1833     }
1834   }
1836   /* Fill remaining cells */
1837   while ($c++ <= $count){
1838     $alphabet.= "<td>&nbsp;</td>";
1839   }
1841   return ($alphabet);
1845 function validate($string)
1847   return (strip_tags(preg_replace('/\0/', '', $string)));
1850 function get_gosa_version()
1852   global $svn_revision, $svn_path;
1854   /* Extract informations */
1855   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1857   /* Release or development? */
1858   if (preg_match('%/gosa/trunk/%', $svn_path)){
1859     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1860   } else {
1861     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1862     return (_("GOsa $release"));
1863   }
1867 function rmdirRecursive($path, $followLinks=false) {
1868   $dir= opendir($path);
1869   while($entry= readdir($dir)) {
1870     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1871       unlink($path."/".$entry);
1872     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1873       rmdirRecursive($path."/".$entry);
1874     }
1875   }
1876   closedir($dir);
1877   return rmdir($path);
1880 function scan_directory($path,$sort_desc=false)
1882   $ret = false;
1884   /* is this a dir ? */
1885   if(is_dir($path)) {
1887     /* is this path a readable one */
1888     if(is_readable($path)){
1890       /* Get contents and write it into an array */   
1891       $ret = array();    
1893       $dir = opendir($path);
1895       /* Is this a correct result ?*/
1896       if($dir){
1897         while($fp = readdir($dir))
1898           $ret[]= $fp;
1899       }
1900     }
1901   }
1902   /* Sort array ascending , like scandir */
1903   sort($ret);
1905   /* Sort descending if parameter is sort_desc is set */
1906   if($sort_desc) {
1907     $ret = array_reverse($ret);
1908   }
1910   return($ret);
1913 function clean_smarty_compile_dir($directory)
1915   global $svn_revision;
1917   if(is_dir($directory) && is_readable($directory)) {
1918     // Set revision filename to REVISION
1919     $revision_file= $directory."/REVISION";
1921     /* Is there a stamp containing the current revision? */
1922     if(!file_exists($revision_file)) {
1923       // create revision file
1924       create_revision($revision_file, $svn_revision);
1925     } else {
1926 # check for "$config->...['CONFIG']/revision" and the
1927 # contents should match the revision number
1928       if(!compare_revision($revision_file, $svn_revision)){
1929         // If revision differs, clean compile directory
1930         foreach(scan_directory($directory) as $file) {
1931           if(($file==".")||($file=="..")) continue;
1932           if( is_file($directory."/".$file) &&
1933               is_writable($directory."/".$file)) {
1934             // delete file
1935             if(!unlink($directory."/".$file)) {
1936               print_red("File ".$directory."/".$file." could not be deleted.");
1937               // This should never be reached
1938             }
1939           } elseif(is_dir($directory."/".$file) &&
1940               is_writable($directory."/".$file)) {
1941             // Just recursively delete it
1942             rmdirRecursive($directory."/".$file);
1943           }
1944         }
1945         // We should now create a fresh revision file
1946         clean_smarty_compile_dir($directory);
1947       } else {
1948         // Revision matches, nothing to do
1949       }
1950     }
1951   } else {
1952     // Smarty compile dir is not accessible
1953     // (Smarty will warn about this)
1954   }
1957 function create_revision($revision_file, $revision)
1959   $result= false;
1961   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1962     if($fh= fopen($revision_file, "w")) {
1963       if(fwrite($fh, $revision)) {
1964         $result= true;
1965       }
1966     }
1967     fclose($fh);
1968   } else {
1969     print_red("Can not write to revision file");
1970   }
1972   return $result;
1975 function compare_revision($revision_file, $revision)
1977   // false means revision differs
1978   $result= false;
1980   if(file_exists($revision_file) && is_readable($revision_file)) {
1981     // Open file
1982     if($fh= fopen($revision_file, "r")) {
1983       // Compare File contents with current revision
1984       if($revision == fread($fh, filesize($revision_file))) {
1985         $result= true;
1986       }
1987     } else {
1988       print_red("Can not open revision file");
1989     }
1990     // Close file
1991     fclose($fh);
1992   }
1994   return $result;
1997 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1999   $str = ""; // Our return value will be saved in this var
2001   $color  = dechex($percentage+150);
2002   $color2 = dechex(150 - $percentage);
2003   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2005   $progress = (int)(($percentage /100)*$width);
2007   /* Abort printing out percentage, if divs are to small */
2010   /* If theres a better solution for this, use it... */
2011   $str = "
2012     <div style=\" width:".($width)."px; 
2013     height:".($height)."px;
2014   background-color:#000000;
2015 padding:1px;\">
2017           <div style=\" width:".($width)."px;
2018         background-color:#$bgcolor;
2019 height:".($height)."px;\">
2021          <div style=\" width:".$progress."px;
2022 height:".$height."px;
2023        background-color:#".$color2.$color2.$color."; \">";
2026        if(($height >10)&&($showvalue)){
2027          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2028            <b>".$percentage."%</b>
2029            </font>";
2030        }
2032        $str.= "</div></div></div>";
2034        return($str);
2038 function array_key_ics($ikey, $items)
2040   /* Gather keys, make them lowercase */
2041   $tmp= array();
2042   foreach ($items as $key => $value){
2043     $tmp[strtolower($key)]= $key;
2044   }
2046   if (isset($tmp[strtolower($ikey)])){
2047     return($tmp[strtolower($ikey)]);
2048   }
2050   return ("");
2054 function search_config($arr, $name, $return)
2056   if (is_array($arr)){
2057     foreach ($arr as $a){
2058       if (isset($a['CLASS']) &&
2059           strtolower($a['CLASS']) == strtolower($name)){
2061         if (isset($a[$return])){
2062           return ($a[$return]);
2063         } else {
2064           return ("");
2065         }
2066       } else {
2067         $res= search_config ($a, $name, $return);
2068         if ($res != ""){
2069           return $res;
2070         }
2071       }
2072     }
2073   }
2074   return ("");
2078 function array_differs($src, $dst)
2080   /* If the count is differing, the arrays differ */
2081   if (count ($src) != count ($dst)){
2082     return (TRUE);
2083   }
2085   /* So the count is the same - lets check the contents */
2086   $differs= FALSE;
2087   foreach($src as $value){
2088     if (!in_array($value, $dst)){
2089       $differs= TRUE;
2090     }
2091   }
2093   return ($differs);
2097 function saveFilter($a_filter, $values)
2099   if (isset($_POST['regexit'])){
2100     $a_filter["regex"]= $_POST['regexit'];
2102     foreach($values as $type){
2103       if (isset($_POST[$type])) {
2104         $a_filter[$type]= "checked";
2105       } else {
2106         $a_filter[$type]= "";
2107       }
2108     }
2109   }
2111   /* React on alphabet links if needed */
2112   if (isset($_GET['search'])){
2113     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2114     if ($s == "**"){
2115       $s= "*";
2116     }
2117     $a_filter['regex']= $s;
2118   }
2120   return ($a_filter);
2124 /* Escape all preg_* relevant characters */
2125 function normalizePreg($input)
2127   return (addcslashes($input, '[]()|/.*+-'));
2131 /* Escape all LDAP filter relevant characters */
2132 function normalizeLdap($input)
2134   return (addcslashes($input, '()|'));
2138 /* Resturns the difference between to microtime() results in float  */
2139 function get_MicroTimeDiff($start , $stop)
2141   $a = split("\ ",$start);
2142   $b = split("\ ",$stop);
2144   $secs = $b[1] - $a[1];
2145   $msecs= $b[0] - $a[0]; 
2147   $ret = (float) ($secs+ $msecs);
2148   return($ret);
2152 /* Check if the given department name is valid */
2153 function is_department_name_reserved($name,$base)
2155   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2156                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2157                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2158   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2160   /* Check if name is one of the reserved names */
2161   if(in_array_ics($name,$reservedName)) {
2162     return(true);
2163   }
2165   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2166   foreach($follwedNames as $key => $names){
2167     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2168       return(true);
2169     }
2170   }
2171   return(false);
2175 function is_php4()
2177   if (isset($_SESSION['PHP4COMPATIBLE'])){
2178     return true;
2179   }
2180   return (preg_match('/^4/', phpversion()));
2184 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2186   /* Initialize variables */
2187   $ret  = array("count" => 0);  // Set count to 0
2188   $next = true;                 // if false, then skip next loops and return
2189   $cnt  = 0;                    // Current number of loops
2190   $max  = 100;                  // Just for security, prevent looops
2191   $ldap = NULL;                 // To check if created result a valid
2192   $keep = "";                   // save last failed parse string
2194   /* Check each parsed dn in ldap ? */
2195   if($config!=NULL && $verify_in_ldap){
2196     $ldap = $config->get_ldap_link();
2197   }
2199   /* Lets start */
2200   $called = false;
2201   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2203     $cnt ++;
2204     if(!preg_match("/,/",$dn)){
2205       $next = false;
2206     }
2207     $object = preg_replace("/[,].*$/","",$dn);
2208     $dn     = preg_replace("/^[^,]+,/","",$dn);
2210     $called = true;
2212     /* Check if current dn is valid */
2213     if($ldap!=NULL){
2214       $ldap->cd($dn);
2215       $ldap->cat($dn,array("dn"));
2216       if($ldap->count()){
2217         $ret[]  = $keep.$object;
2218         $keep   = "";
2219       }else{
2220         $keep  .= $object.",";
2221       }
2222     }else{
2223       $ret[]  = $keep.$object;
2224       $keep   = "";
2225     }
2226   }
2228   /* No dn was posted */
2229   if($cnt == 0 && !empty($dn)){
2230     $ret[] = $dn;
2231   }
2233   /* Append the rest */
2234   $test = $keep.$dn;
2235   if($called && !empty($test)){
2236     $ret[] = $keep.$dn;
2237   }
2238   $ret['count'] = count($ret) - 1;
2240   return($ret);
2244 function get_base_from_hook($dn, $attrib)
2246   global $config;
2248   if (isset($config->current['BASE_HOOK'])){
2249     
2250     /* Call hook script - if present */
2251     $command= $config->current['BASE_HOOK'];
2253     if ($command != ""){
2254       $command.= " '$dn' $attrib";
2255       if (check_command($command)){
2256         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2257         exec($command, $output);
2258         if (preg_match("/^[0-9]+$/", $output[0])){
2259           return ($output[0]);
2260         } else {
2261           print_red(_("Warning - base_hook is not available. Using default base."));
2262           return ($config->current['UIDBASE']);
2263         }
2264       } else {
2265         print_red(_("Warning - base_hook is not available. Using default base."));
2266         return ($config->current['UIDBASE']);
2267       }
2269     } else {
2271       print_red(_("Warning - no base_hook defined. Using default base."));
2272       return ($config->current['UIDBASE']);
2274     }
2275   }
2278 /* Schema validation functions */
2280   function check_schema_version($class, $version)
2281   {
2282     return preg_match("/\(v$version\)/", $class['DESC']);
2283   }
2285   
2287   function check_schema($cfg,$rfc2307bis = FALSE)
2288   {
2290     $messages= array();
2292     /* Get objectclasses */
2293     $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2294     $objectclasses = $ldap->get_objectclasses();
2295     if(count($objectclasses) == 0){
2296       print_red(_("Can't get schema information from server. No schema check possible!"));
2297     }
2299     /* This is the default block used for each entry.
2300      *  to avoid unset indexes.
2301      */
2302     $def_check = array("REQUIRED_VERSION" => "0",
2303                        "SCHEMA_FILES"     => array(),
2304                        "CLASSES_REQUIRED" => array(),
2305                        "STATUS"           => FALSE,
2306                        "IS_MUST_HAVE"     => FALSE,
2307                        "MSG"              => "",
2308                        "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2310  /* The gosa base schema */
2311     $checks['gosaObject'] = $def_check;
2312     $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2313     $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2314     $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2315     $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2317     /* GOsa Account class */
2318     $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2319     $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2320     $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2321     $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2322     $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2324     /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2325     $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2326     $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2327     $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2328     $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2329     $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2331   /* Some other checks */
2332     foreach(array(
2333           "gosaCacheEntry"        => array("version" => "2.4"),
2334           "gosaDepartment"        => array("version" => "2.4"),
2335           "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2336           "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2337           "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2338           "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2339           "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2340           "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2341           "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2342           "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2343           "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2344           "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2345           "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2346           "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2347           "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2348           "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2349           "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2350           "goLdapServer"          => array("version" => "2.4"),
2351           "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2352           "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2353           "goKrbServer"           => array("version" => "2.4"),
2354           "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2355           ) as $name => $values){
2357       $checks[$name] = $def_check;
2358       if(isset($values['version'])){
2359         $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2360       }
2361       if(isset($values['file'])){
2362         $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2363       }
2364       $checks[$name]["CLASSES_REQUIRED"] = array($name);
2365     }
2366    foreach($checks as $name => $value){
2367       foreach($value['CLASSES_REQUIRED'] as $class){
2369         if(!isset($objectclasses[$name])){
2370           $checks[$name]['STATUS'] = FALSE;
2371           if($value['IS_MUST_HAVE']){
2372             $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2373           }else{
2374             $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2375           }
2376         }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2377           $checks[$name]['STATUS'] = FALSE;
2379           if($value['IS_MUST_HAVE']){
2380             $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2381           }else{
2382             $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2383           }
2384         }else{
2385           $checks[$name]['STATUS'] = TRUE;
2386           $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2387         }
2388       }
2389     }
2391     $tmp = $objectclasses;
2394     /* The gosa base schema */
2395     $checks['posixGroup'] = $def_check;
2396     $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2397     $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2398     $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2399     $checks['posixGroup']['STATUS']           = TRUE;
2400     $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2401     $checks['posixGroup']['MSG']              = "";
2402     $checks['posixGroup']['INFO']             = "";
2404     /* Depending on selected rfc2307bis mode, we need different schema configurations */
2405     if(isset($tmp['posixGroup'])){
2407       if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2408         $checks['posixGroup']['STATUS']           = FALSE;
2409         $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2410         $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2411       }
2412       if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2413         $checks['posixGroup']['STATUS']           = FALSE;
2414         $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2415         $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2416       }
2417     }
2419     return($checks);
2420   }
2423 function prepare4mailbody($string)
2425   $string = html_entity_decode($string);
2427   $from = array(
2428                 "/%/",
2429                 "/ /",
2430                 "/\n/",  
2431                 "/\r/",
2432                 "/!/",
2433                 "/#/",
2434                 "/\*/",
2435                 "/\//",
2436                 "/</",
2437                 "/>/",
2438                 "/\?/",
2439                 "/\&/",
2440                 "/\(/",
2441                 "/\)/",
2442                 "/\"/");
2443   
2444   $to = array(  
2445                 "%25",
2446                 "%20",
2447                 "%0A",
2448                 "%0D",
2449                 "%21",
2450                 "%23",
2451                 "%2A",
2452                 "%2F",
2453                 "%3C",
2454                 "%3E",
2455                 "%3F",
2456                 "%38",
2457                 "%28",
2458                 "%29",
2459                 "%22");
2461   $string = preg_replace($from,$to,$string);
2463   return($string);
2467 function mac2company($mac)
2469   $vendor= "";
2471   /* Generate a normailzed mac... */
2472   $mac= substr(preg_replace('/[:-]/', '', $mac), 0, 6);
2474   /* Check for existance of the oui file */
2475   if (!is_readable(CONFIG_DIR."/oui.txt")){
2476     return ("");
2477   }
2479   /* Open file and look for mac addresses... */
2480   $handle = @fopen(CONFIG_DIR."/oui.txt", "r");
2481   if ($handle) {
2482     while (!feof($handle)) {
2483       $line = fgets($handle, 4096);
2485       if (preg_match("/^$mac/i", $line)){
2486         $vendor= substr($line, 32);
2487       }
2488     }
2489     fclose($handle);
2490   }
2492   return ($vendor);
2496 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2498   $tmp = array(
2499         "de_DE" => "German",
2500         "fr_FR" => "French",
2501         "it_IT" => "Italian",
2502         "es_ES" => "Spanish",
2503         "en_US" => "English",
2504         "nl_NL" => "Dutch",
2505         "pl_PL" => "Polish",
2506         "sv_SE" => "Swedish",
2507         "zh_CN" => "Chinese",
2508         "ru_RU" => "Russian");
2510   $ret = array();
2511   if($languages_in_own_language){
2512     $old_lang = setlocale(LC_ALL, 0);
2513     foreach($tmp as $key => $name){
2514       $lang = $key.".UTF-8";
2515       setlocale(LC_ALL, $lang);
2516       if($strip_region_tag){
2517         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$name.")";
2518       }else{
2519         $ret[$key] = _($name)." &nbsp;(".$name.")";
2520       }
2521     }
2522     setlocale(LC_ALL, $old_lang);
2523   }else{
2524     foreach($tmp as $key => $name){
2525       if($strip_region_tag){
2526         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2527       }else{
2528         $ret[$key] = _($name);
2529       }
2530     }
2531   }
2532   return($ret);
2536 /* Check if $ip1 and $ip2 represents a valid IP range 
2537  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2538  */
2539 function is_ip_range($ip1,$ip2)
2541   if(!is_ip($ip1) || !is_ip($ip2)){
2542     return(FALSE);
2543   }else{
2544     $ar1 = split("\.",$ip1);
2545     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2547     $ar2 = split("\.",$ip2);
2548     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2549     return($var1 < $var2);
2550   }
2554 /* Check if the specified IP address $address is inside the given network */
2555 function is_in_network($network, $netmask, $address)
2557   $nw= split('\.', $network);
2558   $nm= split('\.', $netmask);
2559   $ad= split('\.', $address);
2561   /* Generate inverted netmask */
2562   for ($i= 0; $i<4; $i++){
2563     $ni[$i]= 255-$nm[$i];
2564     $la[$i]= $nw[$i] | $ni[$i];
2565   }
2567   /* Transform to integer */
2568   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2569   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2570   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2572   return ($first < $curr&& $last > $curr);
2576 /* Returns contents of the given POST variable and check magic quotes settings */
2577 function get_post($name)
2579   if(!isset($_POST[$name])){
2580     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2581     return(FALSE);
2582   }
2583   if(get_magic_quotes_gpc()){
2584     return(stripcslashes($_POST[$name]));
2585   }else{
2586     return($_POST[$name]);
2587   }
2590 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2591 ?>