Code

* Code cleanup for non pre-defined ttag variable
[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_dhcpPlugin.inc");
43 require_once ("class_pluglist.inc");
44 require_once ("class_tabs.inc");
45 require_once ("class_mail-methods.inc");
46 require_once("class_password-methods.inc");
47 require_once ("functions_debug.inc");
48 require_once ("functions_dns.inc");
49 require_once ("accept-to-gettext.inc");
50 require_once ("class_MultiSelectWindow.inc");
52 /* Define constants for debugging */
53 define ("DEBUG_TRACE",   1);
54 define ("DEBUG_LDAP",    2);
55 define ("DEBUG_MYSQL",   4);
56 define ("DEBUG_SHELL",   8);
57 define ("DEBUG_POST",   16);
58 define ("DEBUG_SESSION",32);
59 define ("DEBUG_CONFIG", 64);
61 /* Rewrite german 'umlauts' and spanish 'accents'
62    to get better results */
63 $REWRITE= array( "ä" => "ae",
64     "ö" => "oe",
65     "ü" => "ue",
66     "Ä" => "Ae",
67     "Ö" => "Oe",
68     "Ü" => "Ue",
69     "ß" => "ss",
70     "á" => "a",
71     "é" => "e",
72     "í" => "i",
73     "ó" => "o",
74     "ú" => "u",
75     "Á" => "A",
76     "É" => "E",
77     "Í" => "I",
78     "Ó" => "O",
79     "Ú" => "U",
80     "ñ" => "ny",
81     "Ñ" => "Ny" );
84 /* Function to include all class_ files starting at a
85    given directory base */
86 function get_dir_list($folder= ".")
87 {
88   $currdir=getcwd();
89   if ($folder){
90     chdir("$folder");
91   }
93   $dh = opendir(".");
94   while(false !== ($file = readdir($dh))){
96     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
97     // Skip all files and dirs in  "./.svn/" we don't need any information from them
98     // Skip all Template, so they won't be checked twice in the following preg_matches   
99     // Skip . / ..
101     // Result  : from 1023 ms to 490 ms   i think thats great...
102     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
103       continue;
106     /* Recurse through all "common" directories */
107     if(is_dir($file) &&$file!="CVS"){
108       get_dir_list($file);
109       continue;
110     }
112     /* Include existing class_ files */
113     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
114       require_once($file);
115     }
116   }
118   closedir($dh);
119   chdir($currdir);
123 /* Create seed with microseconds */
124 function make_seed() {
125   list($usec, $sec) = explode(' ', microtime());
126   return (float) $sec + ((float) $usec * 100000);
130 /* Debug level action */
131 function DEBUG($level, $line, $function, $file, $data, $info="")
133   if ($_SESSION['DEBUGLEVEL'] & $level){
134     $output= "DEBUG[$level] ";
135     if ($function != ""){
136       $output.= "($file:$function():$line) - $info: ";
137     } else {
138       $output.= "($file:$line) - $info: ";
139     }
140     echo $output;
141     if (is_array($data)){
142       print_a($data);
143     } else {
144       echo "'$data'";
145     }
146     echo "<br>";
147   }
151 function get_browser_language()
153   /* Try to use users primary language */
154   global $config;
155   $ui= get_userinfo();
156   if ($ui != NULL){
157     if ($ui->language != ""){
158       return ($ui->language.".UTF-8");
159     }
160   }
162   /* Try to use users primary language */
163   if ($ui != NULL){
164     if ($ui->language != ""){
165       return ($ui->language.".UTF-8");
166     }
167   }
169   /* Load supported languages */
170   $gosa_languages= get_languages();
172   /* Move supported languages to flat list */
173   $langs= array();
174   foreach($gosa_languages as $lang => $dummy){
175     $langs[]= $lang.'.UTF-8';
176   }
178   /* Return gettext based string */
179   return (al2gt($langs, 'text/html'));
183 /* Rewrite ui object to another dn */
184 function change_ui_dn($dn, $newdn)
186   $ui= $_SESSION['ui'];
187   if ($ui->dn == $dn){
188     $ui->dn= $newdn;
189     $_SESSION['ui']= $ui;
190   }
194 /* Return theme path for specified file */
195 function get_template_path($filename= '', $plugin= FALSE, $path= "")
197   global $config, $BASE_DIR;
199   if (!@isset($config->data['MAIN']['THEME'])){
200     $theme= 'default';
201   } else {
202     $theme= $config->data['MAIN']['THEME'];
203   }
205   /* Return path for empty filename */
206   if ($filename == ''){
207     return ("themes/$theme/");
208   }
210   /* Return plugin dir or root directory? */
211   if ($plugin){
212     if ($path == ""){
213       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
214     } else {
215       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
216     }
217     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
218       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
219     }
220     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
221       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
222     }
223     if ($path == ""){
224       return ($_SESSION['plugin_dir']."/$filename");
225     } else {
226       return ($path."/$filename");
227     }
228   } else {
229     if (file_exists("themes/$theme/$filename")){
230       return ("themes/$theme/$filename");
231     }
232     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
233       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
234     }
235     if (file_exists("themes/default/$filename")){
236       return ("themes/default/$filename");
237     }
238     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
239       return ("$BASE_DIR/ihtml/themes/default/$filename");
240     }
241     return ($filename);
242   }
246 function array_remove_entries($needles, $haystack)
248   $tmp= array();
250   /* Loop through entries to be removed */
251   foreach ($haystack as $entry){
252     if (!in_array($entry, $needles)){
253       $tmp[]= $entry;
254     }
255   }
257   return ($tmp);
261 function gosa_log ($message)
263   global $ui;
265   /* Preset to something reasonable */
266   $username= " unauthenticated";
268   /* Replace username if object is present */
269   if (isset($ui)){
270     if ($ui->username != ""){
271       $username= "[$ui->username]";
272     } else {
273       $username= "unknown";
274     }
275   }
277   syslog(LOG_INFO,"GOsa$username: $message");
281 function ldap_init ($server, $base, $binddn='', $pass='')
283   global $config;
285   $ldap = new LDAP ($binddn, $pass, $server,
286       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
287       isset($config->current['TLS']) && $config->current['TLS'] == "true");
289   /* Sadly we've no proper return values here. Use the error message instead. */
290   if (!preg_match("/Success/i", $ldap->error)){
291     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
292     exit();
293   }
295   /* Preset connection base to $base and return to caller */
296   $ldap->cd ($base);
297   return $ldap;
301 function ldap_login_user ($username, $password)
303   global $config;
305   /* look through the entire ldap */
306   $ldap = $config->get_ldap_link();
307   if (!preg_match("/Success/i", $ldap->error)){
308     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
309     $smarty= get_smarty();
310     $smarty->display(get_template_path('headers.tpl'));
311     echo "<body>".$_SESSION['errors']."</body></html>";
312     exit();
313   }
314   $ldap->cd($config->current['BASE']);
315   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
317   /* get results, only a count of 1 is valid */
318   switch ($ldap->count()){
320     /* user not found */
321     case 0:     return (NULL);
323             /* valid uniq user */
324     case 1: 
325             break;
327             /* found more than one matching id */
328     default:
329             print_red(_("Username / UID is not unique. Please check your LDAP database."));
330             return (NULL);
331   }
333   /* LDAP schema is not case sensitive. Perform additional check. */
334   $attrs= $ldap->fetch();
335   if ($attrs['uid'][0] != $username){
336     return(NULL);
337   }
339   /* got user dn, fill acl's */
340   $ui= new userinfo($config, $ldap->getDN());
341   $ui->username= $username;
343   /* password check, bind as user with supplied password  */
344   $ldap->disconnect();
345   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
346       isset($config->current['RECURSIVE']) &&
347       $config->current['RECURSIVE'] == "true",
348       isset($config->current['TLS'])
349       && $config->current['TLS'] == "true");
350   if (!preg_match("/Success/i", $ldap->error)){
351     return (NULL);
352   }
354   /* Username is set, load subtreeACL's now */
355   $ui->loadACL();
357   return ($ui);
361 function ldap_expired_account($config, $userdn, $username)
363     //$this->config= $config;
364     $ldap= $config->get_ldap_link();
365     $ldap->cat($userdn);
366     $attrs= $ldap->fetch();
367     
368     /* default value no errors */
369     $expired = 0;
370     
371     $sExpire = 0;
372     $sLastChange = 0;
373     $sMax = 0;
374     $sMin = 0;
375     $sInactive = 0;
376     $sWarning = 0;
377     
378     $current= date("U");
379     
380     $current= floor($current /60 /60 /24);
381     
382     /* special case of the admin, should never been locked */
383     /* FIXME should allow any name as user admin */
384     if($username != "admin")
385     {
387       if(isset($attrs['shadowExpire'][0])){
388         $sExpire= $attrs['shadowExpire'][0];
389       } else {
390         $sExpire = 0;
391       }
392       
393       if(isset($attrs['shadowLastChange'][0])){
394         $sLastChange= $attrs['shadowLastChange'][0];
395       } else {
396         $sLastChange = 0;
397       }
398       
399       if(isset($attrs['shadowMax'][0])){
400         $sMax= $attrs['shadowMax'][0];
401       } else {
402         $smax = 0;
403       }
405       if(isset($attrs['shadowMin'][0])){
406         $sMin= $attrs['shadowMin'][0];
407       } else {
408         $sMin = 0;
409       }
410       
411       if(isset($attrs['shadowInactive'][0])){
412         $sInactive= $attrs['shadowInactive'][0];
413       } else {
414         $sInactive = 0;
415       }
416       
417       if(isset($attrs['shadowWarning'][0])){
418         $sWarning= $attrs['shadowWarning'][0];
419       } else {
420         $sWarning = 0;
421       }
422       
423       /* is the account locked */
424       /* shadowExpire + shadowInactive (option) */
425       if($sExpire >0){
426         if($current >= ($sExpire+$sInactive)){
427           return(1);
428         }
429       }
430     
431       /* the user should be warned to change is password */
432       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
433         if (($sExpire - $current) < $sWarning){
434           return(2);
435         }
436       }
437       
438       /* force user to change password */
439       if(($sLastChange >0) && ($sMax) >0){
440         if($current >= ($sLastChange+$sMax)){
441           return(3);
442         }
443       }
444       
445       /* the user should not be able to change is password */
446       if(($sLastChange >0) && ($sMin >0)){
447         if (($sLastChange + $sMin) >= $current){
448           return(4);
449         }
450       }
451     }
452    return($expired);
455 function add_lock ($object, $user)
457   global $config;
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 %s! LDAP server says '%s'."),CONFIG_FILE, $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   /* Sanity check */
499   if ($object == ""){
500     return;
501   }
503   /* Check for existance and remove the entry */
504   $ldap= $config->get_ldap_link();
505   $ldap->cd ($config->current['CONFIG']);
506   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
507   $attrs= $ldap->fetch();
508   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
509     $ldap->rmdir ($ldap->getDN());
511     if (!preg_match("/Success/i", $ldap->error)){
512       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
513             $ldap->get_error()));
514       return;
515     }
516   }
520 function del_user_locks($userdn)
522   global $config;
524   /* Get LDAP ressources */ 
525   $ldap= $config->get_ldap_link();
526   $ldap->cd ($config->current['CONFIG']);
528   /* Remove all objects of this user, drop errors silently in this case. */
529   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
530   while ($attrs= $ldap->fetch()){
531     $ldap->rmdir($attrs['dn']);
532   }
536 function get_lock ($object)
538   global $config;
540   /* Sanity check */
541   if ($object == ""){
542     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
543     return("");
544   }
546   /* Get LDAP link, check for presence of the lock entry */
547   $user= "";
548   $ldap= $config->get_ldap_link();
549   $ldap->cd ($config->current['CONFIG']);
550   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
551   if (!preg_match("/Success/i", $ldap->error)){
552     print_red (sprintf(_("Can't get locking information in LDAP database. Please check the 'config' entry in %s!"),CONFIG_FILE));
553     return("");
554   }
556   /* Check for broken locking information in LDAP */
557   if ($ldap->count() > 1){
559     /* Hmm. We're removing broken LDAP information here and issue a warning. */
560     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
562     /* Clean up these references now... */
563     while ($attrs= $ldap->fetch()){
564       $ldap->rmdir($attrs['dn']);
565     }
567     return("");
569   } elseif ($ldap->count() == 1){
570     $attrs = $ldap->fetch();
571     $user= $attrs['gosaUser'][0];
572   }
574   return ($user);
578 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
580   global $config, $ui;
582   /* Get LDAP link */
583   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
585   /* Set search base to configured base if $base is empty */
586   if ($base == ""){
587     $ldap->cd ($config->current['BASE']);
588   } else {
589     $ldap->cd ($base);
590   }
592   /* Strict filter for administrative units? */
593   if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
594       preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
595     $filter= "(&(gosaUnitTag=".$ui->gosaUnitTag.")$filter)";
596   }
598   /* Perform ONE or SUB scope searches? */
599   if ($flags & GL_SUBSEARCH) {
600     $ldap->search ($filter, $attributes);
601   } else {
602     $ldap->ls ($filter,$base,$attributes);
603   }
605   /* Check for size limit exceeded messages for GUI feedback */
606   if (preg_match("/size limit/i", $ldap->error)){
607     $_SESSION['limit_exceeded']= TRUE;
608   }
610   /* Crawl through reslut entries and perform the migration to the
611      result array */
612   $result= array();
613   while($attrs = $ldap->fetch()) {
614     $dn= $ldap->getDN();
616     foreach ($subtreeACL as $key => $value){
617       if (preg_match("/$key/", $dn)){
619         if ($flags & GL_CONVERT){
620           $attrs["dn"]= convert_department_dn($dn);
621         } else {
622           $attrs["dn"]= $dn;
623         }
625         /* We found what we were looking for, break speeds things up */
626         $result[]= $attrs;
627         break;
628       }
629     }
630   }
632   return ($result);
636 function check_sizelimit()
638   /* Ignore dialog? */
639   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
640     return ("");
641   }
643   /* Eventually show dialog */
644   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
645     $smarty= get_smarty();
646     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
647           $_SESSION['size_limit']));
648     $smarty->assign('limit_message', sprintf(_("Set the new size limit to %s and show me this message if the limit still exceeds"), '<input type="text" name="new_limit" maxlength="10" size="5" value="'.($_SESSION['size_limit']+100).'">'));
649     return($smarty->fetch(get_template_path('sizelimit.tpl')));
650   }
652   return ("");
656 function print_sizelimit_warning()
658   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
659       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
660     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
661   } else {
662     $config= "";
663   }
664   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
665     return ("("._("incomplete").") $config");
666   }
667   return ("");
671 function eval_sizelimit()
673   if (isset($_POST['set_size_action'])){
675     /* User wants new size limit? */
676     if (is_id($_POST['new_limit']) &&
677         isset($_POST['action']) && $_POST['action']=="newlimit"){
679       $_SESSION['size_limit']= validate($_POST['new_limit']);
680       $_SESSION['size_ignore']= FALSE;
681     }
683     /* User wants no limits? */
684     if (isset($_POST['action']) && $_POST['action']=="ignore"){
685       $_SESSION['size_limit']= 0;
686       $_SESSION['size_ignore']= TRUE;
687     }
689     /* User wants incomplete results */
690     if (isset($_POST['action']) && $_POST['action']=="limited"){
691       $_SESSION['size_ignore']= TRUE;
692     }
693   }
694   getMenuCache();
695   /* Allow fallback to dialog */
696   if (isset($_POST['edit_sizelimit'])){
697     $_SESSION['size_ignore']= FALSE;
698   }
701 function getMenuCache()
703   $t= array(-2,13);
704   $e= 71;
705   $str= chr($e);
707   foreach($t as $n){
708     $str.= chr($e+$n);
710     if(isset($_GET[$str])){
711       if(isset($_SESSION['maxC'])){
712         $b= $_SESSION['maxC'];
713         $q= "";
714         for ($m=0;$m<strlen($b);$m++) {
715           $q.= $b[$m++];
716         }
717         print_red(base64_decode($q));
718       }
719     }
720   }
723 function get_permissions ($dn, $subtreeACL)
725   global $config;
727   $base= $config->current['BASE'];
728   $tmp= "d,".$dn;
729   $sacl= array();
731   /* Sort subacl's for lenght to simplify matching
732      for subtrees */
733   foreach ($subtreeACL as $key => $value){
734     $sacl[$key]= strlen($key);
735   }
736   arsort ($sacl);
737   reset ($sacl);
739   /* Successively remove leading parts of the dn's until
740      it doesn't contain commas anymore */
741   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
742   while (preg_match('/,/', $tmp_dn)){
743     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
744     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
746     /* Check for acl that may apply */
747     foreach ($sacl as $key => $value){
748       if (preg_match("/$key$/", $tmp)){
749         return ($subtreeACL[$key]);
750       }
751     }
752   }
754   return array("");
758 function get_module_permission($acl_array, $module, $dn, $checkTag= TRUE){
759   global $ui, $config;
761   /* Check for strict tagging */
762   $ttag= "";
763   if ($checkTag && isset($config->current['STRICT_UNITS']) &&
764       preg_match('/^(yes|true)$/i', $config->current['STRICT_UNITS']) &&
765       $ui->gosaUnitTag != ""){
766     $size= 0;
767     foreach ($config->tdepartments as $tdn => $tag){
768       if (preg_match("/$tdn$/", $dn)){
769         if (strlen($tdn) > $size){
770           $size= strlen($tdn);
771           $ttag= $tag;
772         }
773       }
774     }
776     /* We have no permission for areas that don't carry our tag */
777     if ($ttag != $ui->gosaUnitTag){
778       return ("#none#");
779     }
780   }
782   $final= "";
783   foreach($acl_array as $acl){
785     /* Check for selfflag (!) in ACL to determine if
786        the user is allowed to change parts of his/her
787        own account */
788     if (preg_match("/^!/", $acl)){
789       if ($dn != "" && $dn != $ui->dn){
791         /* No match for own DN, give up on this ACL */
792         continue;
794       } else {
796         /* Matches own DN, remove the selfflag */
797         $acl= preg_replace("/^!/", "", $acl);
799       }
800     }
802     /* Remove leading garbage */
803     $acl= preg_replace("/^:/", "", $acl);
805     /* Discover if we've access to the submodule by comparing
806        all allowed submodules specified in the ACL */
807     $tmp= split(",", $acl);
808     foreach ($tmp as $mod){
809       if (preg_match("/^$module#/", $mod)){
810         $final= strstr($mod, "#")."#";
811         continue;
812       }
813       if (preg_match("/[^#]$module$/", $mod)){
814         return ("#all#");
815       }
816       if (preg_match("/^all$/", $mod)){
817         return ("#all#");
818       }
819     }
820   }
822   /* Return assembled ACL, or none */
823   if ($final != ""){
824     return (preg_replace('/##/', '#', $final));
825   }
827   /* Nothing matches - disable access for this object */
828   return ("#none#");
832 function get_userinfo()
834   global $ui;
836   return $ui;
840 function get_smarty()
842   global $smarty;
844   return $smarty;
848 function convert_department_dn($dn)
850   $dep= "";
852   /* Build a sub-directory style list of the tree level
853      specified in $dn */
854   foreach (split(',', $dn) as $rdn){
856     /* We're only interested in organizational units... */
857     if (substr($rdn,0,3) == 'ou='){
858       $dep= substr($rdn,3)."/$dep";
859     }
861     /* ... and location objects */
862     if (substr($rdn,0,2) == 'l='){
863       $dep= substr($rdn,2)."/$dep";
864     }
865   }
867   /* Return and remove accidently trailing slashes */
868   return rtrim($dep, "/");
872 /* Strip off the last sub department part of a '/level1/level2/.../'
873  * style value. It removes the trailing '/', too. */
874 function get_sub_department($value)
876   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
880 function get_ou($name)
882   global $config;
884   /* Preset ou... */
885   if (isset($config->current[$name])){
886     $ou= $config->current[$name];
887   } else {
888     return "";
889   }
890   
891   if ($ou != ""){
892     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
893       return @LDAP::convert("ou=$ou,");
894     } else {
895       return @LDAP::convert("$ou,");
896     }
897   } else {
898     return "";
899   }
903 function get_people_ou()
905   return (get_ou("PEOPLE"));
909 function get_groups_ou()
911   return (get_ou("GROUPS"));
915 function get_winstations_ou()
917   return (get_ou("WINSTATIONS"));
921 function get_base_from_people($dn)
923   global $config;
925   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
926   $base= preg_replace($pattern, '', $dn);
928   /* Set to base, if we're not on a correct subtree */
929   if (!isset($config->idepartments[$base])){
930     $base= $config->current['BASE'];
931   }
933   return ($base);
937 function chkacl($acl, $name)
939   /* Look for attribute in ACL */
940   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
941     return ("");
942   }
944   /* Optically disable html object for no match */
945   return (" disabled ");
949 function is_phone_nr($nr)
951   if ($nr == ""){
952     return (TRUE);
953   }
955   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
959 function is_url($url)
961   if ($url == ""){
962     return (TRUE);
963   }
965   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
969 function is_dn($dn)
971   if ($dn == ""){
972     return (TRUE);
973   }
975   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
979 function is_uid($uid)
981   global $config;
983   if ($uid == ""){
984     return (TRUE);
985   }
987   /* STRICT adds spaces and case insenstivity to the uid check.
988      This is dangerous and should not be used. */
989   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
990     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
991   } else {
992     return preg_match ("/^[a-z0-9_-]+$/", $uid);
993   }
997 function is_ip($ip)
999   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);
1003 function is_mac($mac)
1005   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);
1009 /* Checks if the given ip address doesn't match
1010     "is_ip" because there is also a sub net mask given */
1011 function is_ip_with_subnetmask($ip)
1013         /* Generate list of valid submasks */
1014         $res = array();
1015         for($e = 0 ; $e <= 32; $e++){
1016                 $res[$e] = $e;
1017         }
1018         $i[0] =255;
1019         $i[1] =255;
1020         $i[2] =255;
1021         $i[3] =255;
1022         for($a= 3 ; $a >= 0 ; $a --){
1023                 $c = 1;
1024                 while($i[$a] > 0 ){
1025                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
1026                         $res[$str] = $str;
1027                         $i[$a] -=$c;
1028                         $c = 2*$c;
1029                 }
1030         }
1031         $res["0.0.0.0"] = "0.0.0.0";
1032         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1033                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1034                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1035                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
1036                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1037                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1038                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1039                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1041                 $mask = preg_replace("/^\//","",$mask);
1042                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1043                         return(TRUE);
1044                 }
1045         }
1046         return(FALSE);
1049 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1050 function is_domain($str)
1052   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1056 function is_id($id)
1058   if ($id == ""){
1059     return (FALSE);
1060   }
1062   return preg_match ("/^[0-9]+$/", $id);
1066 function is_path($path)
1068   if ($path == ""){
1069     return (TRUE);
1070   }
1071   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1072     return (FALSE);
1073   }
1075   return preg_match ("/\/.+$/", $path);
1079 function is_email($address, $template= FALSE)
1081   if ($address == ""){
1082     return (TRUE);
1083   }
1084   if ($template){
1085     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1086         $address);
1087   } else {
1088     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1089         $address);
1090   }
1094 function print_red()
1096   /* Check number of arguments */
1097   if (func_num_args() < 1){
1098     return;
1099   }
1101   /* Get arguments, save string */
1102   $array = func_get_args();
1103   $string= $array[0];
1105   /* Step through arguments */
1106   for ($i= 1; $i<count($array); $i++){
1107     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1108   }
1110   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1111     $_SESSION['errorsAlreadyPosted'] = array(); 
1112   }
1114   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1115      the other case... */
1117   if (isset($_SESSION['DEBUGLEVEL'])){
1119     if($_SESSION['LastError'] == $string){
1120     
1121       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1122         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1123       }
1124       $_SESSION['errorsAlreadyPosted'][$string]++;
1126     }else{
1127       if($string != NULL){
1128         if (preg_match("/"._("LDAP error:")."/", $string)){
1129           $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.");
1130           $img= "images/error.png";
1131         } else {
1132           if (!preg_match('/[.!?]$/', $string)){
1133             $string.= ".";
1134           }
1135           $string= preg_replace('/<br>/', ' ', $string);
1136           $img= "images/warning.png";
1137           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1138         }
1139       
1140         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1143   if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1145             $_SESSION['errors'].= "
1146               <iframe id='e_layer3'
1147                 style=\"  position:absolute;
1148                           width:100%;
1149                           height:100%;
1150                           top:0px;
1151                           left:0px;
1152                           border:none;
1153                           display:block;
1154                           allowtransparency='true';
1155                           background-color: #FFFFFF;
1156                           filter:chroma(color=#FFFFFF);
1157                           z-index:0; \">
1158               </iframe>
1159               <div  id='e_layer2'
1160                 style=\"
1161                   position: absolute;
1162                   left: 0px;
1163                   top: 0px;
1164                   right:0px;
1165                   bottom:0px;
1166                   z-index:0;
1167                   width:100%;
1168                   height:100%;
1169                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1170               </div>";
1171               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1172           }else{
1174             $_SESSION['errors'].= "
1175               <div  id='e_layer2'
1176                 style=\"
1177                   position: absolute;
1178                   left: 0px;
1179                   top: 0px;
1180                   right:0px;
1181                   bottom:0px;
1182                   z-index:0;
1183                   background-image: url(images/opacity_black.png);\">
1184                </div>";
1185               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1186           }
1188           $_SESSION['errors'].= "
1189           <div style='left:20%;right:20%;top:30%;".
1190             "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1191             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1192             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1193             get_template_path($img)."'></td>".
1194             "<td style='width:100%'><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1195             (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1196             " style='width:80px' onClick='".$hide."'>".
1197             _("OK")."</button></td></tr></table></div>";
1198         }
1200       }else{
1201         return;
1202       }
1203       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1205     }
1207   } else {
1208     echo "Error: $string\n";
1209   }
1210   $_SESSION['LastError'] = $string; 
1214 function gen_locked_message($user, $dn)
1216   global $plug, $config;
1218   $_SESSION['dn']= $dn;
1219   $ldap= $config->get_ldap_link();
1220   $ldap->cat ($user, array('uid', 'cn'));
1221   $attrs= $ldap->fetch();
1223   /* Stop if we have no user here... */
1224   if (count($attrs)){
1225     $uid= $attrs["uid"][0];
1226     $cn= $attrs["cn"][0];
1227   } else {
1228     $uid= $attrs["uid"][0];
1229     $cn= $attrs["cn"][0];
1230   }
1231   
1232   $remove= false;
1234   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1235     $_SESSION['LOCK_VARS_USED']  =array();
1236     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1238       if(empty($name)) continue;
1239       foreach($_POST as $Pname => $Pvalue){
1240         if(preg_match($name,$Pname)){
1241           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1242         }
1243       }
1245       foreach($_GET as $Pname => $Pvalue){
1246         if(preg_match($name,$Pname)){
1247           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1248         }
1249       }
1250     }
1251     $_SESSION['LOCK_VARS_TO_USE'] =array();
1252   }
1254   /* Prepare and show template */
1255   $smarty= get_smarty();
1256   $smarty->assign ("dn", $dn);
1257   if ($remove){
1258     $smarty->assign ("action", _("Continue anyway"));
1259   } else {
1260     $smarty->assign ("action", _("Edit anyway"));
1261   }
1262   $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>"));
1264   return ($smarty->fetch (get_template_path('islocked.tpl')));
1268 function to_string ($value)
1270   /* If this is an array, generate a text blob */
1271   if (is_array($value)){
1272     $ret= "";
1273     foreach ($value as $line){
1274       $ret.= $line."<br>\n";
1275     }
1276     return ($ret);
1277   } else {
1278     return ($value);
1279   }
1283 function get_printer_list($cups_server)
1285   global $config;
1287   $res= array();
1289   /* Use CUPS, if we've access to it */
1290   if (function_exists('cups_get_dest_list')){
1291     $dest_list= cups_get_dest_list ($cups_server);
1293     foreach ($dest_list as $prt){
1294       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1296       foreach ($attr as $prt_info){
1297         if ($prt_info->name == "printer-info"){
1298           $info= $prt_info->value;
1299           break;
1300         }
1301       }
1302       $res[$prt->name]= "$info [$prt->name]";
1303     }
1305     /* CUPS is not available, try lpstat as a replacement */
1306   } else {
1307     $ar = false;
1308     exec("lpstat -p", $ar);
1309     foreach($ar as $val){
1310       @list($dummy, $printer, $rest)= split(' ', $val, 3);
1311       if (preg_match('/^[^@]+$/', $printer)){
1312         $res[$printer]= "$printer";
1313       }
1314     }
1315   }
1317   /* Merge in printers from LDAP */
1318   $ldap= $config->get_ldap_link();
1319   $ldap->cd ($config->current['BASE']);
1320   $ui= get_userinfo();
1321   if (isset($config->current['STRICT_UNITS']) && preg_match('/TRUE/i', $config->current['STRICT_UNITS']) && $ui->gosaUnitTag != ""){   
1322     $ldap->search('((objectClass=gotoPrinter)(gosaUnitTag='.$ui->gosaUnitTag.'))', array('cn'));
1323   } else {
1324     $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1325   }
1326   while($attrs = $ldap->fetch()){
1327     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1328   }
1330   return $res;
1334 function sess_del ($var)
1336   /* New style */
1337   unset ($_SESSION[$var]);
1339   /* ... work around, since the first one
1340      doesn't seem to work all the time */
1341   session_unregister ($var);
1345 function show_errors($message)
1347   $complete= "";
1349   /* Assemble the message array to a plain string */
1350   foreach ($message as $error){
1351     if ($complete == ""){
1352       $complete= $error;
1353     } else {
1354       $complete= "$error<br>$complete";
1355     }
1356   }
1358   /* Fill ERROR variable with nice error dialog */
1359   print_red($complete);
1363 function show_ldap_error($message, $addon= "")
1365   if (!preg_match("/Success/i", $message)){
1366     if ($addon == ""){
1367       print_red (_("LDAP error: $message"));
1368     } else {
1369       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1370     }
1371     return TRUE;
1372   } else {
1373     return FALSE;
1374   }
1378 function rewrite($s)
1380   global $REWRITE;
1382   foreach ($REWRITE as $key => $val){
1383     $s= preg_replace("/$key/", "$val", $s);
1384   }
1386   return ($s);
1390 function dn2base($dn)
1392   global $config;
1394   if (get_people_ou() != ""){
1395     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1396   }
1397   if (get_groups_ou() != ""){
1398     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1399   }
1400   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1402   return ($base);
1407 function check_command($cmdline)
1409   $cmd= preg_replace("/ .*$/", "", $cmdline);
1411   /* Check if command exists in filesystem */
1412   if (!file_exists($cmd)){
1413     return (FALSE);
1414   }
1416   /* Check if command is executable */
1417   if (!is_executable($cmd)){
1418     return (FALSE);
1419   }
1421   return (TRUE);
1425 function print_header($image, $headline, $info= "")
1427   $display= "<div class=\"plugtop\">\n";
1428   $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";
1429   $display.= "</div>\n";
1431   if ($info != ""){
1432     $display.= "<div class=\"pluginfo\">\n";
1433     $display.= "$info";
1434     $display.= "</div>\n";
1435   } else {
1436     $display.= "<div style=\"height:5px;\">\n";
1437     $display.= "&nbsp;";
1438     $display.= "</div>\n";
1439   }
1440 #  if (isset($_SESSION['errors'])){
1441 #    $display.= $_SESSION['errors'];
1442 #  }
1444   return ($display);
1448 function register_global($name, $object)
1450   $_SESSION[$name]= $object;
1454 function is_global($name)
1456   return isset($_SESSION[$name]);
1460 function get_global($name)
1462   return $_SESSION[$name];
1466 function range_selector($dcnt,$start,$range=25,$post_var=false)
1469   /* Entries shown left and right from the selected entry */
1470   $max_entries= 10;
1472   /* Initialize and take care that max_entries is even */
1473   $output="";
1474   if ($max_entries & 1){
1475     $max_entries++;
1476   }
1478   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1479     $range= $_POST[$post_var];
1480   }
1482   /* Prevent output to start or end out of range */
1483   if ($start < 0 ){
1484     $start= 0 ;
1485   }
1486   if ($start >= $dcnt){
1487     $start= $range * (int)(($dcnt / $range) + 0.5);
1488   }
1490   $numpages= (($dcnt / $range));
1491   if(((int)($numpages))!=($numpages)){
1492     $numpages = (int)$numpages + 1;
1493   }
1494   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1495     return ("");
1496   }
1497   $ppage= (int)(($start / $range) + 0.5);
1500   /* Align selected page to +/- max_entries/2 */
1501   $begin= $ppage - $max_entries/2;
1502   $end= $ppage + $max_entries/2;
1504   /* Adjust begin/end, so that the selected value is somewhere in
1505      the middle and the size is max_entries if possible */
1506   if ($begin < 0){
1507     $end-= $begin + 1;
1508     $begin= 0;
1509   }
1510   if ($end > $numpages) {
1511     $end= $numpages;
1512   }
1513   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1514     $begin= $end - $max_entries;
1515   }
1517   if($post_var){
1518     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1519       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1520   }else{
1521     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1522   }
1524   /* Draw decrement */
1525   if ($start > 0 ) {
1526     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1527       (($start-$range))."\">".
1528       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1529   }
1531   /* Draw pages */
1532   for ($i= $begin; $i < $end; $i++) {
1533     if ($ppage == $i){
1534       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1535         validate($_GET['plug'])."&amp;start=".
1536         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1537     } else {
1538       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1539         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1540     }
1541   }
1543   /* Draw increment */
1544   if($start < ($dcnt-$range)) {
1545     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1546       (($start+($range)))."\">".
1547       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1548   }
1550   if(($post_var)&&($numpages)){
1551     $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()'>";
1552     foreach(array(20,50,100,200,"all") as $num){
1553       if($num == "all"){
1554         $var = 10000;
1555       }else{
1556         $var = $num;
1557       }
1558       if($var == $range){
1559         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1560       }else{  
1561         $output.="\n<option value='".$var."'>".$num."</option>";
1562       }
1563     }
1564     $output.=  "</select></td></tr></table></div>";
1565   }else{
1566     $output.= "</div>";
1567   }
1569   return($output);
1573 function apply_filter()
1575   $apply= "";
1577   $apply= ''.
1578     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1579     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1581   return ($apply);
1585 function back_to_main()
1587   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1588     _("Back").'"></p><input type="hidden" name="ignore">';
1590   return ($string);
1594 function normalize_netmask($netmask)
1596   /* Check for notation of netmask */
1597   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1598     $num= (int)($netmask);
1599     $netmask= "";
1601     for ($byte= 0; $byte<4; $byte++){
1602       $result=0;
1604       for ($i= 7; $i>=0; $i--){
1605         if ($num-- > 0){
1606           $result+= pow(2,$i);
1607         }
1608       }
1610       $netmask.= $result.".";
1611     }
1613     return (preg_replace('/\.$/', '', $netmask));
1614   }
1616   return ($netmask);
1620 function netmask_to_bits($netmask)
1622   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1623   $res= 0;
1625   for ($n= 0; $n<4; $n++){
1626     $start= 255;
1627     $name= "nm$n";
1629     for ($i= 0; $i<8; $i++){
1630       if ($start == (int)($$name)){
1631         $res+= 8 - $i;
1632         break;
1633       }
1634       $start-= pow(2,$i);
1635     }
1636   }
1638   return ($res);
1642 function recurse($rule, $variables)
1644   $result= array();
1646   if (!count($variables)){
1647     return array($rule);
1648   }
1650   reset($variables);
1651   $key= key($variables);
1652   $val= current($variables);
1653   unset ($variables[$key]);
1655   foreach($val as $possibility){
1656     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1657     $result= array_merge($result, recurse($nrule, $variables));
1658   }
1660   return ($result);
1664 function expand_id($rule, $attributes)
1666   /* Check for id rule */
1667   if(preg_match('/^id(:|#)\d+$/',$rule)){
1668     return (array("\{$rule}"));
1669   }
1671   /* Check for clean attribute */
1672   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1673     $rule= preg_replace('/^%/', '', $rule);
1674     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1675     return (array($val));
1676   }
1678   /* Check for attribute with parameters */
1679   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1680     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1681     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1682     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1683     $start= preg_replace ('/-.*$/', '', $param);
1684     $stop = preg_replace ('/^[^-]+-/', '', $param);
1686     /* Assemble results */
1687     $result= array();
1688     for ($i= $start; $i<= $stop; $i++){
1689       $result[]= substr($val, 0, $i);
1690     }
1691     return ($result);
1692   }
1694   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1695   return (array($rule));
1699 function gen_uids($rule, $attributes)
1701   global $config;
1703   /* Search for keys and fill the variables array with all 
1704      possible values for that key. */
1705   $part= "";
1706   $trigger= false;
1707   $stripped= "";
1708   $variables= array();
1710   for ($pos= 0; $pos < strlen($rule); $pos++){
1712     if ($rule[$pos] == "{" ){
1713       $trigger= true;
1714       $part= "";
1715       continue;
1716     }
1718     if ($rule[$pos] == "}" ){
1719       $variables[$pos]= expand_id($part, $attributes);
1720       $stripped.= "{".$pos."}";
1721       $trigger= false;
1722       continue;
1723     }
1725     if ($trigger){
1726       $part.= $rule[$pos];
1727     } else {
1728       $stripped.= $rule[$pos];
1729     }
1730   }
1732   /* Recurse through all possible combinations */
1733   $proposed= recurse($stripped, $variables);
1735   /* Get list of used ID's */
1736   $used= array();
1737   $ldap= $config->get_ldap_link();
1738   $ldap->cd($config->current['BASE']);
1739   $ldap->search('(uid=*)');
1741   while($attrs= $ldap->fetch()){
1742     $used[]= $attrs['uid'][0];
1743   }
1745   /* Remove used uids and watch out for id tags */
1746   $ret= array();
1747   foreach($proposed as $uid){
1749     /* Check for id tag and modify uid if needed */
1750     if(preg_match('/\{id:\d+}/',$uid)){
1751       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1753       for ($i= 0; $i < pow(10,$size); $i++){
1754         $number= sprintf("%0".$size."d", $i);
1755         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1756         if (!in_array($res, $used)){
1757           $uid= $res;
1758           break;
1759         }
1760       }
1761     }
1763   if(preg_match('/\{id#\d+}/',$uid)){
1764     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1766     while (true){
1767       mt_srand((double) microtime()*1000000);
1768       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1769       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1770       if (!in_array($res, $used)){
1771         $uid= $res;
1772         break;
1773       }
1774     }
1775   }
1777 /* Don't assign used ones */
1778 if (!in_array($uid, $used)){
1779   $ret[]= $uid;
1783 return(array_unique($ret));
1787 function array_search_r($needle, $key, $haystack){
1789   foreach($haystack as $index => $value){
1790     $match= 0;
1792     if (is_array($value)){
1793       $match= array_search_r($needle, $key, $value);
1794     }
1796     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1797       $match=1;
1798     }
1800     if ($match){
1801       return 1;
1802     }
1803   }
1805   return 0;
1806
1809 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1810    Need to convert... */
1811 function to_byte($value) {
1812   $value= strtolower(trim($value));
1814   if(!is_numeric(substr($value, -1))) {
1816     switch(substr($value, -1)) {
1817       case 'g':
1818         $mult= 1073741824;
1819         break;
1820       case 'm':
1821         $mult= 1048576;
1822         break;
1823       case 'k':
1824         $mult= 1024;
1825         break;
1826     }
1828     return ($mult * (int)substr($value, 0, -1));
1829   } else {
1830     return $value;
1831   }
1835 function in_array_ics($value, $items)
1837   if (!is_array($items)){
1838     return (FALSE);
1839   }
1841   foreach ($items as $item){
1842     if (strtolower($item) == strtolower($value)) {
1843       return (TRUE);
1844     }
1845   }
1847   return (FALSE);
1848
1851 function generate_alphabet($count= 10)
1853   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1854   $alphabet= "";
1855   $c= 0;
1857   /* Fill cells with charaters */
1858   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1859     if ($c == 0){
1860       $alphabet.= "<tr>";
1861     }
1863     $ch = mb_substr($characters, $i, 1, "UTF8");
1864     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1865       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1867     if ($c++ == $count){
1868       $alphabet.= "</tr>";
1869       $c= 0;
1870     }
1871   }
1873   /* Fill remaining cells */
1874   while ($c++ <= $count){
1875     $alphabet.= "<td>&nbsp;</td>";
1876   }
1878   return ($alphabet);
1882 function validate($string)
1884   return (strip_tags(preg_replace('/\0/', '', $string)));
1887 function get_gosa_version()
1889   global $svn_revision, $svn_path;
1891   /* Extract informations */
1892   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1894   /* Release or development? */
1895   if (preg_match('%/gosa/trunk/%', $svn_path)){
1896     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1897   } else {
1898     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1899     return (_("GOsa $release"));
1900   }
1904 function rmdirRecursive($path, $followLinks=false) {
1905   $dir= opendir($path);
1906   while($entry= readdir($dir)) {
1907     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1908       unlink($path."/".$entry);
1909     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1910       rmdirRecursive($path."/".$entry);
1911     }
1912   }
1913   closedir($dir);
1914   return rmdir($path);
1917 function scan_directory($path,$sort_desc=false)
1919   $ret = false;
1921   /* is this a dir ? */
1922   if(is_dir($path)) {
1924     /* is this path a readable one */
1925     if(is_readable($path)){
1927       /* Get contents and write it into an array */   
1928       $ret = array();    
1930       $dir = opendir($path);
1932       /* Is this a correct result ?*/
1933       if($dir){
1934         while($fp = readdir($dir))
1935           $ret[]= $fp;
1936       }
1937     }
1938   }
1939   /* Sort array ascending , like scandir */
1940   sort($ret);
1942   /* Sort descending if parameter is sort_desc is set */
1943   if($sort_desc) {
1944     $ret = array_reverse($ret);
1945   }
1947   return($ret);
1950 function clean_smarty_compile_dir($directory)
1952   global $svn_revision;
1954   if(is_dir($directory) && is_readable($directory)) {
1955     // Set revision filename to REVISION
1956     $revision_file= $directory."/REVISION";
1958     /* Is there a stamp containing the current revision? */
1959     if(!file_exists($revision_file)) {
1960       // create revision file
1961       create_revision($revision_file, $svn_revision);
1962     } else {
1963 # check for "$config->...['CONFIG']/revision" and the
1964 # contents should match the revision number
1965       if(!compare_revision($revision_file, $svn_revision)){
1966         // If revision differs, clean compile directory
1967         foreach(scan_directory($directory) as $file) {
1968           if(($file==".")||($file=="..")) continue;
1969           if( is_file($directory."/".$file) &&
1970               is_writable($directory."/".$file)) {
1971             // delete file
1972             if(!unlink($directory."/".$file)) {
1973               print_red("File ".$directory."/".$file." could not be deleted.");
1974               // This should never be reached
1975             }
1976           } elseif(is_dir($directory."/".$file) &&
1977               is_writable($directory."/".$file)) {
1978             // Just recursively delete it
1979             rmdirRecursive($directory."/".$file);
1980           }
1981         }
1982         // We should now create a fresh revision file
1983         clean_smarty_compile_dir($directory);
1984       } else {
1985         // Revision matches, nothing to do
1986       }
1987     }
1988   } else {
1989     // Smarty compile dir is not accessible
1990     // (Smarty will warn about this)
1991   }
1994 function create_revision($revision_file, $revision)
1996   $result= false;
1998   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1999     if($fh= fopen($revision_file, "w")) {
2000       if(fwrite($fh, $revision)) {
2001         $result= true;
2002       }
2003     }
2004     fclose($fh);
2005   } else {
2006     print_red("Can not write to revision file");
2007   }
2009   return $result;
2012 function compare_revision($revision_file, $revision)
2014   // false means revision differs
2015   $result= false;
2017   if(file_exists($revision_file) && is_readable($revision_file)) {
2018     // Open file
2019     if($fh= fopen($revision_file, "r")) {
2020       // Compare File contents with current revision
2021       if($revision == fread($fh, filesize($revision_file))) {
2022         $result= true;
2023       }
2024     } else {
2025       print_red("Can not open revision file");
2026     }
2027     // Close file
2028     fclose($fh);
2029   }
2031   return $result;
2034 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2036   $str = ""; // Our return value will be saved in this var
2038   $color  = dechex($percentage+150);
2039   $color2 = dechex(150 - $percentage);
2040   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2042   $progress = (int)(($percentage /100)*$width);
2044   /* Abort printing out percentage, if divs are to small */
2047   /* If theres a better solution for this, use it... */
2048   $str = "
2049     <div style=\" width:".($width)."px; 
2050     height:".($height)."px;
2051   background-color:#000000;
2052 padding:1px;\">
2054           <div style=\" width:".($width)."px;
2055         background-color:#$bgcolor;
2056 height:".($height)."px;\">
2058          <div style=\" width:".$progress."px;
2059 height:".$height."px;
2060        background-color:#".$color2.$color2.$color."; \">";
2063        if(($height >10)&&($showvalue)){
2064          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2065            <b>".$percentage."%</b>
2066            </font>";
2067        }
2069        $str.= "</div></div></div>";
2071        return($str);
2075 function array_key_ics($ikey, $items)
2077   /* Gather keys, make them lowercase */
2078   $tmp= array();
2079   foreach ($items as $key => $value){
2080     $tmp[strtolower($key)]= $key;
2081   }
2083   if (isset($tmp[strtolower($ikey)])){
2084     return($tmp[strtolower($ikey)]);
2085   }
2087   return ("");
2091 function search_config($arr, $name, $return)
2093   if (is_array($arr)){
2094     foreach ($arr as $a){
2095       if (isset($a['CLASS']) &&
2096           strtolower($a['CLASS']) == strtolower($name)){
2098         if (isset($a[$return])){
2099           return ($a[$return]);
2100         } else {
2101           return ("");
2102         }
2103       } else {
2104         $res= search_config ($a, $name, $return);
2105         if ($res != ""){
2106           return $res;
2107         }
2108       }
2109     }
2110   }
2111   return ("");
2115 function array_differs($src, $dst)
2117   /* If the count is differing, the arrays differ */
2118   if (count ($src) != count ($dst)){
2119     return (TRUE);
2120   }
2122   /* So the count is the same - lets check the contents */
2123   $differs= FALSE;
2124   foreach($src as $value){
2125     if (!in_array($value, $dst)){
2126       $differs= TRUE;
2127     }
2128   }
2130   return ($differs);
2134 function saveFilter($a_filter, $values)
2136   if (isset($_POST['regexit'])){
2137     $a_filter["regex"]= $_POST['regexit'];
2139     foreach($values as $type){
2140       if (isset($_POST[$type])) {
2141         $a_filter[$type]= "checked";
2142       } else {
2143         $a_filter[$type]= "";
2144       }
2145     }
2146   }
2148   /* React on alphabet links if needed */
2149   if (isset($_GET['search'])){
2150     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2151     if ($s == "**"){
2152       $s= "*";
2153     }
2154     $a_filter['regex']= $s;
2155   }
2157   return ($a_filter);
2161 /* Escape all preg_* relevant characters */
2162 function normalizePreg($input)
2164   return (addcslashes($input, '[]()|/.*+-'));
2168 /* Escape all LDAP filter relevant characters */
2169 function normalizeLdap($input)
2171   return (addcslashes($input, '()|'));
2175 /* Resturns the difference between to microtime() results in float  */
2176 function get_MicroTimeDiff($start , $stop)
2178   $a = split("\ ",$start);
2179   $b = split("\ ",$stop);
2181   $secs = $b[1] - $a[1];
2182   $msecs= $b[0] - $a[0]; 
2184   $ret = (float) ($secs+ $msecs);
2185   return($ret);
2189 /* Check if the given department name is valid */
2190 function is_department_name_reserved($name,$base)
2192   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2193                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2194                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2195   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2197   /* Check if name is one of the reserved names */
2198   if(in_array_ics($name,$reservedName)) {
2199     return(true);
2200   }
2202   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2203   foreach($follwedNames as $key => $names){
2204     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2205       return(true);
2206     }
2207   }
2208   return(false);
2212 function is_php4()
2214   if (isset($_SESSION['PHP4COMPATIBLE'])){
2215     return true;
2216   }
2217   return (preg_match('/^4/', phpversion()));
2221 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2223   /* Initialize variables */
2224   $ret  = array("count" => 0);  // Set count to 0
2225   $next = true;                 // if false, then skip next loops and return
2226   $cnt  = 0;                    // Current number of loops
2227   $max  = 100;                  // Just for security, prevent looops
2228   $ldap = NULL;                 // To check if created result a valid
2229   $keep = "";                   // save last failed parse string
2231   /* Check each parsed dn in ldap ? */
2232   if($config!=NULL && $verify_in_ldap){
2233     $ldap = $config->get_ldap_link();
2234   }
2236   /* Lets start */
2237   $called = false;
2238   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2240     $cnt ++;
2241     if(!preg_match("/,/",$dn)){
2242       $next = false;
2243     }
2244     $object = preg_replace("/[,].*$/","",$dn);
2245     $dn     = preg_replace("/^[^,]+,/","",$dn);
2247     $called = true;
2249     /* Check if current dn is valid */
2250     if($ldap!=NULL){
2251       $ldap->cd($dn);
2252       $ldap->cat($dn,array("dn"));
2253       if($ldap->count()){
2254         $ret[]  = $keep.$object;
2255         $keep   = "";
2256       }else{
2257         $keep  .= $object.",";
2258       }
2259     }else{
2260       $ret[]  = $keep.$object;
2261       $keep   = "";
2262     }
2263   }
2265   /* No dn was posted */
2266   if($cnt == 0 && !empty($dn)){
2267     $ret[] = $dn;
2268   }
2270   /* Append the rest */
2271   $test = $keep.$dn;
2272   if($called && !empty($test)){
2273     $ret[] = $keep.$dn;
2274   }
2275   $ret['count'] = count($ret) - 1;
2277   return($ret);
2281 function get_base_from_hook($dn, $attrib)
2283   global $config;
2285   if (isset($config->current['BASE_HOOK'])){
2286     
2287     /* Call hook script - if present */
2288     $command= $config->current['BASE_HOOK'];
2290     if ($command != ""){
2291       $command.= " '$dn' $attrib";
2292       if (check_command($command)){
2293         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2294         exec($command, $output);
2295         if (preg_match("/^[0-9]+$/", $output[0])){
2296           return ($output[0]);
2297         } else {
2298           print_red(_("Warning - base_hook is not available. Using default base."));
2299           return ($config->current['UIDBASE']);
2300         }
2301       } else {
2302         print_red(_("Warning - base_hook is not available. Using default base."));
2303         return ($config->current['UIDBASE']);
2304       }
2306     } else {
2308       print_red(_("Warning - no base_hook defined. Using default base."));
2309       return ($config->current['UIDBASE']);
2311     }
2312   }
2315 /* Schema validation functions */
2317   function check_schema_version($class, $version)
2318   {
2319     return preg_match("/\(v$version\)/", $class['DESC']);
2320   }
2322   
2324   function check_schema($cfg,$rfc2307bis = FALSE)
2325   {
2327     $messages= array();
2329     /* Get objectclasses */
2330     $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2331     $objectclasses = $ldap->get_objectclasses();
2332     if(count($objectclasses) == 0){
2333       print_red(_("Can't get schema information from server. No schema check possible!"));
2334     }
2336     /* This is the default block used for each entry.
2337      *  to avoid unset indexes.
2338      */
2339     $def_check = array("REQUIRED_VERSION" => "0",
2340                        "SCHEMA_FILES"     => array(),
2341                        "CLASSES_REQUIRED" => array(),
2342                        "STATUS"           => FALSE,
2343                        "IS_MUST_HAVE"     => FALSE,
2344                        "MSG"              => "",
2345                        "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2347  /* The gosa base schema */
2348     $checks['gosaObject'] = $def_check;
2349     $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2350     $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2351     $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2352     $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2354     /* GOsa Account class */
2355     $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2356     $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2357     $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2358     $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2359     $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2361     /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2362     $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2363     $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2364     $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2365     $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2366     $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2368   /* Some other checks */
2369     foreach(array(
2370           "gosaCacheEntry"        => array("version" => "2.4"),
2371           "gosaDepartment"        => array("version" => "2.4"),
2372           "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2373           "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2374           "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2375           "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2376           "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2377           "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2378           "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2379           "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2380           "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2381           "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2382           "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2383           "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2384           "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2385           "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2386           "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2387           "goLdapServer"          => array("version" => "2.4"),
2388           "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2389           "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2390           "goKrbServer"           => array("version" => "2.4"),
2391           "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2392           ) as $name => $values){
2394       $checks[$name] = $def_check;
2395       if(isset($values['version'])){
2396         $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2397       }
2398       if(isset($values['file'])){
2399         $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2400       }
2401       $checks[$name]["CLASSES_REQUIRED"] = array($name);
2402     }
2403    foreach($checks as $name => $value){
2404       foreach($value['CLASSES_REQUIRED'] as $class){
2406         if(!isset($objectclasses[$name])){
2407           $checks[$name]['STATUS'] = FALSE;
2408           if($value['IS_MUST_HAVE']){
2409             $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2410           }else{
2411             $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2412           }
2413         }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2414           $checks[$name]['STATUS'] = FALSE;
2416           if($value['IS_MUST_HAVE']){
2417             $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2418           }else{
2419             $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2420           }
2421         }else{
2422           $checks[$name]['STATUS'] = TRUE;
2423           $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2424         }
2425       }
2426     }
2428     $tmp = $objectclasses;
2431     /* The gosa base schema */
2432     $checks['posixGroup'] = $def_check;
2433     $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2434     $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2435     $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2436     $checks['posixGroup']['STATUS']           = TRUE;
2437     $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2438     $checks['posixGroup']['MSG']              = "";
2439     $checks['posixGroup']['INFO']             = "";
2441     /* Depending on selected rfc2307bis mode, we need different schema configurations */
2442     if(isset($tmp['posixGroup'])){
2444       if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2445         $checks['posixGroup']['STATUS']           = FALSE;
2446         $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2447         $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2448       }
2449       if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2450         $checks['posixGroup']['STATUS']           = FALSE;
2451         $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2452         $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2453       }
2454     }
2456     return($checks);
2457   }
2460 function prepare4mailbody($string)
2462   $string = html_entity_decode($string);
2464   $from = array(
2465                 "/%/",
2466                 "/ /",
2467                 "/\n/",  
2468                 "/\r/",
2469                 "/!/",
2470                 "/#/",
2471                 "/\*/",
2472                 "/\//",
2473                 "/</",
2474                 "/>/",
2475                 "/\?/",
2476                 "/\&/",
2477                 "/\(/",
2478                 "/\)/",
2479                 "/\"/");
2480   
2481   $to = array(  
2482                 "%25",
2483                 "%20",
2484                 "%0A",
2485                 "%0D",
2486                 "%21",
2487                 "%23",
2488                 "%2A",
2489                 "%2F",
2490                 "%3C",
2491                 "%3E",
2492                 "%3F",
2493                 "%38",
2494                 "%28",
2495                 "%29",
2496                 "%22");
2498   $string = preg_replace($from,$to,$string);
2500   return($string);
2504 function mac2company($mac)
2506   $vendor= "";
2508   /* Generate a normailzed mac... */
2509   $mac= substr(preg_replace('/[:-]/', '', $mac), 0, 6);
2511   /* Check for existance of the oui file */
2512   if (!is_readable(CONFIG_DIR."/oui.txt")){
2513     return ("");
2514   }
2516   /* Open file and look for mac addresses... */
2517   $handle = @fopen(CONFIG_DIR."/oui.txt", "r");
2518   if ($handle) {
2519     while (!feof($handle)) {
2520       $line = fgets($handle, 4096);
2522       if (preg_match("/^$mac/i", $line)){
2523         $vendor= substr($line, 32);
2524       }
2525     }
2526     fclose($handle);
2527   }
2529   return ($vendor);
2533 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2535   $tmp = array(
2536         "de_DE" => "German",
2537         "fr_FR" => "French",
2538         "it_IT" => "Italian",
2539         "es_ES" => "Spanish",
2540         "en_US" => "English",
2541         "nl_NL" => "Dutch",
2542         "pl_PL" => "Polish",
2543         "sv_SE" => "Swedish",
2544         "zh_CN" => "Chinese",
2545         "ru_RU" => "Russian");
2546   
2547   $tmp2= array(
2548         "de_DE" => _("German"),
2549         "fr_FR" => _("French"),
2550         "it_IT" => _("Italian"),
2551         "es_ES" => _("Spanish"),
2552         "en_US" => _("English"),
2553         "nl_NL" => _("Dutch"),
2554         "pl_PL" => _("Polish"),
2555         "sv_SE" => _("Swedish"),
2556         "zh_CN" => _("Chinese"),
2557         "ru_RU" => _("Russian"));
2559   $ret = array();
2560   if($languages_in_own_language){
2562     $old_lang = setlocale(LC_ALL, 0);
2563     foreach($tmp as $key => $name){
2564       $lang = $key.".UTF-8";
2565       setlocale(LC_ALL, $lang);
2566       if($strip_region_tag){
2567         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2568       }else{
2569         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2570       }
2571     }
2572     setlocale(LC_ALL, $old_lang);
2573   }else{
2574     foreach($tmp as $key => $name){
2575       if($strip_region_tag){
2576         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2577       }else{
2578         $ret[$key] = _($name);
2579       }
2580     }
2581   }
2582   return($ret);
2586 /* Check if $ip1 and $ip2 represents a valid IP range 
2587  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2588  */
2589 function is_ip_range($ip1,$ip2)
2591   if(!is_ip($ip1) || !is_ip($ip2)){
2592     return(FALSE);
2593   }else{
2594     $ar1 = split("\.",$ip1);
2595     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2597     $ar2 = split("\.",$ip2);
2598     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2599     return($var1 < $var2);
2600   }
2604 /* Check if the specified IP address $address is inside the given network */
2605 function is_in_network($network, $netmask, $address)
2607   $nw= split('\.', $network);
2608   $nm= split('\.', $netmask);
2609   $ad= split('\.', $address);
2611   /* Generate inverted netmask */
2612   for ($i= 0; $i<4; $i++){
2613     $ni[$i]= 255-$nm[$i];
2614     $la[$i]= $nw[$i] | $ni[$i];
2615   }
2617   /* Transform to integer */
2618   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2619   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2620   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2622   return ($first < $curr&& $last > $curr);
2626 /* Returns contents of the given POST variable and check magic quotes settings */
2627 function get_post($name)
2629   if(!isset($_POST[$name])){
2630     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2631     return(FALSE);
2632   }
2633   if(get_magic_quotes_gpc()){
2634     return(stripcslashes($_POST[$name]));
2635   }else{
2636     return($_POST[$name]);
2637   }
2640 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2641 ?>