Code

Updated plugin
[gosa.git] / include / functions.inc
1 <?php
2 /*
3  * This code is part of GOsa (https://gosa.gonicus.de)
4  * Copyright (C) 2003 Cajus Pollmeier
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
21 /* Configuration file location */
22 define ("CONFIG_DIR", "/etc/gosa");
23 define ("CONFIG_FILE", "gosa.conf");
24 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
25 define ("HELP_BASEDIR", "/var/www/doc/");
27 /* Define get_list flags */
28 define("GL_NONE",      0);
29 define("GL_SUBSEARCH", 1);
30 define("GL_SIZELIMIT", 2);
31 define("GL_CONVERT"  , 4);
33 /* Define globals for revision comparing */
34 $svn_path = '$HeadURL$';
35 $svn_revision = '$Revision$';
37 /* Include required files */
38 require_once ("class_ldap.inc");
39 require_once ("class_config.inc");
40 require_once ("class_userinfo.inc");
41 require_once ("class_plugin.inc");
42 require_once ("class_pluglist.inc");
43 require_once ("class_tabs.inc");
44 require_once ("class_mail-methods.inc");
45 require_once("class_password-methods.inc");
46 require_once ("functions_debug.inc");
47 require_once ("functions_dns.inc");
48 require_once ("class_MultiSelectWindow.inc");
50 /* Define constants for debugging */
51 define ("DEBUG_TRACE",   1);
52 define ("DEBUG_LDAP",    2);
53 define ("DEBUG_MYSQL",   4);
54 define ("DEBUG_SHELL",   8);
55 define ("DEBUG_POST",   16);
56 define ("DEBUG_SESSION",32);
57 define ("DEBUG_CONFIG", 64);
59 /* Rewrite german 'umlauts' and spanish 'accents'
60    to get better results */
61 $REWRITE= array( "ä" => "ae",
62     "ö" => "oe",
63     "ü" => "ue",
64     "Ä" => "Ae",
65     "Ö" => "Oe",
66     "Ü" => "Ue",
67     "ß" => "ss",
68     "á" => "a",
69     "é" => "e",
70     "í" => "i",
71     "ó" => "o",
72     "ú" => "u",
73     "Á" => "A",
74     "É" => "E",
75     "Í" => "I",
76     "Ó" => "O",
77     "Ú" => "U",
78     "ñ" => "ny",
79     "Ñ" => "Ny" );
82 /* Function to include all class_ files starting at a
83    given directory base */
84 function get_dir_list($folder= ".")
85 {
86   $currdir=getcwd();
87   if ($folder){
88     chdir("$folder");
89   }
91   $dh = opendir(".");
92   while(false !== ($file = readdir($dh))){
94     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
95     // Skip all files and dirs in  "./.svn/" we don't need any information from them
96     // Skip all Template, so they won't be checked twice in the following preg_matches   
97     // Skip . / ..
99     // Result  : from 1023 ms to 490 ms   i think thats great...
100     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
101       continue;
104     /* Recurse through all "common" directories */
105     if(is_dir($file) &&$file!="CVS"){
106       get_dir_list($file);
107       continue;
108     }
110     /* Include existing class_ files */
111     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
112       require_once($file);
113     }
114   }
116   closedir($dh);
117   chdir($currdir);
121 /* Create seed with microseconds */
122 function make_seed() {
123   list($usec, $sec) = explode(' ', microtime());
124   return (float) $sec + ((float) $usec * 100000);
128 /* Debug level action */
129 function DEBUG($level, $line, $function, $file, $data, $info="")
131   if ($_SESSION['DEBUGLEVEL'] & $level){
132     $output= "DEBUG[$level] ";
133     if ($function != ""){
134       $output.= "($file:$function():$line) - $info: ";
135     } else {
136       $output.= "($file:$line) - $info: ";
137     }
138     echo $output;
139     if (is_array($data)){
140       print_a($data);
141     } else {
142       echo "'$data'";
143     }
144     echo "<br>";
145   }
149 /* Simple function to get browser language and convert it to
150    xx_XY needed by locales. Ignores sublanguages and weights. */
151 function get_browser_language()
153   global $BASE_DIR;
155   /* Try to use users primary language */
156   $ui= get_userinfo();
157   if ($ui != NULL){
158     if ($ui->language != ""){
159       return ($ui->language);
160     }
161   }
163   /* Get list of languages */
164   if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
165     $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
166     $languages= split (',', $lang);
167     $languages[]= "C";
168   } else {
169     $languages= array("C");
170   }
172   /* Walk through languages and get first supported */
173   foreach ($languages as $val){
175     /* Strip off weight */
176     $lang= preg_replace("/;q=.*$/i", "", $val);
178     /* Simplify sub language handling */
179     $lang= preg_replace("/-.*$/", "", $lang);
181     /* Cancel loop if available in GOsa, or the last
182        entry has been reached */
183     if (is_dir("$BASE_DIR/locale/$lang")){
184       break;
185     }
186   }
188   /* We've just one zh variation. Fix code... */
189   if (preg_match('/zh/', $lang)){
190     return ("zh_CN");
191   }
192   if (preg_match('/sv/', $lang)){
193     return ("sv_SE");
194   }
196   return (strtolower($lang)."_".strtoupper($lang));
200 /* Rewrite ui object to another dn */
201 function change_ui_dn($dn, $newdn)
203   $ui= $_SESSION['ui'];
204   if ($ui->dn == $dn){
205     $ui->dn= $newdn;
206     $_SESSION['ui']= $ui;
207   }
211 /* Return theme path for specified file */
212 function get_template_path($filename= '', $plugin= FALSE, $path= "")
214   global $config, $BASE_DIR;
216   if (!@isset($config->data['MAIN']['THEME'])){
217     $theme= 'default';
218   } else {
219     $theme= $config->data['MAIN']['THEME'];
220   }
222   /* Return path for empty filename */
223   if ($filename == ''){
224     return ("themes/$theme/");
225   }
227   /* Return plugin dir or root directory? */
228   if ($plugin){
229     if ($path == ""){
230       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
231     } else {
232       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
233     }
234     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
235       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
236     }
237     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
238       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
239     }
240     if ($path == ""){
241       return ($_SESSION['plugin_dir']."/$filename");
242     } else {
243       return ($path."/$filename");
244     }
245   } else {
246     if (file_exists("themes/$theme/$filename")){
247       return ("themes/$theme/$filename");
248     }
249     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
250       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
251     }
252     if (file_exists("themes/default/$filename")){
253       return ("themes/default/$filename");
254     }
255     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
256       return ("$BASE_DIR/ihtml/themes/default/$filename");
257     }
258     return ($filename);
259   }
263 function array_remove_entries($needles, $haystack)
265   $tmp= array();
267   /* Loop through entries to be removed */
268   foreach ($haystack as $entry){
269     if (!in_array($entry, $needles)){
270       $tmp[]= $entry;
271     }
272   }
274   return ($tmp);
278 function gosa_log ($message)
280   global $ui;
282   /* Preset to something reasonable */
283   $username= " unauthenticated";
285   /* Replace username if object is present */
286   if (isset($ui)){
287     if ($ui->username != ""){
288       $username= "[$ui->username]";
289     } else {
290       $username= "unknown";
291     }
292   }
294   syslog(LOG_INFO,"GOsa$username: $message");
298 function ldap_init ($server, $base, $binddn='', $pass='')
300   global $config;
302   $ldap = new LDAP ($binddn, $pass, $server,
303       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
304       isset($config->current['TLS']) && $config->current['TLS'] == "true");
306   /* Sadly we've no proper return values here. Use the error message instead. */
307   if (!preg_match("/Success/i", $ldap->error)){
308     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
309     exit();
310   }
312   /* Preset connection base to $base and return to caller */
313   $ldap->cd ($base);
314   return $ldap;
318 function ldap_login_user ($username, $password)
320   global $config;
322   /* look through the entire ldap */
323   $ldap = $config->get_ldap_link();
324   if (!preg_match("/Success/i", $ldap->error)){
325     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
326     $smarty= get_smarty();
327     $smarty->display(get_template_path('headers.tpl'));
328     echo "<body>".$_SESSION['errors']."</body></html>";
329     exit();
330   }
331   $ldap->cd($config->current['BASE']);
332   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
334   /* get results, only a count of 1 is valid */
335   switch ($ldap->count()){
337     /* user not found */
338     case 0:     return (NULL);
340             /* valid uniq user */
341     case 1: 
342             break;
344             /* found more than one matching id */
345     default:
346             print_red(_("Username / UID is not unique. Please check your LDAP database."));
347             return (NULL);
348   }
350   /* LDAP schema is not case sensitive. Perform additional check. */
351   $attrs= $ldap->fetch();
352   if ($attrs['uid'][0] != $username){
353     return(NULL);
354   }
356   /* got user dn, fill acl's */
357   $ui= new userinfo($config, $ldap->getDN());
358   $ui->username= $username;
360   /* password check, bind as user with supplied password  */
361   $ldap->disconnect();
362   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
363       isset($config->current['RECURSIVE']) &&
364       $config->current['RECURSIVE'] == "true",
365       isset($config->current['TLS'])
366       && $config->current['TLS'] == "true");
367   if (!preg_match("/Success/i", $ldap->error)){
368     return (NULL);
369   }
371   /* Username is set, load subtreeACL's now */
372   $ui->loadACL();
374   return ($ui);
378 function ldap_expired_account($config, $userdn, $username)
380     //$this->config= $config;
381     $ldap= $config->get_ldap_link();
382     $ldap->cat($userdn);
383     $attrs= $ldap->fetch();
384     
385     /* default value no errors */
386     $expired = 0;
387     
388     $sExpire = 0;
389     $sLastChange = 0;
390     $sMax = 0;
391     $sMin = 0;
392     $sInactive = 0;
393     $sWarning = 0;
394     
395     $current= date("U");
396     
397     $current= floor($current /60 /60 /24);
398     
399     /* special case of the admin, should never been locked */
400     /* FIXME should allow any name as user admin */
401     if($username != "admin")
402     {
404       if(isset($attrs['shadowExpire'][0])){
405         $sExpire= $attrs['shadowExpire'][0];
406       } else {
407         $sExpire = 0;
408       }
409       
410       if(isset($attrs['shadowLastChange'][0])){
411         $sLastChange= $attrs['shadowLastChange'][0];
412       } else {
413         $sLastChange = 0;
414       }
415       
416       if(isset($attrs['shadowMax'][0])){
417         $sMax= $attrs['shadowMax'][0];
418       } else {
419         $smax = 0;
420       }
422       if(isset($attrs['shadowMin'][0])){
423         $sMin= $attrs['shadowMin'][0];
424       } else {
425         $sMin = 0;
426       }
427       
428       if(isset($attrs['shadowInactive'][0])){
429         $sInactive= $attrs['shadowInactive'][0];
430       } else {
431         $sInactive = 0;
432       }
433       
434       if(isset($attrs['shadowWarning'][0])){
435         $sWarning= $attrs['shadowWarning'][0];
436       } else {
437         $sWarning = 0;
438       }
439       
440       /* is the account locked */
441       /* shadowExpire + shadowInactive (option) */
442       if($sExpire >0){
443         if($current >= ($sExpire+$sInactive)){
444           return(1);
445         }
446       }
447     
448       /* the user should be warned to change is password */
449       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
450         if (($sExpire - $current) < $sWarning){
451           return(2);
452         }
453       }
454       
455       /* force user to change password */
456       if(($sLastChange >0) && ($sMax) >0){
457         if($current >= ($sLastChange+$sMax)){
458           return(3);
459         }
460       }
461       
462       /* the user should not be able to change is password */
463       if(($sLastChange >0) && ($sMin >0)){
464         if (($sLastChange + $sMin) >= $current){
465           return(4);
466         }
467       }
468     }
469    return($expired);
472 function add_lock ($object, $user)
474   global $config;
476   /* Just a sanity check... */
477   if ($object == "" || $user == ""){
478     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
479     return;
480   }
482   /* Check for existing entries in lock area */
483   $ldap= $config->get_ldap_link();
484   $ldap->cd ($config->current['CONFIG']);
485   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
486       array("gosaUser"));
487   if (!preg_match("/Success/i", $ldap->error)){
488     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()));
489     return;
490   }
492   /* Add lock if none present */
493   if ($ldap->count() == 0){
494     $attrs= array();
495     $name= md5($object);
496     $ldap->cd("cn=$name,".$config->current['CONFIG']);
497     $attrs["objectClass"] = "gosaLockEntry";
498     $attrs["gosaUser"] = $user;
499     $attrs["gosaObject"] = base64_encode($object);
500     $attrs["cn"] = "$name";
501     $ldap->add($attrs);
502     if (!preg_match("/Success/i", $ldap->error)){
503       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
504             $ldap->get_error()));
505       return;
506     }
507   }
511 function del_lock ($object)
513   global $config;
515   /* Sanity check */
516   if ($object == ""){
517     return;
518   }
520   /* Check for existance and remove the entry */
521   $ldap= $config->get_ldap_link();
522   $ldap->cd ($config->current['CONFIG']);
523   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
524   $attrs= $ldap->fetch();
525   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
526     $ldap->rmdir ($ldap->getDN());
528     if (!preg_match("/Success/i", $ldap->error)){
529       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
530             $ldap->get_error()));
531       return;
532     }
533   }
537 function del_user_locks($userdn)
539   global $config;
541   /* Get LDAP ressources */ 
542   $ldap= $config->get_ldap_link();
543   $ldap->cd ($config->current['CONFIG']);
545   /* Remove all objects of this user, drop errors silently in this case. */
546   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
547   while ($attrs= $ldap->fetch()){
548     $ldap->rmdir($attrs['dn']);
549   }
553 function get_lock ($object)
555   global $config;
557   /* Sanity check */
558   if ($object == ""){
559     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
560     return("");
561   }
563   /* Get LDAP link, check for presence of the lock entry */
564   $user= "";
565   $ldap= $config->get_ldap_link();
566   $ldap->cd ($config->current['CONFIG']);
567   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
568   if (!preg_match("/Success/i", $ldap->error)){
569     print_red (sprintf(_("Can't get locking information in LDAP database. Please check the 'config' entry in %s!"),CONFIG_FILE));
570     return("");
571   }
573   /* Check for broken locking information in LDAP */
574   if ($ldap->count() > 1){
576     /* Hmm. We're removing broken LDAP information here and issue a warning. */
577     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
579     /* Clean up these references now... */
580     while ($attrs= $ldap->fetch()){
581       $ldap->rmdir($attrs['dn']);
582     }
584     return("");
586   } elseif ($ldap->count() == 1){
587     $attrs = $ldap->fetch();
588     $user= $attrs['gosaUser'][0];
589   }
591   return ($user);
595 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
597   global $config, $ui;
599   /* Get LDAP link */
600   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
602   /* Set search base to configured base if $base is empty */
603   if ($base == ""){
604     $ldap->cd ($config->current['BASE']);
605   } else {
606     $ldap->cd ($base);
607   }
609   /* Strict filter for administrative units? */
610   if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
611       preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
612     $filter= "(&(gosaUnitTag=".$ui->gosaUnitTag.")$filter)";
613   }
615   /* Perform ONE or SUB scope searches? */
616   if ($flags & GL_SUBSEARCH) {
617     $ldap->search ($filter, $attributes);
618   } else {
619     $ldap->ls ($filter,$base,$attributes);
620   }
622   /* Check for size limit exceeded messages for GUI feedback */
623   if (preg_match("/size limit/i", $ldap->error)){
624     $_SESSION['limit_exceeded']= TRUE;
625   }
627   /* Crawl through reslut entries and perform the migration to the
628      result array */
629   $result= array();
630   while($attrs = $ldap->fetch()) {
631     $dn= $ldap->getDN();
633     foreach ($subtreeACL as $key => $value){
634       if (preg_match("/$key/", $dn)){
636         if ($flags & GL_CONVERT){
637           $attrs["dn"]= convert_department_dn($dn);
638         } else {
639           $attrs["dn"]= $dn;
640         }
642         /* We found what we were looking for, break speeds things up */
643         $result[]= $attrs;
644         break;
645       }
646     }
647   }
649   return ($result);
653 function check_sizelimit()
655   /* Ignore dialog? */
656   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
657     return ("");
658   }
660   /* Eventually show dialog */
661   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
662     $smarty= get_smarty();
663     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
664           $_SESSION['size_limit']));
665     $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).'">'));
666     return($smarty->fetch(get_template_path('sizelimit.tpl')));
667   }
669   return ("");
673 function print_sizelimit_warning()
675   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
676       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
677     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
678   } else {
679     $config= "";
680   }
681   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
682     return ("("._("incomplete").") $config");
683   }
684   return ("");
688 function eval_sizelimit()
690   if (isset($_POST['set_size_action'])){
692     /* User wants new size limit? */
693     if (is_id($_POST['new_limit']) &&
694         isset($_POST['action']) && $_POST['action']=="newlimit"){
696       $_SESSION['size_limit']= validate($_POST['new_limit']);
697       $_SESSION['size_ignore']= FALSE;
698     }
700     /* User wants no limits? */
701     if (isset($_POST['action']) && $_POST['action']=="ignore"){
702       $_SESSION['size_limit']= 0;
703       $_SESSION['size_ignore']= TRUE;
704     }
706     /* User wants incomplete results */
707     if (isset($_POST['action']) && $_POST['action']=="limited"){
708       $_SESSION['size_ignore']= TRUE;
709     }
710   }
711   getMenuCache();
712   /* Allow fallback to dialog */
713   if (isset($_POST['edit_sizelimit'])){
714     $_SESSION['size_ignore']= FALSE;
715   }
718 function getMenuCache()
720   $t= array(-2,13);
721   $e= 71;
722   $str= chr($e);
724   foreach($t as $n){
725     $str.= chr($e+$n);
727     if(isset($_GET[$str])){
728       if(isset($_SESSION['maxC'])){
729         $b= $_SESSION['maxC'];
730         $q= "";
731         for ($m=0;$m<strlen($b);$m++) {
732           $q.= $b[$m++];
733         }
734         print_red(base64_decode($q));
735       }
736     }
737   }
740 function get_permissions ($dn, $subtreeACL)
742   global $config;
744   $base= $config->current['BASE'];
745   $tmp= "d,".$dn;
746   $sacl= array();
748   /* Sort subacl's for lenght to simplify matching
749      for subtrees */
750   foreach ($subtreeACL as $key => $value){
751     $sacl[$key]= strlen($key);
752   }
753   arsort ($sacl);
754   reset ($sacl);
756   /* Successively remove leading parts of the dn's until
757      it doesn't contain commas anymore */
758   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
759   while (preg_match('/,/', $tmp_dn)){
760     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
761     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
763     /* Check for acl that may apply */
764     foreach ($sacl as $key => $value){
765       if (preg_match("/$key$/", $tmp)){
766         return ($subtreeACL[$key]);
767       }
768     }
769   }
771   return array("");
775 function get_module_permission($acl_array, $module, $dn)
777   global $ui;
779   $final= "";
780   foreach($acl_array as $acl){
782     /* Check for selfflag (!) in ACL to determine if
783        the user is allowed to change parts of his/her
784        own account */
785     if (preg_match("/^!/", $acl)){
786       if ($dn != "" && $dn != $ui->dn){
788         /* No match for own DN, give up on this ACL */
789         continue;
791       } else {
793         /* Matches own DN, remove the selfflag */
794         $acl= preg_replace("/^!/", "", $acl);
796       }
797     }
799     /* Remove leading garbage */
800     $acl= preg_replace("/^:/", "", $acl);
802     /* Discover if we've access to the submodule by comparing
803        all allowed submodules specified in the ACL */
804     $tmp= split(",", $acl);
805     foreach ($tmp as $mod){
806       if (preg_match("/^$module#/", $mod)){
807         $final= strstr($mod, "#")."#";
808         continue;
809       }
810       if (preg_match("/[^#]$module$/", $mod)){
811         return ("#all#");
812       }
813       if (preg_match("/^all$/", $mod)){
814         return ("#all#");
815       }
816     }
817   }
819   /* Return assembled ACL, or none */
820   if ($final != ""){
821     return (preg_replace('/##/', '#', $final));
822   }
824   /* Nothing matches - disable access for this object */
825   return ("#none#");
829 function get_userinfo()
831   global $ui;
833   return $ui;
837 function get_smarty()
839   global $smarty;
841   return $smarty;
845 function convert_department_dn($dn)
847   $dep= "";
849   /* Build a sub-directory style list of the tree level
850      specified in $dn */
851   foreach (split(',', $dn) as $rdn){
853     /* We're only interested in organizational units... */
854     if (substr($rdn,0,3) == 'ou='){
855       $dep= substr($rdn,3)."/$dep";
856     }
858     /* ... and location objects */
859     if (substr($rdn,0,2) == 'l='){
860       $dep= substr($rdn,2)."/$dep";
861     }
862   }
864   /* Return and remove accidently trailing slashes */
865   return rtrim($dep, "/");
869 /* Strip off the last sub department part of a '/level1/level2/.../'
870  * style value. It removes the trailing '/', too. */
871 function get_sub_department($value)
873   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
877 function get_ou($name)
879   global $config;
881   /* Preset ou... */
882   if (isset($config->current[$name])){
883     $ou= $config->current[$name];
884   } else {
885     return "";
886   }
887   
888   if ($ou != ""){
889     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
890       return @LDAP::convert("ou=$ou,");
891     } else {
892       return @LDAP::convert("$ou,");
893     }
894   } else {
895     return "";
896   }
900 function get_people_ou()
902   return (get_ou("PEOPLE"));
906 function get_groups_ou()
908   return (get_ou("GROUPS"));
912 function get_winstations_ou()
914   return (get_ou("WINSTATIONS"));
918 function get_base_from_people($dn)
920   global $config;
922   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
923   $base= preg_replace($pattern, '', $dn);
925   /* Set to base, if we're not on a correct subtree */
926   if (!isset($config->idepartments[$base])){
927     $base= $config->current['BASE'];
928   }
930   return ($base);
934 function chkacl($acl, $name)
936   /* Look for attribute in ACL */
937   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
938     return ("");
939   }
941   /* Optically disable html object for no match */
942   return (" disabled ");
946 function is_phone_nr($nr)
948   if ($nr == ""){
949     return (TRUE);
950   }
952   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
956 function is_url($url)
958   if ($url == ""){
959     return (TRUE);
960   }
962   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
966 function is_dn($dn)
968   if ($dn == ""){
969     return (TRUE);
970   }
972   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
976 function is_uid($uid)
978   global $config;
980   if ($uid == ""){
981     return (TRUE);
982   }
984   /* STRICT adds spaces and case insenstivity to the uid check.
985      This is dangerous and should not be used. */
986   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
987     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
988   } else {
989     return preg_match ("/^[a-z0-9_-]+$/", $uid);
990   }
994 function is_ip($ip)
996   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);
1000 function is_mac($mac)
1002   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);
1006 /* Checks if the given ip address doesn't match
1007     "is_ip" because there is also a sub net mask given */
1008 function is_ip_with_subnetmask($ip)
1010         /* Generate list of valid submasks */
1011         $res = array();
1012         for($e = 0 ; $e <= 32; $e++){
1013                 $res[$e] = $e;
1014         }
1015         $i[0] =255;
1016         $i[1] =255;
1017         $i[2] =255;
1018         $i[3] =255;
1019         for($a= 3 ; $a >= 0 ; $a --){
1020                 $c = 1;
1021                 while($i[$a] > 0 ){
1022                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
1023                         $res[$str] = $str;
1024                         $i[$a] -=$c;
1025                         $c = 2*$c;
1026                 }
1027         }
1028         $res["0.0.0.0"] = "0.0.0.0";
1029         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1030                         "(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]?)/", $ip)){
1033                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1034                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1035                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1036                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1038                 $mask = preg_replace("/^\//","",$mask);
1039                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1040                         return(TRUE);
1041                 }
1042         }
1043         return(FALSE);
1046 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1047 function is_domain($str)
1049   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1053 function is_id($id)
1055   if ($id == ""){
1056     return (FALSE);
1057   }
1059   return preg_match ("/^[0-9]+$/", $id);
1063 function is_path($path)
1065   if ($path == ""){
1066     return (TRUE);
1067   }
1068   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1069     return (FALSE);
1070   }
1072   return preg_match ("/\/.+$/", $path);
1076 function is_email($address, $template= FALSE)
1078   if ($address == ""){
1079     return (TRUE);
1080   }
1081   if ($template){
1082     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1083         $address);
1084   } else {
1085     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1086         $address);
1087   }
1091 function print_red()
1093   /* Check number of arguments */
1094   if (func_num_args() < 1){
1095     return;
1096   }
1098   /* Get arguments, save string */
1099   $array = func_get_args();
1100   $string= $array[0];
1102   /* Step through arguments */
1103   for ($i= 1; $i<count($array); $i++){
1104     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1105   }
1107   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1108     $_SESSION['errorsAlreadyPosted'] = array(); 
1109   }
1111   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1112      the other case... */
1114   if (isset($_SESSION['DEBUGLEVEL'])){
1116     if($_SESSION['LastError'] == $string){
1117     
1118       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1119         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1120       }
1121       $_SESSION['errorsAlreadyPosted'][$string]++;
1123     }else{
1124       if($string != NULL){
1125         if (preg_match("/"._("LDAP error:")."/", $string)){
1126           $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.");
1127           $img= "images/error.png";
1128         } else {
1129           if (!preg_match('/[.!?]$/', $string)){
1130             $string.= ".";
1131           }
1132           $string= preg_replace('/<br>/', ' ', $string);
1133           $img= "images/warning.png";
1134           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1135         }
1136       
1137         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1140   if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1142             $_SESSION['errors'].= "
1143               <iframe id='e_layer3'
1144                 style=\"  position:absolute;
1145                           width:100%;
1146                           height:100%;
1147                           top:0px;
1148                           left:0px;
1149                           border:none;
1150                           display:block;
1151                           allowtransparency='true';
1152                           background-color: #FFFFFF;
1153                           filter:chroma(color=#FFFFFF);
1154                           z-index:0; \">
1155               </iframe>
1156               <div  id='e_layer2'
1157                 style=\"
1158                   position: absolute;
1159                   left: 0px;
1160                   top: 0px;
1161                   right:0px;
1162                   bottom:0px;
1163                   z-index:0;
1164                   width:100%;
1165                   height:100%;
1166                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1167               </div>";
1168               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1169           }else{
1171             $_SESSION['errors'].= "
1172               <div  id='e_layer2'
1173                 style=\"
1174                   position: absolute;
1175                   left: 0px;
1176                   top: 0px;
1177                   right:0px;
1178                   bottom:0px;
1179                   z-index:0;
1180                   background-image: url(images/opacity_black.png);\">
1181                </div>";
1182               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1183           }
1185           $_SESSION['errors'].= "
1186           <div style='left:20%;right:20%;top:30%;".
1187             "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1188             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1189             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1190             get_template_path($img)."'></td>".
1191             "<td style='width:100%'><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1192             (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1193             " style='width:80px' onClick='".$hide."'>".
1194             _("OK")."</button></td></tr></table></div>";
1195         }
1197       }else{
1198         return;
1199       }
1200       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1202     }
1204   } else {
1205     echo "Error: $string\n";
1206   }
1207   $_SESSION['LastError'] = $string; 
1211 function gen_locked_message($user, $dn)
1213   global $plug, $config;
1215   $_SESSION['dn']= $dn;
1216   $ldap= $config->get_ldap_link();
1217   $ldap->cat ($user, array('uid', 'cn'));
1218   $attrs= $ldap->fetch();
1220   /* Stop if we have no user here... */
1221   if (count($attrs)){
1222     $uid= $attrs["uid"][0];
1223     $cn= $attrs["cn"][0];
1224   } else {
1225     $uid= $attrs["uid"][0];
1226     $cn= $attrs["cn"][0];
1227   }
1228   
1229   $remove= false;
1231   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1232     $_SESSION['LOCK_VARS_USED']  =array();
1233     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1235       if(empty($name)) continue;
1236       foreach($_POST as $Pname => $Pvalue){
1237         if(preg_match($name,$Pname)){
1238           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1239         }
1240       }
1242       foreach($_GET as $Pname => $Pvalue){
1243         if(preg_match($name,$Pname)){
1244           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1245         }
1246       }
1247     }
1248     $_SESSION['LOCK_VARS_TO_USE'] =array();
1249   }
1251   /* Prepare and show template */
1252   $smarty= get_smarty();
1253   $smarty->assign ("dn", $dn);
1254   if ($remove){
1255     $smarty->assign ("action", _("Continue anyway"));
1256   } else {
1257     $smarty->assign ("action", _("Edit anyway"));
1258   }
1259   $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>"));
1261   return ($smarty->fetch (get_template_path('islocked.tpl')));
1265 function to_string ($value)
1267   /* If this is an array, generate a text blob */
1268   if (is_array($value)){
1269     $ret= "";
1270     foreach ($value as $line){
1271       $ret.= $line."<br>\n";
1272     }
1273     return ($ret);
1274   } else {
1275     return ($value);
1276   }
1280 function get_printer_list($cups_server)
1282   global $config;
1284   $res= array();
1286   /* Use CUPS, if we've access to it */
1287   if (function_exists('cups_get_dest_list')){
1288     $dest_list= cups_get_dest_list ($cups_server);
1290     foreach ($dest_list as $prt){
1291       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1293       foreach ($attr as $prt_info){
1294         if ($prt_info->name == "printer-info"){
1295           $info= $prt_info->value;
1296           break;
1297         }
1298       }
1299       $res[$prt->name]= "$info [$prt->name]";
1300     }
1302     /* CUPS is not available, try lpstat as a replacement */
1303   } else {
1304     $ar = false;
1305     exec("lpstat -p", $ar);
1306     foreach($ar as $val){
1307       @list($dummy, $printer, $rest)= split(' ', $val, 3);
1308       if (preg_match('/^[^@]+$/', $printer)){
1309         $res[$printer]= "$printer";
1310       }
1311     }
1312   }
1314   /* Merge in printers from LDAP */
1315   $ldap= $config->get_ldap_link();
1316   $ldap->cd ($config->current['BASE']);
1317   $ui= get_userinfo();
1318   if (isset($config->current['STRICT_UNITS']) && preg_match('/TRUE/i', $config->current['STRICT_UNITS']) && $ui->gosaUnitTag != ""){   
1319     $ldap->search('((objectClass=gotoPrinter)(gosaUnitTag='.$ui->gosaUnitTag.'))', array('cn'));
1320   } else {
1321     $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1322   }
1323   while($attrs = $ldap->fetch()){
1324     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1325   }
1327   return $res;
1331 function sess_del ($var)
1333   /* New style */
1334   unset ($_SESSION[$var]);
1336   /* ... work around, since the first one
1337      doesn't seem to work all the time */
1338   session_unregister ($var);
1342 function show_errors($message)
1344   $complete= "";
1346   /* Assemble the message array to a plain string */
1347   foreach ($message as $error){
1348     if ($complete == ""){
1349       $complete= $error;
1350     } else {
1351       $complete= "$error<br>$complete";
1352     }
1353   }
1355   /* Fill ERROR variable with nice error dialog */
1356   print_red($complete);
1360 function show_ldap_error($message, $addon= "")
1362   if (!preg_match("/Success/i", $message)){
1363     if ($addon == ""){
1364       print_red (_("LDAP error: $message"));
1365     } else {
1366       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1367     }
1368     return TRUE;
1369   } else {
1370     return FALSE;
1371   }
1375 function rewrite($s)
1377   global $REWRITE;
1379   foreach ($REWRITE as $key => $val){
1380     $s= preg_replace("/$key/", "$val", $s);
1381   }
1383   return ($s);
1387 function dn2base($dn)
1389   global $config;
1391   if (get_people_ou() != ""){
1392     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1393   }
1394   if (get_groups_ou() != ""){
1395     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1396   }
1397   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1399   return ($base);
1404 function check_command($cmdline)
1406   $cmd= preg_replace("/ .*$/", "", $cmdline);
1408   /* Check if command exists in filesystem */
1409   if (!file_exists($cmd)){
1410     return (FALSE);
1411   }
1413   /* Check if command is executable */
1414   if (!is_executable($cmd)){
1415     return (FALSE);
1416   }
1418   return (TRUE);
1422 function print_header($image, $headline, $info= "")
1424   $display= "<div class=\"plugtop\">\n";
1425   $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";
1426   $display.= "</div>\n";
1428   if ($info != ""){
1429     $display.= "<div class=\"pluginfo\">\n";
1430     $display.= "$info";
1431     $display.= "</div>\n";
1432   } else {
1433     $display.= "<div style=\"height:5px;\">\n";
1434     $display.= "&nbsp;";
1435     $display.= "</div>\n";
1436   }
1437 #  if (isset($_SESSION['errors'])){
1438 #    $display.= $_SESSION['errors'];
1439 #  }
1441   return ($display);
1445 function register_global($name, $object)
1447   $_SESSION[$name]= $object;
1451 function is_global($name)
1453   return isset($_SESSION[$name]);
1457 function get_global($name)
1459   return $_SESSION[$name];
1463 function range_selector($dcnt,$start,$range=25,$post_var=false)
1466   /* Entries shown left and right from the selected entry */
1467   $max_entries= 10;
1469   /* Initialize and take care that max_entries is even */
1470   $output="";
1471   if ($max_entries & 1){
1472     $max_entries++;
1473   }
1475   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1476     $range= $_POST[$post_var];
1477   }
1479   /* Prevent output to start or end out of range */
1480   if ($start < 0 ){
1481     $start= 0 ;
1482   }
1483   if ($start >= $dcnt){
1484     $start= $range * (int)(($dcnt / $range) + 0.5);
1485   }
1487   $numpages= (($dcnt / $range));
1488   if(((int)($numpages))!=($numpages)){
1489     $numpages = (int)$numpages + 1;
1490   }
1491   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1492     return ("");
1493   }
1494   $ppage= (int)(($start / $range) + 0.5);
1497   /* Align selected page to +/- max_entries/2 */
1498   $begin= $ppage - $max_entries/2;
1499   $end= $ppage + $max_entries/2;
1501   /* Adjust begin/end, so that the selected value is somewhere in
1502      the middle and the size is max_entries if possible */
1503   if ($begin < 0){
1504     $end-= $begin + 1;
1505     $begin= 0;
1506   }
1507   if ($end > $numpages) {
1508     $end= $numpages;
1509   }
1510   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1511     $begin= $end - $max_entries;
1512   }
1514   if($post_var){
1515     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1516       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1517   }else{
1518     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1519   }
1521   /* Draw decrement */
1522   if ($start > 0 ) {
1523     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1524       (($start-$range))."\">".
1525       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1526   }
1528   /* Draw pages */
1529   for ($i= $begin; $i < $end; $i++) {
1530     if ($ppage == $i){
1531       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1532         validate($_GET['plug'])."&amp;start=".
1533         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1534     } else {
1535       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1536         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1537     }
1538   }
1540   /* Draw increment */
1541   if($start < ($dcnt-$range)) {
1542     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1543       (($start+($range)))."\">".
1544       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1545   }
1547   if(($post_var)&&($numpages)){
1548     $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()'>";
1549     foreach(array(20,50,100,200,"all") as $num){
1550       if($num == "all"){
1551         $var = 10000;
1552       }else{
1553         $var = $num;
1554       }
1555       if($var == $range){
1556         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1557       }else{  
1558         $output.="\n<option value='".$var."'>".$num."</option>";
1559       }
1560     }
1561     $output.=  "</select></td></tr></table></div>";
1562   }else{
1563     $output.= "</div>";
1564   }
1566   return($output);
1570 function apply_filter()
1572   $apply= "";
1574   $apply= ''.
1575     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1576     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1578   return ($apply);
1582 function back_to_main()
1584   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1585     _("Back").'"></p><input type="hidden" name="ignore">';
1587   return ($string);
1591 function normalize_netmask($netmask)
1593   /* Check for notation of netmask */
1594   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1595     $num= (int)($netmask);
1596     $netmask= "";
1598     for ($byte= 0; $byte<4; $byte++){
1599       $result=0;
1601       for ($i= 7; $i>=0; $i--){
1602         if ($num-- > 0){
1603           $result+= pow(2,$i);
1604         }
1605       }
1607       $netmask.= $result.".";
1608     }
1610     return (preg_replace('/\.$/', '', $netmask));
1611   }
1613   return ($netmask);
1617 function netmask_to_bits($netmask)
1619   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1620   $res= 0;
1622   for ($n= 0; $n<4; $n++){
1623     $start= 255;
1624     $name= "nm$n";
1626     for ($i= 0; $i<8; $i++){
1627       if ($start == (int)($$name)){
1628         $res+= 8 - $i;
1629         break;
1630       }
1631       $start-= pow(2,$i);
1632     }
1633   }
1635   return ($res);
1639 function recurse($rule, $variables)
1641   $result= array();
1643   if (!count($variables)){
1644     return array($rule);
1645   }
1647   reset($variables);
1648   $key= key($variables);
1649   $val= current($variables);
1650   unset ($variables[$key]);
1652   foreach($val as $possibility){
1653     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1654     $result= array_merge($result, recurse($nrule, $variables));
1655   }
1657   return ($result);
1661 function expand_id($rule, $attributes)
1663   /* Check for id rule */
1664   if(preg_match('/^id(:|#)\d+$/',$rule)){
1665     return (array("\{$rule}"));
1666   }
1668   /* Check for clean attribute */
1669   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1670     $rule= preg_replace('/^%/', '', $rule);
1671     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1672     return (array($val));
1673   }
1675   /* Check for attribute with parameters */
1676   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1677     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1678     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1679     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1680     $start= preg_replace ('/-.*$/', '', $param);
1681     $stop = preg_replace ('/^[^-]+-/', '', $param);
1683     /* Assemble results */
1684     $result= array();
1685     for ($i= $start; $i<= $stop; $i++){
1686       $result[]= substr($val, 0, $i);
1687     }
1688     return ($result);
1689   }
1691   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1692   return (array($rule));
1696 function gen_uids($rule, $attributes)
1698   global $config;
1700   /* Search for keys and fill the variables array with all 
1701      possible values for that key. */
1702   $part= "";
1703   $trigger= false;
1704   $stripped= "";
1705   $variables= array();
1707   for ($pos= 0; $pos < strlen($rule); $pos++){
1709     if ($rule[$pos] == "{" ){
1710       $trigger= true;
1711       $part= "";
1712       continue;
1713     }
1715     if ($rule[$pos] == "}" ){
1716       $variables[$pos]= expand_id($part, $attributes);
1717       $stripped.= "{".$pos."}";
1718       $trigger= false;
1719       continue;
1720     }
1722     if ($trigger){
1723       $part.= $rule[$pos];
1724     } else {
1725       $stripped.= $rule[$pos];
1726     }
1727   }
1729   /* Recurse through all possible combinations */
1730   $proposed= recurse($stripped, $variables);
1732   /* Get list of used ID's */
1733   $used= array();
1734   $ldap= $config->get_ldap_link();
1735   $ldap->cd($config->current['BASE']);
1736   $ldap->search('(uid=*)');
1738   while($attrs= $ldap->fetch()){
1739     $used[]= $attrs['uid'][0];
1740   }
1742   /* Remove used uids and watch out for id tags */
1743   $ret= array();
1744   foreach($proposed as $uid){
1746     /* Check for id tag and modify uid if needed */
1747     if(preg_match('/\{id:\d+}/',$uid)){
1748       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1750       for ($i= 0; $i < pow(10,$size); $i++){
1751         $number= sprintf("%0".$size."d", $i);
1752         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1753         if (!in_array($res, $used)){
1754           $uid= $res;
1755           break;
1756         }
1757       }
1758     }
1760   if(preg_match('/\{id#\d+}/',$uid)){
1761     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1763     while (true){
1764       mt_srand((double) microtime()*1000000);
1765       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1766       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1767       if (!in_array($res, $used)){
1768         $uid= $res;
1769         break;
1770       }
1771     }
1772   }
1774 /* Don't assign used ones */
1775 if (!in_array($uid, $used)){
1776   $ret[]= $uid;
1780 return(array_unique($ret));
1784 function array_search_r($needle, $key, $haystack){
1786   foreach($haystack as $index => $value){
1787     $match= 0;
1789     if (is_array($value)){
1790       $match= array_search_r($needle, $key, $value);
1791     }
1793     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1794       $match=1;
1795     }
1797     if ($match){
1798       return 1;
1799     }
1800   }
1802   return 0;
1803
1806 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1807    Need to convert... */
1808 function to_byte($value) {
1809   $value= strtolower(trim($value));
1811   if(!is_numeric(substr($value, -1))) {
1813     switch(substr($value, -1)) {
1814       case 'g':
1815         $mult= 1073741824;
1816         break;
1817       case 'm':
1818         $mult= 1048576;
1819         break;
1820       case 'k':
1821         $mult= 1024;
1822         break;
1823     }
1825     return ($mult * (int)substr($value, 0, -1));
1826   } else {
1827     return $value;
1828   }
1832 function in_array_ics($value, $items)
1834   if (!is_array($items)){
1835     return (FALSE);
1836   }
1838   foreach ($items as $item){
1839     if (strtolower($item) == strtolower($value)) {
1840       return (TRUE);
1841     }
1842   }
1844   return (FALSE);
1845
1848 function generate_alphabet($count= 10)
1850   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1851   $alphabet= "";
1852   $c= 0;
1854   /* Fill cells with charaters */
1855   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1856     if ($c == 0){
1857       $alphabet.= "<tr>";
1858     }
1860     $ch = mb_substr($characters, $i, 1, "UTF8");
1861     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1862       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1864     if ($c++ == $count){
1865       $alphabet.= "</tr>";
1866       $c= 0;
1867     }
1868   }
1870   /* Fill remaining cells */
1871   while ($c++ <= $count){
1872     $alphabet.= "<td>&nbsp;</td>";
1873   }
1875   return ($alphabet);
1879 function validate($string)
1881   return (strip_tags(preg_replace('/\0/', '', $string)));
1884 function get_gosa_version()
1886   global $svn_revision, $svn_path;
1888   /* Extract informations */
1889   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1891   /* Release or development? */
1892   if (preg_match('%/gosa/trunk/%', $svn_path)){
1893     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1894   } else {
1895     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1896     return (_("GOsa $release"));
1897   }
1901 function rmdirRecursive($path, $followLinks=false) {
1902   $dir= opendir($path);
1903   while($entry= readdir($dir)) {
1904     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1905       unlink($path."/".$entry);
1906     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1907       rmdirRecursive($path."/".$entry);
1908     }
1909   }
1910   closedir($dir);
1911   return rmdir($path);
1914 function scan_directory($path,$sort_desc=false)
1916   $ret = false;
1918   /* is this a dir ? */
1919   if(is_dir($path)) {
1921     /* is this path a readable one */
1922     if(is_readable($path)){
1924       /* Get contents and write it into an array */   
1925       $ret = array();    
1927       $dir = opendir($path);
1929       /* Is this a correct result ?*/
1930       if($dir){
1931         while($fp = readdir($dir))
1932           $ret[]= $fp;
1933       }
1934     }
1935   }
1936   /* Sort array ascending , like scandir */
1937   sort($ret);
1939   /* Sort descending if parameter is sort_desc is set */
1940   if($sort_desc) {
1941     $ret = array_reverse($ret);
1942   }
1944   return($ret);
1947 function clean_smarty_compile_dir($directory)
1949   global $svn_revision;
1951   if(is_dir($directory) && is_readable($directory)) {
1952     // Set revision filename to REVISION
1953     $revision_file= $directory."/REVISION";
1955     /* Is there a stamp containing the current revision? */
1956     if(!file_exists($revision_file)) {
1957       // create revision file
1958       create_revision($revision_file, $svn_revision);
1959     } else {
1960 # check for "$config->...['CONFIG']/revision" and the
1961 # contents should match the revision number
1962       if(!compare_revision($revision_file, $svn_revision)){
1963         // If revision differs, clean compile directory
1964         foreach(scan_directory($directory) as $file) {
1965           if(($file==".")||($file=="..")) continue;
1966           if( is_file($directory."/".$file) &&
1967               is_writable($directory."/".$file)) {
1968             // delete file
1969             if(!unlink($directory."/".$file)) {
1970               print_red("File ".$directory."/".$file." could not be deleted.");
1971               // This should never be reached
1972             }
1973           } elseif(is_dir($directory."/".$file) &&
1974               is_writable($directory."/".$file)) {
1975             // Just recursively delete it
1976             rmdirRecursive($directory."/".$file);
1977           }
1978         }
1979         // We should now create a fresh revision file
1980         clean_smarty_compile_dir($directory);
1981       } else {
1982         // Revision matches, nothing to do
1983       }
1984     }
1985   } else {
1986     // Smarty compile dir is not accessible
1987     // (Smarty will warn about this)
1988   }
1991 function create_revision($revision_file, $revision)
1993   $result= false;
1995   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1996     if($fh= fopen($revision_file, "w")) {
1997       if(fwrite($fh, $revision)) {
1998         $result= true;
1999       }
2000     }
2001     fclose($fh);
2002   } else {
2003     print_red("Can not write to revision file");
2004   }
2006   return $result;
2009 function compare_revision($revision_file, $revision)
2011   // false means revision differs
2012   $result= false;
2014   if(file_exists($revision_file) && is_readable($revision_file)) {
2015     // Open file
2016     if($fh= fopen($revision_file, "r")) {
2017       // Compare File contents with current revision
2018       if($revision == fread($fh, filesize($revision_file))) {
2019         $result= true;
2020       }
2021     } else {
2022       print_red("Can not open revision file");
2023     }
2024     // Close file
2025     fclose($fh);
2026   }
2028   return $result;
2031 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2033   $str = ""; // Our return value will be saved in this var
2035   $color  = dechex($percentage+150);
2036   $color2 = dechex(150 - $percentage);
2037   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2039   $progress = (int)(($percentage /100)*$width);
2041   /* Abort printing out percentage, if divs are to small */
2044   /* If theres a better solution for this, use it... */
2045   $str = "
2046     <div style=\" width:".($width)."px; 
2047     height:".($height)."px;
2048   background-color:#000000;
2049 padding:1px;\">
2051           <div style=\" width:".($width)."px;
2052         background-color:#$bgcolor;
2053 height:".($height)."px;\">
2055          <div style=\" width:".$progress."px;
2056 height:".$height."px;
2057        background-color:#".$color2.$color2.$color."; \">";
2060        if(($height >10)&&($showvalue)){
2061          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2062            <b>".$percentage."%</b>
2063            </font>";
2064        }
2066        $str.= "</div></div></div>";
2068        return($str);
2072 function array_key_ics($ikey, $items)
2074   /* Gather keys, make them lowercase */
2075   $tmp= array();
2076   foreach ($items as $key => $value){
2077     $tmp[strtolower($key)]= $key;
2078   }
2080   if (isset($tmp[strtolower($ikey)])){
2081     return($tmp[strtolower($ikey)]);
2082   }
2084   return ("");
2088 function search_config($arr, $name, $return)
2090   if (is_array($arr)){
2091     foreach ($arr as $a){
2092       if (isset($a['CLASS']) &&
2093           strtolower($a['CLASS']) == strtolower($name)){
2095         if (isset($a[$return])){
2096           return ($a[$return]);
2097         } else {
2098           return ("");
2099         }
2100       } else {
2101         $res= search_config ($a, $name, $return);
2102         if ($res != ""){
2103           return $res;
2104         }
2105       }
2106     }
2107   }
2108   return ("");
2112 function array_differs($src, $dst)
2114   /* If the count is differing, the arrays differ */
2115   if (count ($src) != count ($dst)){
2116     return (TRUE);
2117   }
2119   /* So the count is the same - lets check the contents */
2120   $differs= FALSE;
2121   foreach($src as $value){
2122     if (!in_array($value, $dst)){
2123       $differs= TRUE;
2124     }
2125   }
2127   return ($differs);
2131 function saveFilter($a_filter, $values)
2133   if (isset($_POST['regexit'])){
2134     $a_filter["regex"]= $_POST['regexit'];
2136     foreach($values as $type){
2137       if (isset($_POST[$type])) {
2138         $a_filter[$type]= "checked";
2139       } else {
2140         $a_filter[$type]= "";
2141       }
2142     }
2143   }
2145   /* React on alphabet links if needed */
2146   if (isset($_GET['search'])){
2147     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2148     if ($s == "**"){
2149       $s= "*";
2150     }
2151     $a_filter['regex']= $s;
2152   }
2154   return ($a_filter);
2158 /* Escape all preg_* relevant characters */
2159 function normalizePreg($input)
2161   return (addcslashes($input, '[]()|/.*+-'));
2165 /* Escape all LDAP filter relevant characters */
2166 function normalizeLdap($input)
2168   return (addcslashes($input, '()|'));
2172 /* Resturns the difference between to microtime() results in float  */
2173 function get_MicroTimeDiff($start , $stop)
2175   $a = split("\ ",$start);
2176   $b = split("\ ",$stop);
2178   $secs = $b[1] - $a[1];
2179   $msecs= $b[0] - $a[0]; 
2181   $ret = (float) ($secs+ $msecs);
2182   return($ret);
2186 /* Check if the given department name is valid */
2187 function is_department_name_reserved($name,$base)
2189   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2190                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2191                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2192   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2194   /* Check if name is one of the reserved names */
2195   if(in_array_ics($name,$reservedName)) {
2196     return(true);
2197   }
2199   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2200   foreach($follwedNames as $key => $names){
2201     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2202       return(true);
2203     }
2204   }
2205   return(false);
2209 function is_php4()
2211   if (isset($_SESSION['PHP4COMPATIBLE'])){
2212     return true;
2213   }
2214   return (preg_match('/^4/', phpversion()));
2218 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2220   /* Initialize variables */
2221   $ret  = array("count" => 0);  // Set count to 0
2222   $next = true;                 // if false, then skip next loops and return
2223   $cnt  = 0;                    // Current number of loops
2224   $max  = 100;                  // Just for security, prevent looops
2225   $ldap = NULL;                 // To check if created result a valid
2226   $keep = "";                   // save last failed parse string
2228   /* Check each parsed dn in ldap ? */
2229   if($config!=NULL && $verify_in_ldap){
2230     $ldap = $config->get_ldap_link();
2231   }
2233   /* Lets start */
2234   $called = false;
2235   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2237     $cnt ++;
2238     if(!preg_match("/,/",$dn)){
2239       $next = false;
2240     }
2241     $object = preg_replace("/[,].*$/","",$dn);
2242     $dn     = preg_replace("/^[^,]+,/","",$dn);
2244     $called = true;
2246     /* Check if current dn is valid */
2247     if($ldap!=NULL){
2248       $ldap->cd($dn);
2249       $ldap->cat($dn,array("dn"));
2250       if($ldap->count()){
2251         $ret[]  = $keep.$object;
2252         $keep   = "";
2253       }else{
2254         $keep  .= $object.",";
2255       }
2256     }else{
2257       $ret[]  = $keep.$object;
2258       $keep   = "";
2259     }
2260   }
2262   /* No dn was posted */
2263   if($cnt == 0 && !empty($dn)){
2264     $ret[] = $dn;
2265   }
2267   /* Append the rest */
2268   $test = $keep.$dn;
2269   if($called && !empty($test)){
2270     $ret[] = $keep.$dn;
2271   }
2272   $ret['count'] = count($ret) - 1;
2274   return($ret);
2278 function get_base_from_hook($dn, $attrib)
2280   global $config;
2282   if (isset($config->current['BASE_HOOK'])){
2283     
2284     /* Call hook script - if present */
2285     $command= $config->current['BASE_HOOK'];
2287     if ($command != ""){
2288       $command.= " '$dn' $attrib";
2289       if (check_command($command)){
2290         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2291         exec($command, $output);
2292         if (preg_match("/^[0-9]+$/", $output[0])){
2293           return ($output[0]);
2294         } else {
2295           print_red(_("Warning - base_hook is not available. Using default base."));
2296           return ($config->current['UIDBASE']);
2297         }
2298       } else {
2299         print_red(_("Warning - base_hook is not available. Using default base."));
2300         return ($config->current['UIDBASE']);
2301       }
2303     } else {
2305       print_red(_("Warning - no base_hook defined. Using default base."));
2306       return ($config->current['UIDBASE']);
2308     }
2309   }
2312 /* Schema validation functions */
2314   function check_schema_version($class, $version)
2315   {
2316     return preg_match("/\(v$version\)/", $class['DESC']);
2317   }
2319   
2321   function check_schema($cfg,$rfc2307bis = FALSE)
2322   {
2324     $messages= array();
2326     /* Get objectclasses */
2327     $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2328     $objectclasses = $ldap->get_objectclasses();
2329     if(count($objectclasses) == 0){
2330       print_red(_("Can't get schema information from server. No schema check possible!"));
2331     }
2333     /* This is the default block used for each entry.
2334      *  to avoid unset indexes.
2335      */
2336     $def_check = array("REQUIRED_VERSION" => "0",
2337                        "SCHEMA_FILES"     => array(),
2338                        "CLASSES_REQUIRED" => array(),
2339                        "STATUS"           => FALSE,
2340                        "IS_MUST_HAVE"     => FALSE,
2341                        "MSG"              => "",
2342                        "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2344  /* The gosa base schema */
2345     $checks['gosaObject'] = $def_check;
2346     $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2347     $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2348     $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2349     $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2351     /* GOsa Account class */
2352     $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2353     $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2354     $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2355     $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2356     $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2358     /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2359     $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2360     $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2361     $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2362     $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2363     $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2365   /* Some other checks */
2366     foreach(array(
2367           "gosaCacheEntry"        => array("version" => "2.4"),
2368           "gosaDepartment"        => array("version" => "2.4"),
2369           "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2370           "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2371           "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2372           "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2373           "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2374           "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2375           "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2376           "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2377           "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2378           "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2379           "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2380           "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2381           "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2382           "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2383           "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2384           "goLdapServer"          => array("version" => "2.4"),
2385           "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2386           "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2387           "goKrbServer"           => array("version" => "2.4"),
2388           "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2389           ) as $name => $values){
2391       $checks[$name] = $def_check;
2392       if(isset($values['version'])){
2393         $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2394       }
2395       if(isset($values['file'])){
2396         $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2397       }
2398       $checks[$name]["CLASSES_REQUIRED"] = array($name);
2399     }
2400    foreach($checks as $name => $value){
2401       foreach($value['CLASSES_REQUIRED'] as $class){
2403         if(!isset($objectclasses[$name])){
2404           $checks[$name]['STATUS'] = FALSE;
2405           if($value['IS_MUST_HAVE']){
2406             $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2407           }else{
2408             $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2409           }
2410         }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2411           $checks[$name]['STATUS'] = FALSE;
2413           if($value['IS_MUST_HAVE']){
2414             $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2415           }else{
2416             $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2417           }
2418         }else{
2419           $checks[$name]['STATUS'] = TRUE;
2420           $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2421         }
2422       }
2423     }
2425     $tmp = $objectclasses;
2428     /* The gosa base schema */
2429     $checks['posixGroup'] = $def_check;
2430     $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2431     $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2432     $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2433     $checks['posixGroup']['STATUS']           = TRUE;
2434     $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2435     $checks['posixGroup']['MSG']              = "";
2436     $checks['posixGroup']['INFO']             = "";
2438     /* Depending on selected rfc2307bis mode, we need different schema configurations */
2439     if(isset($tmp['posixGroup'])){
2441       if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2442         $checks['posixGroup']['STATUS']           = FALSE;
2443         $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2444         $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2445       }
2446       if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2447         $checks['posixGroup']['STATUS']           = FALSE;
2448         $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2449         $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2450       }
2451     }
2453     return($checks);
2454   }
2457 function prepare4mailbody($string)
2459   $string = html_entity_decode($string);
2461   $from = array(
2462                 "/%/",
2463                 "/ /",
2464                 "/\n/",  
2465                 "/\r/",
2466                 "/!/",
2467                 "/#/",
2468                 "/\*/",
2469                 "/\//",
2470                 "/</",
2471                 "/>/",
2472                 "/\?/",
2473                 "/\&/",
2474                 "/\(/",
2475                 "/\)/",
2476                 "/\"/");
2477   
2478   $to = array(  
2479                 "%25",
2480                 "%20",
2481                 "%0A",
2482                 "%0D",
2483                 "%21",
2484                 "%23",
2485                 "%2A",
2486                 "%2F",
2487                 "%3C",
2488                 "%3E",
2489                 "%3F",
2490                 "%38",
2491                 "%28",
2492                 "%29",
2493                 "%22");
2495   $string = preg_replace($from,$to,$string);
2497   return($string);
2501 function mac2company($mac)
2503   $vendor= "";
2505   /* Generate a normailzed mac... */
2506   $mac= substr(preg_replace('/[:-]/', '', $mac), 0, 6);
2508   /* Check for existance of the oui file */
2509   if (!is_readable(CONFIG_DIR."/oui.txt")){
2510     return ("");
2511   }
2513   /* Open file and look for mac addresses... */
2514   $handle = @fopen(CONFIG_DIR."/oui.txt", "r");
2515   if ($handle) {
2516     while (!feof($handle)) {
2517       $line = fgets($handle, 4096);
2519       if (preg_match("/^$mac/i", $line)){
2520         $vendor= substr($line, 32);
2521       }
2522     }
2523     fclose($handle);
2524   }
2526   return ($vendor);
2530 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2532   $tmp = array(
2533         "de_DE" => "German",
2534         "fr_FR" => "French",
2535         "it_IT" => "Italian",
2536         "es_ES" => "Spanish",
2537         "en_US" => "English",
2538         "nl_NL" => "Dutch",
2539         "pl_PL" => "Polish",
2540         "sv_SE" => "Swedish",
2541         "zh_CN" => "Chinese",
2542         "ru_RU" => "Russian");
2544   $ret = array();
2545   if($languages_in_own_language){
2546     $old_lang = setlocale(LC_ALL, 0);
2547     foreach($tmp as $key => $name){
2548       $lang = $key.".UTF-8";
2549       setlocale(LC_ALL, $lang);
2550       if($strip_region_tag){
2551         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$name.")";
2552       }else{
2553         $ret[$key] = _($name)." &nbsp;(".$name.")";
2554       }
2555     }
2556     setlocale(LC_ALL, $old_lang);
2557   }else{
2558     foreach($tmp as $key => $name){
2559       if($strip_region_tag){
2560         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2561       }else{
2562         $ret[$key] = _($name);
2563       }
2564     }
2565   }
2566   return($ret);
2570 /* Check if $ip1 and $ip2 represents a valid IP range 
2571  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2572  */
2573 function is_ip_range($ip1,$ip2)
2575   if(!is_ip($ip1) || !is_ip($ip2)){
2576     return(FALSE);
2577   }else{
2578     $ar1 = split("\.",$ip1);
2579     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2581     $ar2 = split("\.",$ip2);
2582     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2583     return($var1 < $var2);
2584   }
2587 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2588 ?>