Code

39fc85b6697e6c37b6bb4e8b7b0bb5f1a3719d39
[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   if ($checkTag && isset($config->current['STRICT_UNITS']) &&
763       preg_match('/^(yes|true)$/i', $config->current['STRICT_UNITS']) &&
764       $ui->gosaUnitTag != ""){
765     $size= 0;
766     foreach ($config->tdepartments as $tdn => $tag){
767       if (preg_match("/$tdn$/", $dn)){
768         if (strlen($tdn) > $size){
769           $size= strlen($tdn);
770           $ttag= $tag;
771         }
772       }
773     }
775     /* We have no permission for areas that don't carry our tag */
776     if ($ttag != $ui->gosaUnitTag){
777       return ("#none#");
778     }
779   }
781   $final= "";
782   foreach($acl_array as $acl){
784     /* Check for selfflag (!) in ACL to determine if
785        the user is allowed to change parts of his/her
786        own account */
787     if (preg_match("/^!/", $acl)){
788       if ($dn != "" && $dn != $ui->dn){
790         /* No match for own DN, give up on this ACL */
791         continue;
793       } else {
795         /* Matches own DN, remove the selfflag */
796         $acl= preg_replace("/^!/", "", $acl);
798       }
799     }
801     /* Remove leading garbage */
802     $acl= preg_replace("/^:/", "", $acl);
804     /* Discover if we've access to the submodule by comparing
805        all allowed submodules specified in the ACL */
806     $tmp= split(",", $acl);
807     foreach ($tmp as $mod){
808       if (preg_match("/^$module#/", $mod)){
809         $final= strstr($mod, "#")."#";
810         continue;
811       }
812       if (preg_match("/[^#]$module$/", $mod)){
813         return ("#all#");
814       }
815       if (preg_match("/^all$/", $mod)){
816         return ("#all#");
817       }
818     }
819   }
821   /* Return assembled ACL, or none */
822   if ($final != ""){
823     return (preg_replace('/##/', '#', $final));
824   }
826   /* Nothing matches - disable access for this object */
827   return ("#none#");
831 function get_userinfo()
833   global $ui;
835   return $ui;
839 function get_smarty()
841   global $smarty;
843   return $smarty;
847 function convert_department_dn($dn)
849   $dep= "";
851   /* Build a sub-directory style list of the tree level
852      specified in $dn */
853   foreach (split(',', $dn) as $rdn){
855     /* We're only interested in organizational units... */
856     if (substr($rdn,0,3) == 'ou='){
857       $dep= substr($rdn,3)."/$dep";
858     }
860     /* ... and location objects */
861     if (substr($rdn,0,2) == 'l='){
862       $dep= substr($rdn,2)."/$dep";
863     }
864   }
866   /* Return and remove accidently trailing slashes */
867   return rtrim($dep, "/");
871 /* Strip off the last sub department part of a '/level1/level2/.../'
872  * style value. It removes the trailing '/', too. */
873 function get_sub_department($value)
875   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
879 function get_ou($name)
881   global $config;
883   /* Preset ou... */
884   if (isset($config->current[$name])){
885     $ou= $config->current[$name];
886   } else {
887     return "";
888   }
889   
890   if ($ou != ""){
891     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
892       return @LDAP::convert("ou=$ou,");
893     } else {
894       return @LDAP::convert("$ou,");
895     }
896   } else {
897     return "";
898   }
902 function get_people_ou()
904   return (get_ou("PEOPLE"));
908 function get_groups_ou()
910   return (get_ou("GROUPS"));
914 function get_winstations_ou()
916   return (get_ou("WINSTATIONS"));
920 function get_base_from_people($dn)
922   global $config;
924   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
925   $base= preg_replace($pattern, '', $dn);
927   /* Set to base, if we're not on a correct subtree */
928   if (!isset($config->idepartments[$base])){
929     $base= $config->current['BASE'];
930   }
932   return ($base);
936 function chkacl($acl, $name)
938   /* Look for attribute in ACL */
939   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
940     return ("");
941   }
943   /* Optically disable html object for no match */
944   return (" disabled ");
948 function is_phone_nr($nr)
950   if ($nr == ""){
951     return (TRUE);
952   }
954   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
958 function is_url($url)
960   if ($url == ""){
961     return (TRUE);
962   }
964   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
968 function is_dn($dn)
970   if ($dn == ""){
971     return (TRUE);
972   }
974   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
978 function is_uid($uid)
980   global $config;
982   if ($uid == ""){
983     return (TRUE);
984   }
986   /* STRICT adds spaces and case insenstivity to the uid check.
987      This is dangerous and should not be used. */
988   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
989     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
990   } else {
991     return preg_match ("/^[a-z0-9_-]+$/", $uid);
992   }
996 function is_ip($ip)
998   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);
1002 function is_mac($mac)
1004   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);
1008 /* Checks if the given ip address doesn't match
1009     "is_ip" because there is also a sub net mask given */
1010 function is_ip_with_subnetmask($ip)
1012         /* Generate list of valid submasks */
1013         $res = array();
1014         for($e = 0 ; $e <= 32; $e++){
1015                 $res[$e] = $e;
1016         }
1017         $i[0] =255;
1018         $i[1] =255;
1019         $i[2] =255;
1020         $i[3] =255;
1021         for($a= 3 ; $a >= 0 ; $a --){
1022                 $c = 1;
1023                 while($i[$a] > 0 ){
1024                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
1025                         $res[$str] = $str;
1026                         $i[$a] -=$c;
1027                         $c = 2*$c;
1028                 }
1029         }
1030         $res["0.0.0.0"] = "0.0.0.0";
1031         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1032                         "(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]?)/", $ip)){
1035                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1036                         "(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]?)/","",$ip);
1040                 $mask = preg_replace("/^\//","",$mask);
1041                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1042                         return(TRUE);
1043                 }
1044         }
1045         return(FALSE);
1048 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1049 function is_domain($str)
1051   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1055 function is_id($id)
1057   if ($id == ""){
1058     return (FALSE);
1059   }
1061   return preg_match ("/^[0-9]+$/", $id);
1065 function is_path($path)
1067   if ($path == ""){
1068     return (TRUE);
1069   }
1070   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1071     return (FALSE);
1072   }
1074   return preg_match ("/\/.+$/", $path);
1078 function is_email($address, $template= FALSE)
1080   if ($address == ""){
1081     return (TRUE);
1082   }
1083   if ($template){
1084     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1085         $address);
1086   } else {
1087     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1088         $address);
1089   }
1093 function print_red()
1095   /* Check number of arguments */
1096   if (func_num_args() < 1){
1097     return;
1098   }
1100   /* Get arguments, save string */
1101   $array = func_get_args();
1102   $string= $array[0];
1104   /* Step through arguments */
1105   for ($i= 1; $i<count($array); $i++){
1106     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1107   }
1109   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1110     $_SESSION['errorsAlreadyPosted'] = array(); 
1111   }
1113   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1114      the other case... */
1116   if (isset($_SESSION['DEBUGLEVEL'])){
1118     if($_SESSION['LastError'] == $string){
1119     
1120       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1121         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1122       }
1123       $_SESSION['errorsAlreadyPosted'][$string]++;
1125     }else{
1126       if($string != NULL){
1127         if (preg_match("/"._("LDAP error:")."/", $string)){
1128           $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.");
1129           $img= "images/error.png";
1130         } else {
1131           if (!preg_match('/[.!?]$/', $string)){
1132             $string.= ".";
1133           }
1134           $string= preg_replace('/<br>/', ' ', $string);
1135           $img= "images/warning.png";
1136           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1137         }
1138       
1139         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1142   if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1144             $_SESSION['errors'].= "
1145               <iframe id='e_layer3'
1146                 style=\"  position:absolute;
1147                           width:100%;
1148                           height:100%;
1149                           top:0px;
1150                           left:0px;
1151                           border:none;
1152                           display:block;
1153                           allowtransparency='true';
1154                           background-color: #FFFFFF;
1155                           filter:chroma(color=#FFFFFF);
1156                           z-index:0; \">
1157               </iframe>
1158               <div  id='e_layer2'
1159                 style=\"
1160                   position: absolute;
1161                   left: 0px;
1162                   top: 0px;
1163                   right:0px;
1164                   bottom:0px;
1165                   z-index:0;
1166                   width:100%;
1167                   height:100%;
1168                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1169               </div>";
1170               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1171           }else{
1173             $_SESSION['errors'].= "
1174               <div  id='e_layer2'
1175                 style=\"
1176                   position: absolute;
1177                   left: 0px;
1178                   top: 0px;
1179                   right:0px;
1180                   bottom:0px;
1181                   z-index:0;
1182                   background-image: url(images/opacity_black.png);\">
1183                </div>";
1184               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1185           }
1187           $_SESSION['errors'].= "
1188           <div style='left:20%;right:20%;top:30%;".
1189             "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1190             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1191             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1192             get_template_path($img)."'></td>".
1193             "<td style='width:100%'><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1194             (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1195             " style='width:80px' onClick='".$hide."'>".
1196             _("OK")."</button></td></tr></table></div>";
1197         }
1199       }else{
1200         return;
1201       }
1202       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1204     }
1206   } else {
1207     echo "Error: $string\n";
1208   }
1209   $_SESSION['LastError'] = $string; 
1213 function gen_locked_message($user, $dn)
1215   global $plug, $config;
1217   $_SESSION['dn']= $dn;
1218   $ldap= $config->get_ldap_link();
1219   $ldap->cat ($user, array('uid', 'cn'));
1220   $attrs= $ldap->fetch();
1222   /* Stop if we have no user here... */
1223   if (count($attrs)){
1224     $uid= $attrs["uid"][0];
1225     $cn= $attrs["cn"][0];
1226   } else {
1227     $uid= $attrs["uid"][0];
1228     $cn= $attrs["cn"][0];
1229   }
1230   
1231   $remove= false;
1233   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1234     $_SESSION['LOCK_VARS_USED']  =array();
1235     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1237       if(empty($name)) continue;
1238       foreach($_POST as $Pname => $Pvalue){
1239         if(preg_match($name,$Pname)){
1240           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1241         }
1242       }
1244       foreach($_GET as $Pname => $Pvalue){
1245         if(preg_match($name,$Pname)){
1246           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1247         }
1248       }
1249     }
1250     $_SESSION['LOCK_VARS_TO_USE'] =array();
1251   }
1253   /* Prepare and show template */
1254   $smarty= get_smarty();
1255   $smarty->assign ("dn", $dn);
1256   if ($remove){
1257     $smarty->assign ("action", _("Continue anyway"));
1258   } else {
1259     $smarty->assign ("action", _("Edit anyway"));
1260   }
1261   $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>"));
1263   return ($smarty->fetch (get_template_path('islocked.tpl')));
1267 function to_string ($value)
1269   /* If this is an array, generate a text blob */
1270   if (is_array($value)){
1271     $ret= "";
1272     foreach ($value as $line){
1273       $ret.= $line."<br>\n";
1274     }
1275     return ($ret);
1276   } else {
1277     return ($value);
1278   }
1282 function get_printer_list($cups_server)
1284   global $config;
1286   $res= array();
1288   /* Use CUPS, if we've access to it */
1289   if (function_exists('cups_get_dest_list')){
1290     $dest_list= cups_get_dest_list ($cups_server);
1292     foreach ($dest_list as $prt){
1293       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1295       foreach ($attr as $prt_info){
1296         if ($prt_info->name == "printer-info"){
1297           $info= $prt_info->value;
1298           break;
1299         }
1300       }
1301       $res[$prt->name]= "$info [$prt->name]";
1302     }
1304     /* CUPS is not available, try lpstat as a replacement */
1305   } else {
1306     $ar = false;
1307     exec("lpstat -p", $ar);
1308     foreach($ar as $val){
1309       @list($dummy, $printer, $rest)= split(' ', $val, 3);
1310       if (preg_match('/^[^@]+$/', $printer)){
1311         $res[$printer]= "$printer";
1312       }
1313     }
1314   }
1316   /* Merge in printers from LDAP */
1317   $ldap= $config->get_ldap_link();
1318   $ldap->cd ($config->current['BASE']);
1319   $ui= get_userinfo();
1320   if (isset($config->current['STRICT_UNITS']) && preg_match('/TRUE/i', $config->current['STRICT_UNITS']) && $ui->gosaUnitTag != ""){   
1321     $ldap->search('((objectClass=gotoPrinter)(gosaUnitTag='.$ui->gosaUnitTag.'))', array('cn'));
1322   } else {
1323     $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1324   }
1325   while($attrs = $ldap->fetch()){
1326     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1327   }
1329   return $res;
1333 function sess_del ($var)
1335   /* New style */
1336   unset ($_SESSION[$var]);
1338   /* ... work around, since the first one
1339      doesn't seem to work all the time */
1340   session_unregister ($var);
1344 function show_errors($message)
1346   $complete= "";
1348   /* Assemble the message array to a plain string */
1349   foreach ($message as $error){
1350     if ($complete == ""){
1351       $complete= $error;
1352     } else {
1353       $complete= "$error<br>$complete";
1354     }
1355   }
1357   /* Fill ERROR variable with nice error dialog */
1358   print_red($complete);
1362 function show_ldap_error($message, $addon= "")
1364   if (!preg_match("/Success/i", $message)){
1365     if ($addon == ""){
1366       print_red (_("LDAP error: $message"));
1367     } else {
1368       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1369     }
1370     return TRUE;
1371   } else {
1372     return FALSE;
1373   }
1377 function rewrite($s)
1379   global $REWRITE;
1381   foreach ($REWRITE as $key => $val){
1382     $s= preg_replace("/$key/", "$val", $s);
1383   }
1385   return ($s);
1389 function dn2base($dn)
1391   global $config;
1393   if (get_people_ou() != ""){
1394     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1395   }
1396   if (get_groups_ou() != ""){
1397     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1398   }
1399   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1401   return ($base);
1406 function check_command($cmdline)
1408   $cmd= preg_replace("/ .*$/", "", $cmdline);
1410   /* Check if command exists in filesystem */
1411   if (!file_exists($cmd)){
1412     return (FALSE);
1413   }
1415   /* Check if command is executable */
1416   if (!is_executable($cmd)){
1417     return (FALSE);
1418   }
1420   return (TRUE);
1424 function print_header($image, $headline, $info= "")
1426   $display= "<div class=\"plugtop\">\n";
1427   $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";
1428   $display.= "</div>\n";
1430   if ($info != ""){
1431     $display.= "<div class=\"pluginfo\">\n";
1432     $display.= "$info";
1433     $display.= "</div>\n";
1434   } else {
1435     $display.= "<div style=\"height:5px;\">\n";
1436     $display.= "&nbsp;";
1437     $display.= "</div>\n";
1438   }
1439 #  if (isset($_SESSION['errors'])){
1440 #    $display.= $_SESSION['errors'];
1441 #  }
1443   return ($display);
1447 function register_global($name, $object)
1449   $_SESSION[$name]= $object;
1453 function is_global($name)
1455   return isset($_SESSION[$name]);
1459 function get_global($name)
1461   return $_SESSION[$name];
1465 function range_selector($dcnt,$start,$range=25,$post_var=false)
1468   /* Entries shown left and right from the selected entry */
1469   $max_entries= 10;
1471   /* Initialize and take care that max_entries is even */
1472   $output="";
1473   if ($max_entries & 1){
1474     $max_entries++;
1475   }
1477   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1478     $range= $_POST[$post_var];
1479   }
1481   /* Prevent output to start or end out of range */
1482   if ($start < 0 ){
1483     $start= 0 ;
1484   }
1485   if ($start >= $dcnt){
1486     $start= $range * (int)(($dcnt / $range) + 0.5);
1487   }
1489   $numpages= (($dcnt / $range));
1490   if(((int)($numpages))!=($numpages)){
1491     $numpages = (int)$numpages + 1;
1492   }
1493   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1494     return ("");
1495   }
1496   $ppage= (int)(($start / $range) + 0.5);
1499   /* Align selected page to +/- max_entries/2 */
1500   $begin= $ppage - $max_entries/2;
1501   $end= $ppage + $max_entries/2;
1503   /* Adjust begin/end, so that the selected value is somewhere in
1504      the middle and the size is max_entries if possible */
1505   if ($begin < 0){
1506     $end-= $begin + 1;
1507     $begin= 0;
1508   }
1509   if ($end > $numpages) {
1510     $end= $numpages;
1511   }
1512   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1513     $begin= $end - $max_entries;
1514   }
1516   if($post_var){
1517     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1518       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1519   }else{
1520     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1521   }
1523   /* Draw decrement */
1524   if ($start > 0 ) {
1525     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1526       (($start-$range))."\">".
1527       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1528   }
1530   /* Draw pages */
1531   for ($i= $begin; $i < $end; $i++) {
1532     if ($ppage == $i){
1533       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1534         validate($_GET['plug'])."&amp;start=".
1535         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1536     } else {
1537       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1538         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1539     }
1540   }
1542   /* Draw increment */
1543   if($start < ($dcnt-$range)) {
1544     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1545       (($start+($range)))."\">".
1546       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1547   }
1549   if(($post_var)&&($numpages)){
1550     $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()'>";
1551     foreach(array(20,50,100,200,"all") as $num){
1552       if($num == "all"){
1553         $var = 10000;
1554       }else{
1555         $var = $num;
1556       }
1557       if($var == $range){
1558         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1559       }else{  
1560         $output.="\n<option value='".$var."'>".$num."</option>";
1561       }
1562     }
1563     $output.=  "</select></td></tr></table></div>";
1564   }else{
1565     $output.= "</div>";
1566   }
1568   return($output);
1572 function apply_filter()
1574   $apply= "";
1576   $apply= ''.
1577     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1578     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1580   return ($apply);
1584 function back_to_main()
1586   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1587     _("Back").'"></p><input type="hidden" name="ignore">';
1589   return ($string);
1593 function normalize_netmask($netmask)
1595   /* Check for notation of netmask */
1596   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1597     $num= (int)($netmask);
1598     $netmask= "";
1600     for ($byte= 0; $byte<4; $byte++){
1601       $result=0;
1603       for ($i= 7; $i>=0; $i--){
1604         if ($num-- > 0){
1605           $result+= pow(2,$i);
1606         }
1607       }
1609       $netmask.= $result.".";
1610     }
1612     return (preg_replace('/\.$/', '', $netmask));
1613   }
1615   return ($netmask);
1619 function netmask_to_bits($netmask)
1621   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1622   $res= 0;
1624   for ($n= 0; $n<4; $n++){
1625     $start= 255;
1626     $name= "nm$n";
1628     for ($i= 0; $i<8; $i++){
1629       if ($start == (int)($$name)){
1630         $res+= 8 - $i;
1631         break;
1632       }
1633       $start-= pow(2,$i);
1634     }
1635   }
1637   return ($res);
1641 function recurse($rule, $variables)
1643   $result= array();
1645   if (!count($variables)){
1646     return array($rule);
1647   }
1649   reset($variables);
1650   $key= key($variables);
1651   $val= current($variables);
1652   unset ($variables[$key]);
1654   foreach($val as $possibility){
1655     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1656     $result= array_merge($result, recurse($nrule, $variables));
1657   }
1659   return ($result);
1663 function expand_id($rule, $attributes)
1665   /* Check for id rule */
1666   if(preg_match('/^id(:|#)\d+$/',$rule)){
1667     return (array("\{$rule}"));
1668   }
1670   /* Check for clean attribute */
1671   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1672     $rule= preg_replace('/^%/', '', $rule);
1673     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1674     return (array($val));
1675   }
1677   /* Check for attribute with parameters */
1678   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1679     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1680     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1681     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1682     $start= preg_replace ('/-.*$/', '', $param);
1683     $stop = preg_replace ('/^[^-]+-/', '', $param);
1685     /* Assemble results */
1686     $result= array();
1687     for ($i= $start; $i<= $stop; $i++){
1688       $result[]= substr($val, 0, $i);
1689     }
1690     return ($result);
1691   }
1693   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1694   return (array($rule));
1698 function gen_uids($rule, $attributes)
1700   global $config;
1702   /* Search for keys and fill the variables array with all 
1703      possible values for that key. */
1704   $part= "";
1705   $trigger= false;
1706   $stripped= "";
1707   $variables= array();
1709   for ($pos= 0; $pos < strlen($rule); $pos++){
1711     if ($rule[$pos] == "{" ){
1712       $trigger= true;
1713       $part= "";
1714       continue;
1715     }
1717     if ($rule[$pos] == "}" ){
1718       $variables[$pos]= expand_id($part, $attributes);
1719       $stripped.= "{".$pos."}";
1720       $trigger= false;
1721       continue;
1722     }
1724     if ($trigger){
1725       $part.= $rule[$pos];
1726     } else {
1727       $stripped.= $rule[$pos];
1728     }
1729   }
1731   /* Recurse through all possible combinations */
1732   $proposed= recurse($stripped, $variables);
1734   /* Get list of used ID's */
1735   $used= array();
1736   $ldap= $config->get_ldap_link();
1737   $ldap->cd($config->current['BASE']);
1738   $ldap->search('(uid=*)');
1740   while($attrs= $ldap->fetch()){
1741     $used[]= $attrs['uid'][0];
1742   }
1744   /* Remove used uids and watch out for id tags */
1745   $ret= array();
1746   foreach($proposed as $uid){
1748     /* Check for id tag and modify uid if needed */
1749     if(preg_match('/\{id:\d+}/',$uid)){
1750       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1752       for ($i= 0; $i < pow(10,$size); $i++){
1753         $number= sprintf("%0".$size."d", $i);
1754         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1755         if (!in_array($res, $used)){
1756           $uid= $res;
1757           break;
1758         }
1759       }
1760     }
1762   if(preg_match('/\{id#\d+}/',$uid)){
1763     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1765     while (true){
1766       mt_srand((double) microtime()*1000000);
1767       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1768       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1769       if (!in_array($res, $used)){
1770         $uid= $res;
1771         break;
1772       }
1773     }
1774   }
1776 /* Don't assign used ones */
1777 if (!in_array($uid, $used)){
1778   $ret[]= $uid;
1782 return(array_unique($ret));
1786 function array_search_r($needle, $key, $haystack){
1788   foreach($haystack as $index => $value){
1789     $match= 0;
1791     if (is_array($value)){
1792       $match= array_search_r($needle, $key, $value);
1793     }
1795     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1796       $match=1;
1797     }
1799     if ($match){
1800       return 1;
1801     }
1802   }
1804   return 0;
1805
1808 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1809    Need to convert... */
1810 function to_byte($value) {
1811   $value= strtolower(trim($value));
1813   if(!is_numeric(substr($value, -1))) {
1815     switch(substr($value, -1)) {
1816       case 'g':
1817         $mult= 1073741824;
1818         break;
1819       case 'm':
1820         $mult= 1048576;
1821         break;
1822       case 'k':
1823         $mult= 1024;
1824         break;
1825     }
1827     return ($mult * (int)substr($value, 0, -1));
1828   } else {
1829     return $value;
1830   }
1834 function in_array_ics($value, $items)
1836   if (!is_array($items)){
1837     return (FALSE);
1838   }
1840   foreach ($items as $item){
1841     if (strtolower($item) == strtolower($value)) {
1842       return (TRUE);
1843     }
1844   }
1846   return (FALSE);
1847
1850 function generate_alphabet($count= 10)
1852   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1853   $alphabet= "";
1854   $c= 0;
1856   /* Fill cells with charaters */
1857   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1858     if ($c == 0){
1859       $alphabet.= "<tr>";
1860     }
1862     $ch = mb_substr($characters, $i, 1, "UTF8");
1863     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1864       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1866     if ($c++ == $count){
1867       $alphabet.= "</tr>";
1868       $c= 0;
1869     }
1870   }
1872   /* Fill remaining cells */
1873   while ($c++ <= $count){
1874     $alphabet.= "<td>&nbsp;</td>";
1875   }
1877   return ($alphabet);
1881 function validate($string)
1883   return (strip_tags(preg_replace('/\0/', '', $string)));
1886 function get_gosa_version()
1888   global $svn_revision, $svn_path;
1890   /* Extract informations */
1891   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1893   /* Release or development? */
1894   if (preg_match('%/gosa/trunk/%', $svn_path)){
1895     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1896   } else {
1897     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1898     return (_("GOsa $release"));
1899   }
1903 function rmdirRecursive($path, $followLinks=false) {
1904   $dir= opendir($path);
1905   while($entry= readdir($dir)) {
1906     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1907       unlink($path."/".$entry);
1908     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1909       rmdirRecursive($path."/".$entry);
1910     }
1911   }
1912   closedir($dir);
1913   return rmdir($path);
1916 function scan_directory($path,$sort_desc=false)
1918   $ret = false;
1920   /* is this a dir ? */
1921   if(is_dir($path)) {
1923     /* is this path a readable one */
1924     if(is_readable($path)){
1926       /* Get contents and write it into an array */   
1927       $ret = array();    
1929       $dir = opendir($path);
1931       /* Is this a correct result ?*/
1932       if($dir){
1933         while($fp = readdir($dir))
1934           $ret[]= $fp;
1935       }
1936     }
1937   }
1938   /* Sort array ascending , like scandir */
1939   sort($ret);
1941   /* Sort descending if parameter is sort_desc is set */
1942   if($sort_desc) {
1943     $ret = array_reverse($ret);
1944   }
1946   return($ret);
1949 function clean_smarty_compile_dir($directory)
1951   global $svn_revision;
1953   if(is_dir($directory) && is_readable($directory)) {
1954     // Set revision filename to REVISION
1955     $revision_file= $directory."/REVISION";
1957     /* Is there a stamp containing the current revision? */
1958     if(!file_exists($revision_file)) {
1959       // create revision file
1960       create_revision($revision_file, $svn_revision);
1961     } else {
1962 # check for "$config->...['CONFIG']/revision" and the
1963 # contents should match the revision number
1964       if(!compare_revision($revision_file, $svn_revision)){
1965         // If revision differs, clean compile directory
1966         foreach(scan_directory($directory) as $file) {
1967           if(($file==".")||($file=="..")) continue;
1968           if( is_file($directory."/".$file) &&
1969               is_writable($directory."/".$file)) {
1970             // delete file
1971             if(!unlink($directory."/".$file)) {
1972               print_red("File ".$directory."/".$file." could not be deleted.");
1973               // This should never be reached
1974             }
1975           } elseif(is_dir($directory."/".$file) &&
1976               is_writable($directory."/".$file)) {
1977             // Just recursively delete it
1978             rmdirRecursive($directory."/".$file);
1979           }
1980         }
1981         // We should now create a fresh revision file
1982         clean_smarty_compile_dir($directory);
1983       } else {
1984         // Revision matches, nothing to do
1985       }
1986     }
1987   } else {
1988     // Smarty compile dir is not accessible
1989     // (Smarty will warn about this)
1990   }
1993 function create_revision($revision_file, $revision)
1995   $result= false;
1997   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1998     if($fh= fopen($revision_file, "w")) {
1999       if(fwrite($fh, $revision)) {
2000         $result= true;
2001       }
2002     }
2003     fclose($fh);
2004   } else {
2005     print_red("Can not write to revision file");
2006   }
2008   return $result;
2011 function compare_revision($revision_file, $revision)
2013   // false means revision differs
2014   $result= false;
2016   if(file_exists($revision_file) && is_readable($revision_file)) {
2017     // Open file
2018     if($fh= fopen($revision_file, "r")) {
2019       // Compare File contents with current revision
2020       if($revision == fread($fh, filesize($revision_file))) {
2021         $result= true;
2022       }
2023     } else {
2024       print_red("Can not open revision file");
2025     }
2026     // Close file
2027     fclose($fh);
2028   }
2030   return $result;
2033 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2035   $str = ""; // Our return value will be saved in this var
2037   $color  = dechex($percentage+150);
2038   $color2 = dechex(150 - $percentage);
2039   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2041   $progress = (int)(($percentage /100)*$width);
2043   /* Abort printing out percentage, if divs are to small */
2046   /* If theres a better solution for this, use it... */
2047   $str = "
2048     <div style=\" width:".($width)."px; 
2049     height:".($height)."px;
2050   background-color:#000000;
2051 padding:1px;\">
2053           <div style=\" width:".($width)."px;
2054         background-color:#$bgcolor;
2055 height:".($height)."px;\">
2057          <div style=\" width:".$progress."px;
2058 height:".$height."px;
2059        background-color:#".$color2.$color2.$color."; \">";
2062        if(($height >10)&&($showvalue)){
2063          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2064            <b>".$percentage."%</b>
2065            </font>";
2066        }
2068        $str.= "</div></div></div>";
2070        return($str);
2074 function array_key_ics($ikey, $items)
2076   /* Gather keys, make them lowercase */
2077   $tmp= array();
2078   foreach ($items as $key => $value){
2079     $tmp[strtolower($key)]= $key;
2080   }
2082   if (isset($tmp[strtolower($ikey)])){
2083     return($tmp[strtolower($ikey)]);
2084   }
2086   return ("");
2090 function search_config($arr, $name, $return)
2092   if (is_array($arr)){
2093     foreach ($arr as $a){
2094       if (isset($a['CLASS']) &&
2095           strtolower($a['CLASS']) == strtolower($name)){
2097         if (isset($a[$return])){
2098           return ($a[$return]);
2099         } else {
2100           return ("");
2101         }
2102       } else {
2103         $res= search_config ($a, $name, $return);
2104         if ($res != ""){
2105           return $res;
2106         }
2107       }
2108     }
2109   }
2110   return ("");
2114 function array_differs($src, $dst)
2116   /* If the count is differing, the arrays differ */
2117   if (count ($src) != count ($dst)){
2118     return (TRUE);
2119   }
2121   /* So the count is the same - lets check the contents */
2122   $differs= FALSE;
2123   foreach($src as $value){
2124     if (!in_array($value, $dst)){
2125       $differs= TRUE;
2126     }
2127   }
2129   return ($differs);
2133 function saveFilter($a_filter, $values)
2135   if (isset($_POST['regexit'])){
2136     $a_filter["regex"]= $_POST['regexit'];
2138     foreach($values as $type){
2139       if (isset($_POST[$type])) {
2140         $a_filter[$type]= "checked";
2141       } else {
2142         $a_filter[$type]= "";
2143       }
2144     }
2145   }
2147   /* React on alphabet links if needed */
2148   if (isset($_GET['search'])){
2149     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2150     if ($s == "**"){
2151       $s= "*";
2152     }
2153     $a_filter['regex']= $s;
2154   }
2156   return ($a_filter);
2160 /* Escape all preg_* relevant characters */
2161 function normalizePreg($input)
2163   return (addcslashes($input, '[]()|/.*+-'));
2167 /* Escape all LDAP filter relevant characters */
2168 function normalizeLdap($input)
2170   return (addcslashes($input, '()|'));
2174 /* Resturns the difference between to microtime() results in float  */
2175 function get_MicroTimeDiff($start , $stop)
2177   $a = split("\ ",$start);
2178   $b = split("\ ",$stop);
2180   $secs = $b[1] - $a[1];
2181   $msecs= $b[0] - $a[0]; 
2183   $ret = (float) ($secs+ $msecs);
2184   return($ret);
2188 /* Check if the given department name is valid */
2189 function is_department_name_reserved($name,$base)
2191   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2192                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2193                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2194   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2196   /* Check if name is one of the reserved names */
2197   if(in_array_ics($name,$reservedName)) {
2198     return(true);
2199   }
2201   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2202   foreach($follwedNames as $key => $names){
2203     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2204       return(true);
2205     }
2206   }
2207   return(false);
2211 function is_php4()
2213   if (isset($_SESSION['PHP4COMPATIBLE'])){
2214     return true;
2215   }
2216   return (preg_match('/^4/', phpversion()));
2220 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2222   /* Initialize variables */
2223   $ret  = array("count" => 0);  // Set count to 0
2224   $next = true;                 // if false, then skip next loops and return
2225   $cnt  = 0;                    // Current number of loops
2226   $max  = 100;                  // Just for security, prevent looops
2227   $ldap = NULL;                 // To check if created result a valid
2228   $keep = "";                   // save last failed parse string
2230   /* Check each parsed dn in ldap ? */
2231   if($config!=NULL && $verify_in_ldap){
2232     $ldap = $config->get_ldap_link();
2233   }
2235   /* Lets start */
2236   $called = false;
2237   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2239     $cnt ++;
2240     if(!preg_match("/,/",$dn)){
2241       $next = false;
2242     }
2243     $object = preg_replace("/[,].*$/","",$dn);
2244     $dn     = preg_replace("/^[^,]+,/","",$dn);
2246     $called = true;
2248     /* Check if current dn is valid */
2249     if($ldap!=NULL){
2250       $ldap->cd($dn);
2251       $ldap->cat($dn,array("dn"));
2252       if($ldap->count()){
2253         $ret[]  = $keep.$object;
2254         $keep   = "";
2255       }else{
2256         $keep  .= $object.",";
2257       }
2258     }else{
2259       $ret[]  = $keep.$object;
2260       $keep   = "";
2261     }
2262   }
2264   /* No dn was posted */
2265   if($cnt == 0 && !empty($dn)){
2266     $ret[] = $dn;
2267   }
2269   /* Append the rest */
2270   $test = $keep.$dn;
2271   if($called && !empty($test)){
2272     $ret[] = $keep.$dn;
2273   }
2274   $ret['count'] = count($ret) - 1;
2276   return($ret);
2280 function get_base_from_hook($dn, $attrib)
2282   global $config;
2284   if (isset($config->current['BASE_HOOK'])){
2285     
2286     /* Call hook script - if present */
2287     $command= $config->current['BASE_HOOK'];
2289     if ($command != ""){
2290       $command.= " '$dn' $attrib";
2291       if (check_command($command)){
2292         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2293         exec($command, $output);
2294         if (preg_match("/^[0-9]+$/", $output[0])){
2295           return ($output[0]);
2296         } else {
2297           print_red(_("Warning - base_hook is not available. Using default base."));
2298           return ($config->current['UIDBASE']);
2299         }
2300       } else {
2301         print_red(_("Warning - base_hook is not available. Using default base."));
2302         return ($config->current['UIDBASE']);
2303       }
2305     } else {
2307       print_red(_("Warning - no base_hook defined. Using default base."));
2308       return ($config->current['UIDBASE']);
2310     }
2311   }
2314 /* Schema validation functions */
2316   function check_schema_version($class, $version)
2317   {
2318     return preg_match("/\(v$version\)/", $class['DESC']);
2319   }
2321   
2323   function check_schema($cfg,$rfc2307bis = FALSE)
2324   {
2326     $messages= array();
2328     /* Get objectclasses */
2329     $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2330     $objectclasses = $ldap->get_objectclasses();
2331     if(count($objectclasses) == 0){
2332       print_red(_("Can't get schema information from server. No schema check possible!"));
2333     }
2335     /* This is the default block used for each entry.
2336      *  to avoid unset indexes.
2337      */
2338     $def_check = array("REQUIRED_VERSION" => "0",
2339                        "SCHEMA_FILES"     => array(),
2340                        "CLASSES_REQUIRED" => array(),
2341                        "STATUS"           => FALSE,
2342                        "IS_MUST_HAVE"     => FALSE,
2343                        "MSG"              => "",
2344                        "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2346  /* The gosa base schema */
2347     $checks['gosaObject'] = $def_check;
2348     $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2349     $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2350     $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2351     $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2353     /* GOsa Account class */
2354     $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2355     $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2356     $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2357     $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2358     $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2360     /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2361     $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2362     $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2363     $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2364     $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2365     $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2367   /* Some other checks */
2368     foreach(array(
2369           "gosaCacheEntry"        => array("version" => "2.4"),
2370           "gosaDepartment"        => array("version" => "2.4"),
2371           "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2372           "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2373           "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2374           "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2375           "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2376           "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2377           "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2378           "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2379           "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2380           "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2381           "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2382           "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2383           "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2384           "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2385           "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2386           "goLdapServer"          => array("version" => "2.4"),
2387           "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2388           "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2389           "goKrbServer"           => array("version" => "2.4"),
2390           "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2391           ) as $name => $values){
2393       $checks[$name] = $def_check;
2394       if(isset($values['version'])){
2395         $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2396       }
2397       if(isset($values['file'])){
2398         $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2399       }
2400       $checks[$name]["CLASSES_REQUIRED"] = array($name);
2401     }
2402    foreach($checks as $name => $value){
2403       foreach($value['CLASSES_REQUIRED'] as $class){
2405         if(!isset($objectclasses[$name])){
2406           $checks[$name]['STATUS'] = FALSE;
2407           if($value['IS_MUST_HAVE']){
2408             $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2409           }else{
2410             $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2411           }
2412         }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2413           $checks[$name]['STATUS'] = FALSE;
2415           if($value['IS_MUST_HAVE']){
2416             $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2417           }else{
2418             $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2419           }
2420         }else{
2421           $checks[$name]['STATUS'] = TRUE;
2422           $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2423         }
2424       }
2425     }
2427     $tmp = $objectclasses;
2430     /* The gosa base schema */
2431     $checks['posixGroup'] = $def_check;
2432     $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2433     $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2434     $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2435     $checks['posixGroup']['STATUS']           = TRUE;
2436     $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2437     $checks['posixGroup']['MSG']              = "";
2438     $checks['posixGroup']['INFO']             = "";
2440     /* Depending on selected rfc2307bis mode, we need different schema configurations */
2441     if(isset($tmp['posixGroup'])){
2443       if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2444         $checks['posixGroup']['STATUS']           = FALSE;
2445         $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2446         $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2447       }
2448       if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2449         $checks['posixGroup']['STATUS']           = FALSE;
2450         $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2451         $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2452       }
2453     }
2455     return($checks);
2456   }
2459 function prepare4mailbody($string)
2461   $string = html_entity_decode($string);
2463   $from = array(
2464                 "/%/",
2465                 "/ /",
2466                 "/\n/",  
2467                 "/\r/",
2468                 "/!/",
2469                 "/#/",
2470                 "/\*/",
2471                 "/\//",
2472                 "/</",
2473                 "/>/",
2474                 "/\?/",
2475                 "/\&/",
2476                 "/\(/",
2477                 "/\)/",
2478                 "/\"/");
2479   
2480   $to = array(  
2481                 "%25",
2482                 "%20",
2483                 "%0A",
2484                 "%0D",
2485                 "%21",
2486                 "%23",
2487                 "%2A",
2488                 "%2F",
2489                 "%3C",
2490                 "%3E",
2491                 "%3F",
2492                 "%38",
2493                 "%28",
2494                 "%29",
2495                 "%22");
2497   $string = preg_replace($from,$to,$string);
2499   return($string);
2503 function mac2company($mac)
2505   $vendor= "";
2507   /* Generate a normailzed mac... */
2508   $mac= substr(preg_replace('/[:-]/', '', $mac), 0, 6);
2510   /* Check for existance of the oui file */
2511   if (!is_readable(CONFIG_DIR."/oui.txt")){
2512     return ("");
2513   }
2515   /* Open file and look for mac addresses... */
2516   $handle = @fopen(CONFIG_DIR."/oui.txt", "r");
2517   if ($handle) {
2518     while (!feof($handle)) {
2519       $line = fgets($handle, 4096);
2521       if (preg_match("/^$mac/i", $line)){
2522         $vendor= substr($line, 32);
2523       }
2524     }
2525     fclose($handle);
2526   }
2528   return ($vendor);
2532 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2534   $tmp = array(
2535         "de_DE" => "German",
2536         "fr_FR" => "French",
2537         "it_IT" => "Italian",
2538         "es_ES" => "Spanish",
2539         "en_US" => "English",
2540         "nl_NL" => "Dutch",
2541         "pl_PL" => "Polish",
2542         "sv_SE" => "Swedish",
2543         "zh_CN" => "Chinese",
2544         "ru_RU" => "Russian");
2545   
2546   $tmp2= array(
2547         "de_DE" => _("German"),
2548         "fr_FR" => _("French"),
2549         "it_IT" => _("Italian"),
2550         "es_ES" => _("Spanish"),
2551         "en_US" => _("English"),
2552         "nl_NL" => _("Dutch"),
2553         "pl_PL" => _("Polish"),
2554         "sv_SE" => _("Swedish"),
2555         "zh_CN" => _("Chinese"),
2556         "ru_RU" => _("Russian"));
2558   $ret = array();
2559   if($languages_in_own_language){
2561     $old_lang = setlocale(LC_ALL, 0);
2562     foreach($tmp as $key => $name){
2563       $lang = $key.".UTF-8";
2564       setlocale(LC_ALL, $lang);
2565       if($strip_region_tag){
2566         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2567       }else{
2568         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2569       }
2570     }
2571     setlocale(LC_ALL, $old_lang);
2572   }else{
2573     foreach($tmp as $key => $name){
2574       if($strip_region_tag){
2575         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2576       }else{
2577         $ret[$key] = _($name);
2578       }
2579     }
2580   }
2581   return($ret);
2585 /* Check if $ip1 and $ip2 represents a valid IP range 
2586  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2587  */
2588 function is_ip_range($ip1,$ip2)
2590   if(!is_ip($ip1) || !is_ip($ip2)){
2591     return(FALSE);
2592   }else{
2593     $ar1 = split("\.",$ip1);
2594     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2596     $ar2 = split("\.",$ip2);
2597     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2598     return($var1 < $var2);
2599   }
2603 /* Check if the specified IP address $address is inside the given network */
2604 function is_in_network($network, $netmask, $address)
2606   $nw= split('\.', $network);
2607   $nm= split('\.', $netmask);
2608   $ad= split('\.', $address);
2610   /* Generate inverted netmask */
2611   for ($i= 0; $i<4; $i++){
2612     $ni[$i]= 255-$nm[$i];
2613     $la[$i]= $nw[$i] | $ni[$i];
2614   }
2616   /* Transform to integer */
2617   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2618   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2619   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2621   return ($first < $curr&& $last > $curr);
2625 /* Returns contents of the given POST variable and check magic quotes settings */
2626 function get_post($name)
2628   if(!isset($_POST[$name])){
2629     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2630     return(FALSE);
2631   }
2632   if(get_magic_quotes_gpc()){
2633     return(stripcslashes($_POST[$name]));
2634   }else{
2635     return($_POST[$name]);
2636   }
2639 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2640 ?>