Code

Made auth_mail a boolean value.
[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   }
315   /* Check if mail address is also a valid auth name */
316   $auth_mail = FALSE;
317   if(isset($config->current['AUTH_MAIL']) && preg_match("/true/",$config->current['AUTH_MAIL'])){
318     $auth_mail = TRUE;
319   }
321   $ldap->cd($config->current['BASE']);
322   if(!$auth_mail){
323     $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
324   }else{
325     $ldap->search("(&(|(uid=".$username.")(mail=".$username."))(objectClass=gosaAccount))", array("uid","mail"));
326   }
328   /* get results, only a count of 1 is valid */
329   switch ($ldap->count()){
331     /* user not found */
332     case 0:     return (NULL);
334             /* valid uniq user */
335     case 1: 
336             break;
338             /* found more than one matching id */
339     default:
340             print_red(_("Username / UID is not unique. Please check your LDAP database."));
341             return (NULL);
342   }
344   /* LDAP schema is not case sensitive. Perform additional check. */
345   $attrs= $ldap->fetch();
346   if($auth_mail){
347     if ($attrs['uid'][0] != $username && $attrs['mail'][0] != $username){
348       return(NULL);
349     }
350   }else{
351     if ($attrs['uid'][0] != $username){
352       return(NULL);
353     }
354   }
356   /* got user dn, fill acl's */
357   $ui= new userinfo($config, $ldap->getDN());
358   $ui->username= $attrs['uid'][0];
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, $checkTag= TRUE){
776   global $ui, $config;
778   /* Check for strict tagging */
779   $ttag= "";
780   if ($checkTag && isset($config->current['STRICT_UNITS']) &&
781       preg_match('/^(yes|true)$/i', $config->current['STRICT_UNITS']) &&
782       $ui->gosaUnitTag != ""){
783     $size= 0;
784     foreach ($config->tdepartments as $tdn => $tag){
785       if (preg_match("/$tdn$/", $dn)){
786         if (strlen($tdn) > $size){
787           $size= strlen($tdn);
788           $ttag= $tag;
789         }
790       }
791     }
793     /* We have no permission for areas that don't carry our tag */
794     if ($ttag != $ui->gosaUnitTag){
795       return ("#none#");
796     }
797   }
799   $final= "";
800   foreach($acl_array as $acl){
802     /* Check for selfflag (!) in ACL to determine if
803        the user is allowed to change parts of his/her
804        own account */
805     if (preg_match("/^!/", $acl)){
806       if ($dn != "" && $dn != $ui->dn){
808         /* No match for own DN, give up on this ACL */
809         continue;
811       } else {
813         /* Matches own DN, remove the selfflag */
814         $acl= preg_replace("/^!/", "", $acl);
816       }
817     }
819     /* Remove leading garbage */
820     $acl= preg_replace("/^:/", "", $acl);
822     /* Discover if we've access to the submodule by comparing
823        all allowed submodules specified in the ACL */
824     $tmp= split(",", $acl);
825     foreach ($tmp as $mod){
826       if (preg_match("/^$module#/", $mod)){
827         $final= strstr($mod, "#")."#";
828         continue;
829       }
830       if (preg_match("/[^#]$module$/", $mod)){
831         return ("#all#");
832       }
833       if (preg_match("/^all$/", $mod)){
834         return ("#all#");
835       }
836     }
837   }
839   /* Return assembled ACL, or none */
840   if ($final != ""){
841     return (preg_replace('/##/', '#', $final));
842   }
844   /* Nothing matches - disable access for this object */
845   return ("#none#");
849 function get_userinfo()
851   global $ui;
853   return $ui;
857 function get_smarty()
859   global $smarty;
861   return $smarty;
865 function convert_department_dn($dn)
867   $dep= "";
869   /* Build a sub-directory style list of the tree level
870      specified in $dn */
871   foreach (split(',', $dn) as $rdn){
873     /* We're only interested in organizational units... */
874     if (substr($rdn,0,3) == 'ou='){
875       $dep= substr($rdn,3)."/$dep";
876     }
878     /* ... and location objects */
879     if (substr($rdn,0,2) == 'l='){
880       $dep= substr($rdn,2)."/$dep";
881     }
882   }
884   /* Return and remove accidently trailing slashes */
885   return rtrim($dep, "/");
889 /* Strip off the last sub department part of a '/level1/level2/.../'
890  * style value. It removes the trailing '/', too. */
891 function get_sub_department($value)
893   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
897 function get_ou($name)
899   global $config;
901   /* Preset ou... */
902   if (isset($config->current[$name])){
903     $ou= $config->current[$name];
904   } else {
905     return "";
906   }
907   
908   if ($ou != ""){
909     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
910       return @LDAP::convert("ou=$ou,");
911     } else {
912       return @LDAP::convert("$ou,");
913     }
914   } else {
915     return "";
916   }
920 function get_people_ou()
922   return (get_ou("PEOPLE"));
926 function get_groups_ou()
928   return (get_ou("GROUPS"));
932 function get_winstations_ou()
934   return (get_ou("WINSTATIONS"));
938 function get_base_from_people($dn)
940   global $config;
942   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
943   $base= preg_replace($pattern, '', $dn);
945   /* Set to base, if we're not on a correct subtree */
946   if (!isset($config->idepartments[$base])){
947     $base= $config->current['BASE'];
948   }
950   return ($base);
954 function chkacl($acl, $name)
956   /* Look for attribute in ACL */
957   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
958     return ("");
959   }
961   /* Optically disable html object for no match */
962   return (" disabled ");
966 function is_phone_nr($nr)
968   if ($nr == ""){
969     return (TRUE);
970   }
972   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
975 function is_dns_name($str)
977   return(preg_match("/^[a-z0-9\.\-]*$/i",$str));
980 function is_url($url)
982   if ($url == ""){
983     return (TRUE);
984   }
986   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
990 function is_dn($dn)
992   if ($dn == ""){
993     return (TRUE);
994   }
996   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
1000 function is_uid($uid)
1002   global $config;
1004   if ($uid == ""){
1005     return (TRUE);
1006   }
1008   /* STRICT adds spaces and case insenstivity to the uid check.
1009      This is dangerous and should not be used. */
1010   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
1011     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
1012   } else {
1013     return preg_match ("/^[a-z0-9_-]+$/", $uid);
1014   }
1018 function is_ip($ip)
1020   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);
1024 function is_mac($mac)
1026   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);
1030 /* Checks if the given ip address doesn't match
1031     "is_ip" because there is also a sub net mask given */
1032 function is_ip_with_subnetmask($ip)
1034         /* Generate list of valid submasks */
1035         $res = array();
1036         for($e = 0 ; $e <= 32; $e++){
1037                 $res[$e] = $e;
1038         }
1039         $i[0] =255;
1040         $i[1] =255;
1041         $i[2] =255;
1042         $i[3] =255;
1043         for($a= 3 ; $a >= 0 ; $a --){
1044                 $c = 1;
1045                 while($i[$a] > 0 ){
1046                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
1047                         $res[$str] = $str;
1048                         $i[$a] -=$c;
1049                         $c = 2*$c;
1050                 }
1051         }
1052         $res["0.0.0.0"] = "0.0.0.0";
1053         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1054                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1055                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1056                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
1057                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1058                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1059                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1060                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1062                 $mask = preg_replace("/^\//","",$mask);
1063                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1064                         return(TRUE);
1065                 }
1066         }
1067         return(FALSE);
1070 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1071 function is_domain($str)
1073   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1077 function is_id($id)
1079   if ($id == ""){
1080     return (FALSE);
1081   }
1083   return preg_match ("/^[0-9]+$/", $id);
1087 function is_path($path)
1089   if ($path == ""){
1090     return (TRUE);
1091   }
1092   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1093     return (FALSE);
1094   }
1096   return preg_match ("/\/.+$/", $path);
1100 function is_email($address, $template= FALSE)
1102   if ($address == ""){
1103     return (TRUE);
1104   }
1105   if ($template){
1106     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1107         $address);
1108   } else {
1109     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1110         $address);
1111   }
1115 function print_red()
1117   /* Check number of arguments */
1118   if (func_num_args() < 1){
1119     return;
1120   }
1122   /* Get arguments, save string */
1123   $array = func_get_args();
1124   $string= $array[0];
1126   /* Step through arguments */
1127   for ($i= 1; $i<count($array); $i++){
1128     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1129   }
1131   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1132     $_SESSION['errorsAlreadyPosted'] = array(); 
1133   }
1135   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1136      the other case... */
1138   if (isset($_SESSION['DEBUGLEVEL'])){
1140     if($_SESSION['LastError'] == $string){
1141     
1142       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1143         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1144       }
1145       $_SESSION['errorsAlreadyPosted'][$string]++;
1147     }else{
1148       if($string != NULL){
1149         if (preg_match("/"._("LDAP error:")."/", $string)){
1150           $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.");
1151           $img= "images/error.png";
1152         } else {
1153           if (!preg_match('/[.!?]$/', $string)){
1154             $string.= ".";
1155           }
1156           $string= preg_replace('/<br>/', ' ', $string);
1157           $img= "images/warning.png";
1158           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1159         }
1160       
1161         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1164   if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1166             $_SESSION['errors'].= "
1167               <iframe id='e_layer3'
1168                 style=\"  position:absolute;
1169                           width:100%;
1170                           height:100%;
1171                           top:0px;
1172                           left:0px;
1173                           border:none;
1174                           display:block;
1175                           allowtransparency='true';
1176                           background-color: #FFFFFF;
1177                           filter:chroma(color=#FFFFFF);
1178                           z-index:0; \">
1179               </iframe>
1180               <div  id='e_layer2'
1181                 style=\"
1182                   position: absolute;
1183                   left: 0px;
1184                   top: 0px;
1185                   right:0px;
1186                   bottom:0px;
1187                   z-index:0;
1188                   width:100%;
1189                   height:100%;
1190                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1191               </div>";
1192               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1193           }else{
1195             $_SESSION['errors'].= "
1196               <div  id='e_layer2'
1197                 style=\"
1198                   position: absolute;
1199                   left: 0px;
1200                   top: 0px;
1201                   right:0px;
1202                   bottom:0px;
1203                   z-index:0;
1204                   background-image: url(images/opacity_black.png);\">
1205                </div>";
1206               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1207           }
1209           $_SESSION['errors'].= "
1210           <div style='left:20%;right:20%;top:30%;".
1211             "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1212             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1213             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1214             get_template_path($img)."'></td>".
1215             "<td style='width:100%'><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1216             (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1217             " style='width:80px' onClick='".$hide."'>".
1218             _("OK")."</button></td></tr></table></div>";
1219         }
1221       }else{
1222         return;
1223       }
1224       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1226     }
1228   } else {
1229     echo "Error: $string\n";
1230   }
1231   $_SESSION['LastError'] = $string; 
1235 function gen_locked_message($user, $dn)
1237   global $plug, $config;
1239   $_SESSION['dn']= $dn;
1240   $ldap= $config->get_ldap_link();
1241   $ldap->cat ($user, array('uid', 'cn'));
1242   $attrs= $ldap->fetch();
1244   /* Stop if we have no user here... */
1245   if (count($attrs)){
1246     $uid= $attrs["uid"][0];
1247     $cn= $attrs["cn"][0];
1248   } else {
1249     $uid= $attrs["uid"][0];
1250     $cn= $attrs["cn"][0];
1251   }
1252   
1253   $remove= false;
1255   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1256     $_SESSION['LOCK_VARS_USED']  =array();
1257     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1259       if(empty($name)) continue;
1260       foreach($_POST as $Pname => $Pvalue){
1261         if(preg_match($name,$Pname)){
1262           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1263         }
1264       }
1266       foreach($_GET as $Pname => $Pvalue){
1267         if(preg_match($name,$Pname)){
1268           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1269         }
1270       }
1271     }
1272     $_SESSION['LOCK_VARS_TO_USE'] =array();
1273   }
1275   /* Prepare and show template */
1276   $smarty= get_smarty();
1277   $smarty->assign ("dn", $dn);
1278   if ($remove){
1279     $smarty->assign ("action", _("Continue anyway"));
1280   } else {
1281     $smarty->assign ("action", _("Edit anyway"));
1282   }
1283   $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>"));
1285   return ($smarty->fetch (get_template_path('islocked.tpl')));
1289 function to_string ($value)
1291   /* If this is an array, generate a text blob */
1292   if (is_array($value)){
1293     $ret= "";
1294     foreach ($value as $line){
1295       $ret.= $line."<br>\n";
1296     }
1297     return ($ret);
1298   } else {
1299     return ($value);
1300   }
1304 function get_printer_list($cups_server)
1306   global $config;
1308   $res= array();
1310   /* Use CUPS, if we've access to it */
1311   if (function_exists('cups_get_dest_list')){
1312     $dest_list= cups_get_dest_list ($cups_server);
1314     foreach ($dest_list as $prt){
1315       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1317       foreach ($attr as $prt_info){
1318         if ($prt_info->name == "printer-info"){
1319           $info= $prt_info->value;
1320           break;
1321         }
1322       }
1323       $res[$prt->name]= "$info [$prt->name]";
1324     }
1326     /* CUPS is not available, try lpstat as a replacement */
1327   } else {
1328     $ar = false;
1329     exec("lpstat -p", $ar);
1330     foreach($ar as $val){
1331       @list($dummy, $printer, $rest)= split(' ', $val, 3);
1332       if (preg_match('/^[^@]+$/', $printer)){
1333         $res[$printer]= "$printer";
1334       }
1335     }
1336   }
1338   /* Merge in printers from LDAP */
1339   $ldap= $config->get_ldap_link();
1340   $ldap->cd ($config->current['BASE']);
1341   $ui= get_userinfo();
1342   if (isset($config->current['STRICT_UNITS']) && preg_match('/TRUE/i', $config->current['STRICT_UNITS']) && $ui->gosaUnitTag != ""){   
1343     $ldap->search('((objectClass=gotoPrinter)(gosaUnitTag='.$ui->gosaUnitTag.'))', array('cn'));
1344   } else {
1345     $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1346   }
1347   while($attrs = $ldap->fetch()){
1348     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1349   }
1351   return $res;
1355 function sess_del ($var)
1357   /* New style */
1358   unset ($_SESSION[$var]);
1360   /* ... work around, since the first one
1361      doesn't seem to work all the time */
1362   session_unregister ($var);
1366 function show_errors($message)
1368   $complete= "";
1370   /* Assemble the message array to a plain string */
1371   foreach ($message as $error){
1372     if ($complete == ""){
1373       $complete= $error;
1374     } else {
1375       $complete= "$error<br>$complete";
1376     }
1377   }
1379   /* Fill ERROR variable with nice error dialog */
1380   print_red($complete);
1384 function show_ldap_error($message, $addon= "")
1386   if (!preg_match("/Success/i", $message)){
1387     if ($addon == ""){
1388       print_red (_("LDAP error: $message"));
1389     } else {
1390       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1391     }
1392     return TRUE;
1393   } else {
1394     return FALSE;
1395   }
1399 function rewrite($s)
1401   global $REWRITE;
1403   foreach ($REWRITE as $key => $val){
1404     $s= preg_replace("/$key/", "$val", $s);
1405   }
1407   return ($s);
1411 function dn2base($dn)
1413   global $config;
1415   if (get_people_ou() != ""){
1416     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1417   }
1418   if (get_groups_ou() != ""){
1419     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1420   }
1421   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1423   return ($base);
1428 function check_command($cmdline)
1430   $cmd= preg_replace("/ .*$/", "", $cmdline);
1432   /* Check if command exists in filesystem */
1433   if (!file_exists($cmd)){
1434     return (FALSE);
1435   }
1437   /* Check if command is executable */
1438   if (!is_executable($cmd)){
1439     return (FALSE);
1440   }
1442   return (TRUE);
1446 function print_header($image, $headline, $info= "")
1448   $display= "<div class=\"plugtop\">\n";
1449   $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";
1450   $display.= "</div>\n";
1452   if ($info != ""){
1453     $display.= "<div class=\"pluginfo\">\n";
1454     $display.= "$info";
1455     $display.= "</div>\n";
1456   } else {
1457     $display.= "<div style=\"height:5px;\">\n";
1458     $display.= "&nbsp;";
1459     $display.= "</div>\n";
1460   }
1461 #  if (isset($_SESSION['errors'])){
1462 #    $display.= $_SESSION['errors'];
1463 #  }
1465   return ($display);
1469 function register_global($name, $object)
1471   $_SESSION[$name]= $object;
1475 function is_global($name)
1477   return isset($_SESSION[$name]);
1481 function get_global($name)
1483   return $_SESSION[$name];
1487 function range_selector($dcnt,$start,$range=25,$post_var=false)
1490   /* Entries shown left and right from the selected entry */
1491   $max_entries= 10;
1493   /* Initialize and take care that max_entries is even */
1494   $output="";
1495   if ($max_entries & 1){
1496     $max_entries++;
1497   }
1499   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1500     $range= $_POST[$post_var];
1501   }
1503   /* Prevent output to start or end out of range */
1504   if ($start < 0 ){
1505     $start= 0 ;
1506   }
1507   if ($start >= $dcnt){
1508     $start= $range * (int)(($dcnt / $range) + 0.5);
1509   }
1511   $numpages= (($dcnt / $range));
1512   if(((int)($numpages))!=($numpages)){
1513     $numpages = (int)$numpages + 1;
1514   }
1515   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1516     return ("");
1517   }
1518   $ppage= (int)(($start / $range) + 0.5);
1521   /* Align selected page to +/- max_entries/2 */
1522   $begin= $ppage - $max_entries/2;
1523   $end= $ppage + $max_entries/2;
1525   /* Adjust begin/end, so that the selected value is somewhere in
1526      the middle and the size is max_entries if possible */
1527   if ($begin < 0){
1528     $end-= $begin + 1;
1529     $begin= 0;
1530   }
1531   if ($end > $numpages) {
1532     $end= $numpages;
1533   }
1534   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1535     $begin= $end - $max_entries;
1536   }
1538   if($post_var){
1539     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1540       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1541   }else{
1542     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1543   }
1545   /* Draw decrement */
1546   if ($start > 0 ) {
1547     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1548       (($start-$range))."\">".
1549       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1550   }
1552   /* Draw pages */
1553   for ($i= $begin; $i < $end; $i++) {
1554     if ($ppage == $i){
1555       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1556         validate($_GET['plug'])."&amp;start=".
1557         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1558     } else {
1559       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1560         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1561     }
1562   }
1564   /* Draw increment */
1565   if($start < ($dcnt-$range)) {
1566     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1567       (($start+($range)))."\">".
1568       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1569   }
1571   if(($post_var)&&($numpages)){
1572     $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()'>";
1573     foreach(array(20,50,100,200,"all") as $num){
1574       if($num == "all"){
1575         $var = 10000;
1576       }else{
1577         $var = $num;
1578       }
1579       if($var == $range){
1580         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1581       }else{  
1582         $output.="\n<option value='".$var."'>".$num."</option>";
1583       }
1584     }
1585     $output.=  "</select></td></tr></table></div>";
1586   }else{
1587     $output.= "</div>";
1588   }
1590   return($output);
1594 function apply_filter()
1596   $apply= "";
1598   $apply= ''.
1599     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1600     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1602   return ($apply);
1606 function back_to_main()
1608   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1609     _("Back").'"></p><input type="hidden" name="ignore">';
1611   return ($string);
1615 function normalize_netmask($netmask)
1617   /* Check for notation of netmask */
1618   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1619     $num= (int)($netmask);
1620     $netmask= "";
1622     for ($byte= 0; $byte<4; $byte++){
1623       $result=0;
1625       for ($i= 7; $i>=0; $i--){
1626         if ($num-- > 0){
1627           $result+= pow(2,$i);
1628         }
1629       }
1631       $netmask.= $result.".";
1632     }
1634     return (preg_replace('/\.$/', '', $netmask));
1635   }
1637   return ($netmask);
1641 function netmask_to_bits($netmask)
1643   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1644   $res= 0;
1646   for ($n= 0; $n<4; $n++){
1647     $start= 255;
1648     $name= "nm$n";
1650     for ($i= 0; $i<8; $i++){
1651       if ($start == (int)($$name)){
1652         $res+= 8 - $i;
1653         break;
1654       }
1655       $start-= pow(2,$i);
1656     }
1657   }
1659   return ($res);
1663 function recurse($rule, $variables)
1665   $result= array();
1667   if (!count($variables)){
1668     return array($rule);
1669   }
1671   reset($variables);
1672   $key= key($variables);
1673   $val= current($variables);
1674   unset ($variables[$key]);
1676   foreach($val as $possibility){
1677     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1678     $result= array_merge($result, recurse($nrule, $variables));
1679   }
1681   return ($result);
1685 function expand_id($rule, $attributes)
1687   /* Check for id rule */
1688   if(preg_match('/^id(:|#)\d+$/',$rule)){
1689     return (array("\{$rule}"));
1690   }
1692   /* Check for clean attribute */
1693   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1694     $rule= preg_replace('/^%/', '', $rule);
1695     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1696     return (array($val));
1697   }
1699   /* Check for attribute with parameters */
1700   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1701     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1702     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1703     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1704     $start= preg_replace ('/-.*$/', '', $param);
1705     $stop = preg_replace ('/^[^-]+-/', '', $param);
1707     /* Assemble results */
1708     $result= array();
1709     for ($i= $start; $i<= $stop; $i++){
1710       $result[]= substr($val, 0, $i);
1711     }
1712     return ($result);
1713   }
1715   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1716   return (array($rule));
1720 function gen_uids($rule, $attributes)
1722   global $config;
1724   /* Search for keys and fill the variables array with all 
1725      possible values for that key. */
1726   $part= "";
1727   $trigger= false;
1728   $stripped= "";
1729   $variables= array();
1731   for ($pos= 0; $pos < strlen($rule); $pos++){
1733     if ($rule[$pos] == "{" ){
1734       $trigger= true;
1735       $part= "";
1736       continue;
1737     }
1739     if ($rule[$pos] == "}" ){
1740       $variables[$pos]= expand_id($part, $attributes);
1741       $stripped.= "{".$pos."}";
1742       $trigger= false;
1743       continue;
1744     }
1746     if ($trigger){
1747       $part.= $rule[$pos];
1748     } else {
1749       $stripped.= $rule[$pos];
1750     }
1751   }
1753   /* Recurse through all possible combinations */
1754   $proposed= recurse($stripped, $variables);
1756   /* Get list of used ID's */
1757   $used= array();
1758   $ldap= $config->get_ldap_link();
1759   $ldap->cd($config->current['BASE']);
1760   $ldap->search('(uid=*)');
1762   while($attrs= $ldap->fetch()){
1763     $used[]= $attrs['uid'][0];
1764   }
1766   /* Remove used uids and watch out for id tags */
1767   $ret= array();
1768   foreach($proposed as $uid){
1770     /* Check for id tag and modify uid if needed */
1771     if(preg_match('/\{id:\d+}/',$uid)){
1772       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1774       for ($i= 0; $i < pow(10,$size); $i++){
1775         $number= sprintf("%0".$size."d", $i);
1776         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1777         if (!in_array($res, $used)){
1778           $uid= $res;
1779           break;
1780         }
1781       }
1782     }
1784   if(preg_match('/\{id#\d+}/',$uid)){
1785     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1787     while (true){
1788       mt_srand((double) microtime()*1000000);
1789       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1790       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1791       if (!in_array($res, $used)){
1792         $uid= $res;
1793         break;
1794       }
1795     }
1796   }
1798 /* Don't assign used ones */
1799 if (!in_array($uid, $used)){
1800   $ret[]= $uid;
1804 return(array_unique($ret));
1808 function array_search_r($needle, $key, $haystack){
1810   foreach($haystack as $index => $value){
1811     $match= 0;
1813     if (is_array($value)){
1814       $match= array_search_r($needle, $key, $value);
1815     }
1817     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1818       $match=1;
1819     }
1821     if ($match){
1822       return 1;
1823     }
1824   }
1826   return 0;
1827
1830 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1831    Need to convert... */
1832 function to_byte($value) {
1833   $value= strtolower(trim($value));
1835   if(!is_numeric(substr($value, -1))) {
1837     switch(substr($value, -1)) {
1838       case 'g':
1839         $mult= 1073741824;
1840         break;
1841       case 'm':
1842         $mult= 1048576;
1843         break;
1844       case 'k':
1845         $mult= 1024;
1846         break;
1847     }
1849     return ($mult * (int)substr($value, 0, -1));
1850   } else {
1851     return $value;
1852   }
1856 function in_array_ics($value, $items)
1858   if (!is_array($items)){
1859     return (FALSE);
1860   }
1862   foreach ($items as $item){
1863     if (strtolower($item) == strtolower($value)) {
1864       return (TRUE);
1865     }
1866   }
1868   return (FALSE);
1869
1872 function generate_alphabet($count= 10)
1874   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1875   $alphabet= "";
1876   $c= 0;
1878   /* Fill cells with charaters */
1879   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1880     if ($c == 0){
1881       $alphabet.= "<tr>";
1882     }
1884     $ch = mb_substr($characters, $i, 1, "UTF8");
1885     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1886       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1888     if ($c++ == $count){
1889       $alphabet.= "</tr>";
1890       $c= 0;
1891     }
1892   }
1894   /* Fill remaining cells */
1895   while ($c++ <= $count){
1896     $alphabet.= "<td>&nbsp;</td>";
1897   }
1899   return ($alphabet);
1903 function validate($string)
1905   return (strip_tags(preg_replace('/\0/', '', $string)));
1908 function get_gosa_version()
1910   global $svn_revision, $svn_path;
1912   /* Extract informations */
1913   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1915   /* Release or development? */
1916   if (preg_match('%/gosa/trunk/%', $svn_path)){
1917     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1918   } else {
1919     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1920     return (_("GOsa $release"));
1921   }
1925 function rmdirRecursive($path, $followLinks=false) {
1926   $dir= opendir($path);
1927   while($entry= readdir($dir)) {
1928     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1929       unlink($path."/".$entry);
1930     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1931       rmdirRecursive($path."/".$entry);
1932     }
1933   }
1934   closedir($dir);
1935   return rmdir($path);
1938 function scan_directory($path,$sort_desc=false)
1940   $ret = false;
1942   /* is this a dir ? */
1943   if(is_dir($path)) {
1945     /* is this path a readable one */
1946     if(is_readable($path)){
1948       /* Get contents and write it into an array */   
1949       $ret = array();    
1951       $dir = opendir($path);
1953       /* Is this a correct result ?*/
1954       if($dir){
1955         while($fp = readdir($dir))
1956           $ret[]= $fp;
1957       }
1958     }
1959   }
1960   /* Sort array ascending , like scandir */
1961   sort($ret);
1963   /* Sort descending if parameter is sort_desc is set */
1964   if($sort_desc) {
1965     $ret = array_reverse($ret);
1966   }
1968   return($ret);
1971 function clean_smarty_compile_dir($directory)
1973   global $svn_revision;
1975   if(is_dir($directory) && is_readable($directory)) {
1976     // Set revision filename to REVISION
1977     $revision_file= $directory."/REVISION";
1979     /* Is there a stamp containing the current revision? */
1980     if(!file_exists($revision_file)) {
1981       // create revision file
1982       create_revision($revision_file, $svn_revision);
1983     } else {
1984 # check for "$config->...['CONFIG']/revision" and the
1985 # contents should match the revision number
1986       if(!compare_revision($revision_file, $svn_revision)){
1987         // If revision differs, clean compile directory
1988         foreach(scan_directory($directory) as $file) {
1989           if(($file==".")||($file=="..")) continue;
1990           if( is_file($directory."/".$file) &&
1991               is_writable($directory."/".$file)) {
1992             // delete file
1993             if(!unlink($directory."/".$file)) {
1994               print_red("File ".$directory."/".$file." could not be deleted.");
1995               // This should never be reached
1996             }
1997           } elseif(is_dir($directory."/".$file) &&
1998               is_writable($directory."/".$file)) {
1999             // Just recursively delete it
2000             rmdirRecursive($directory."/".$file);
2001           }
2002         }
2003         // We should now create a fresh revision file
2004         clean_smarty_compile_dir($directory);
2005       } else {
2006         // Revision matches, nothing to do
2007       }
2008     }
2009   } else {
2010     // Smarty compile dir is not accessible
2011     // (Smarty will warn about this)
2012   }
2015 function create_revision($revision_file, $revision)
2017   $result= false;
2019   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2020     if($fh= fopen($revision_file, "w")) {
2021       if(fwrite($fh, $revision)) {
2022         $result= true;
2023       }
2024     }
2025     fclose($fh);
2026   } else {
2027     print_red("Can not write to revision file");
2028   }
2030   return $result;
2033 function compare_revision($revision_file, $revision)
2035   // false means revision differs
2036   $result= false;
2038   if(file_exists($revision_file) && is_readable($revision_file)) {
2039     // Open file
2040     if($fh= fopen($revision_file, "r")) {
2041       // Compare File contents with current revision
2042       if($revision == fread($fh, filesize($revision_file))) {
2043         $result= true;
2044       }
2045     } else {
2046       print_red("Can not open revision file");
2047     }
2048     // Close file
2049     fclose($fh);
2050   }
2052   return $result;
2055 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2057   $str = ""; // Our return value will be saved in this var
2059   $color  = dechex($percentage+150);
2060   $color2 = dechex(150 - $percentage);
2061   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2063   $progress = (int)(($percentage /100)*$width);
2065   /* Abort printing out percentage, if divs are to small */
2068   /* If theres a better solution for this, use it... */
2069   $str = "
2070     <div style=\" width:".($width)."px; 
2071     height:".($height)."px;
2072   background-color:#000000;
2073 padding:1px;\">
2075           <div style=\" width:".($width)."px;
2076         background-color:#$bgcolor;
2077 height:".($height)."px;\">
2079          <div style=\" width:".$progress."px;
2080 height:".$height."px;
2081        background-color:#".$color2.$color2.$color."; \">";
2084        if(($height >10)&&($showvalue)){
2085          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2086            <b>".$percentage."%</b>
2087            </font>";
2088        }
2090        $str.= "</div></div></div>";
2092        return($str);
2096 function array_key_ics($ikey, $items)
2098   /* Gather keys, make them lowercase */
2099   $tmp= array();
2100   foreach ($items as $key => $value){
2101     $tmp[strtolower($key)]= $key;
2102   }
2104   if (isset($tmp[strtolower($ikey)])){
2105     return($tmp[strtolower($ikey)]);
2106   }
2108   return ("");
2112 function search_config($arr, $name, $return)
2114   if (is_array($arr)){
2115     foreach ($arr as $a){
2116       if (isset($a['CLASS']) &&
2117           strtolower($a['CLASS']) == strtolower($name)){
2119         if (isset($a[$return])){
2120           return ($a[$return]);
2121         } else {
2122           return ("");
2123         }
2124       } else {
2125         $res= search_config ($a, $name, $return);
2126         if ($res != ""){
2127           return $res;
2128         }
2129       }
2130     }
2131   }
2132   return ("");
2136 function array_differs($src, $dst)
2138   /* If the count is differing, the arrays differ */
2139   if (count ($src) != count ($dst)){
2140     return (TRUE);
2141   }
2143   /* So the count is the same - lets check the contents */
2144   $differs= FALSE;
2145   foreach($src as $value){
2146     if (!in_array($value, $dst)){
2147       $differs= TRUE;
2148     }
2149   }
2151   return ($differs);
2155 function saveFilter($a_filter, $values)
2157   if (isset($_POST['regexit'])){
2158     $a_filter["regex"]= $_POST['regexit'];
2160     foreach($values as $type){
2161       if (isset($_POST[$type])) {
2162         $a_filter[$type]= "checked";
2163       } else {
2164         $a_filter[$type]= "";
2165       }
2166     }
2167   }
2169   /* React on alphabet links if needed */
2170   if (isset($_GET['search'])){
2171     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2172     if ($s == "**"){
2173       $s= "*";
2174     }
2175     $a_filter['regex']= $s;
2176   }
2178   return ($a_filter);
2182 /* Escape all preg_* relevant characters */
2183 function normalizePreg($input)
2185   return (addcslashes($input, '[]()|/.*+-'));
2189 /* Escape all LDAP filter relevant characters */
2190 function normalizeLdap($input)
2192   return (addcslashes($input, '()|'));
2196 /* Resturns the difference between to microtime() results in float  */
2197 function get_MicroTimeDiff($start , $stop)
2199   $a = split("\ ",$start);
2200   $b = split("\ ",$stop);
2202   $secs = $b[1] - $a[1];
2203   $msecs= $b[0] - $a[0]; 
2205   $ret = (float) ($secs+ $msecs);
2206   return($ret);
2210 /* Check if the given department name is valid */
2211 function is_department_name_reserved($name,$base)
2213   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2214                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2215                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2216   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2218   /* Check if name is one of the reserved names */
2219   if(in_array_ics($name,$reservedName)) {
2220     return(true);
2221   }
2223   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2224   foreach($follwedNames as $key => $names){
2225     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2226       return(true);
2227     }
2228   }
2229   return(false);
2233 function is_php4()
2235   if (isset($_SESSION['PHP4COMPATIBLE'])){
2236     return true;
2237   }
2238   return (preg_match('/^4/', phpversion()));
2242 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2244   /* Initialize variables */
2245   $ret  = array("count" => 0);  // Set count to 0
2246   $next = true;                 // if false, then skip next loops and return
2247   $cnt  = 0;                    // Current number of loops
2248   $max  = 100;                  // Just for security, prevent looops
2249   $ldap = NULL;                 // To check if created result a valid
2250   $keep = "";                   // save last failed parse string
2252   /* Check each parsed dn in ldap ? */
2253   if($config!=NULL && $verify_in_ldap){
2254     $ldap = $config->get_ldap_link();
2255   }
2257   /* Lets start */
2258   $called = false;
2259   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2261     $cnt ++;
2262     if(!preg_match("/,/",$dn)){
2263       $next = false;
2264     }
2265     $object = preg_replace("/[,].*$/","",$dn);
2266     $dn     = preg_replace("/^[^,]+,/","",$dn);
2268     $called = true;
2270     /* Check if current dn is valid */
2271     if($ldap!=NULL){
2272       $ldap->cd($dn);
2273       $ldap->cat($dn,array("dn"));
2274       if($ldap->count()){
2275         $ret[]  = $keep.$object;
2276         $keep   = "";
2277       }else{
2278         $keep  .= $object.",";
2279       }
2280     }else{
2281       $ret[]  = $keep.$object;
2282       $keep   = "";
2283     }
2284   }
2286   /* No dn was posted */
2287   if($cnt == 0 && !empty($dn)){
2288     $ret[] = $dn;
2289   }
2291   /* Append the rest */
2292   $test = $keep.$dn;
2293   if($called && !empty($test)){
2294     $ret[] = $keep.$dn;
2295   }
2296   $ret['count'] = count($ret) - 1;
2298   return($ret);
2302 function get_base_from_hook($dn, $attrib)
2304   global $config;
2306   if (isset($config->current['BASE_HOOK'])){
2307     
2308     /* Call hook script - if present */
2309     $command= $config->current['BASE_HOOK'];
2311     if ($command != ""){
2312       $command.= " '$dn' $attrib";
2313       if (check_command($command)){
2314         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2315         exec($command, $output);
2316         if (preg_match("/^[0-9]+$/", $output[0])){
2317           return ($output[0]);
2318         } else {
2319           print_red(_("Warning - base_hook is not available. Using default base."));
2320           return ($config->current['UIDBASE']);
2321         }
2322       } else {
2323         print_red(_("Warning - base_hook is not available. Using default base."));
2324         return ($config->current['UIDBASE']);
2325       }
2327     } else {
2329       print_red(_("Warning - no base_hook defined. Using default base."));
2330       return ($config->current['UIDBASE']);
2332     }
2333   }
2336 /* Schema validation functions */
2338   function check_schema_version($class, $version)
2339   {
2340     return preg_match("/\(v$version\)/", $class['DESC']);
2341   }
2343   
2345   function check_schema($cfg,$rfc2307bis = FALSE)
2346   {
2348     $messages= array();
2350     /* Get objectclasses */
2351     $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2352     $objectclasses = $ldap->get_objectclasses();
2353     if(count($objectclasses) == 0){
2354       print_red(_("Can't get schema information from server. No schema check possible!"));
2355     }
2357     /* This is the default block used for each entry.
2358      *  to avoid unset indexes.
2359      */
2360     $def_check = array("REQUIRED_VERSION" => "0",
2361                        "SCHEMA_FILES"     => array(),
2362                        "CLASSES_REQUIRED" => array(),
2363                        "STATUS"           => FALSE,
2364                        "IS_MUST_HAVE"     => FALSE,
2365                        "MSG"              => "",
2366                        "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2368  /* The gosa base schema */
2369     $checks['gosaObject'] = $def_check;
2370     $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2371     $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2372     $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2373     $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2375     /* GOsa Account class */
2376     $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2377     $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2378     $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2379     $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2380     $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2382     /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2383     $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2384     $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2385     $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2386     $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2387     $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2389   /* Some other checks */
2390     foreach(array(
2391           "gosaCacheEntry"        => array("version" => "2.4"),
2392           "gosaDepartment"        => array("version" => "2.4"),
2393           "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2394           "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2395           "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2396           "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2397           "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2398           "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2399           "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2400           "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2401           "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2402           "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2403           "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2404           "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2405           "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2406           "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2407           "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2408           "goLdapServer"          => array("version" => "2.4"),
2409           "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2410           "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2411           "goKrbServer"           => array("version" => "2.4"),
2412           "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2413           ) as $name => $values){
2415       $checks[$name] = $def_check;
2416       if(isset($values['version'])){
2417         $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2418       }
2419       if(isset($values['file'])){
2420         $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2421       }
2422       $checks[$name]["CLASSES_REQUIRED"] = array($name);
2423     }
2424    foreach($checks as $name => $value){
2425       foreach($value['CLASSES_REQUIRED'] as $class){
2427         if(!isset($objectclasses[$name])){
2428           $checks[$name]['STATUS'] = FALSE;
2429           if($value['IS_MUST_HAVE']){
2430             $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2431           }else{
2432             $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2433           }
2434         }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2435           $checks[$name]['STATUS'] = FALSE;
2437           if($value['IS_MUST_HAVE']){
2438             $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2439           }else{
2440             $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2441           }
2442         }else{
2443           $checks[$name]['STATUS'] = TRUE;
2444           $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2445         }
2446       }
2447     }
2449     $tmp = $objectclasses;
2452     /* The gosa base schema */
2453     $checks['posixGroup'] = $def_check;
2454     $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2455     $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2456     $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2457     $checks['posixGroup']['STATUS']           = TRUE;
2458     $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2459     $checks['posixGroup']['MSG']              = "";
2460     $checks['posixGroup']['INFO']             = "";
2462     /* Depending on selected rfc2307bis mode, we need different schema configurations */
2463     if(isset($tmp['posixGroup'])){
2465       if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2466         $checks['posixGroup']['STATUS']           = FALSE;
2467         $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2468         $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2469       }
2470       if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2471         $checks['posixGroup']['STATUS']           = FALSE;
2472         $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2473         $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2474       }
2475     }
2477     return($checks);
2478   }
2481 function prepare4mailbody($string)
2483   $string = html_entity_decode($string);
2485   $from = array(
2486                 "/%/",
2487                 "/ /",
2488                 "/\n/",  
2489                 "/\r/",
2490                 "/!/",
2491                 "/#/",
2492                 "/\*/",
2493                 "/\//",
2494                 "/</",
2495                 "/>/",
2496                 "/\?/",
2497                 "/\&/",
2498                 "/\(/",
2499                 "/\)/",
2500                 "/\"/");
2501   
2502   $to = array(  
2503                 "%25",
2504                 "%20",
2505                 "%0A",
2506                 "%0D",
2507                 "%21",
2508                 "%23",
2509                 "%2A",
2510                 "%2F",
2511                 "%3C",
2512                 "%3E",
2513                 "%3F",
2514                 "%38",
2515                 "%28",
2516                 "%29",
2517                 "%22");
2519   $string = preg_replace($from,$to,$string);
2521   return($string);
2525 function mac2company($mac)
2527   $vendor= "";
2529   /* Generate a normailzed mac... */
2530   $mac= substr(preg_replace('/[:-]/', '', $mac), 0, 6);
2532   /* Check for existance of the oui file */
2533   if (!is_readable(CONFIG_DIR."/oui.txt")){
2534     return ("");
2535   }
2537   /* Open file and look for mac addresses... */
2538   $handle = @fopen(CONFIG_DIR."/oui.txt", "r");
2539   if ($handle) {
2540     while (!feof($handle)) {
2541       $line = fgets($handle, 4096);
2543       if (preg_match("/^$mac/i", $line)){
2544         $vendor= substr($line, 32);
2545       }
2546     }
2547     fclose($handle);
2548   }
2550   return ($vendor);
2554 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2556   $tmp = array(
2557         "de_DE" => "German",
2558         "fr_FR" => "French",
2559         "it_IT" => "Italian",
2560         "es_ES" => "Spanish",
2561         "en_US" => "English",
2562         "nl_NL" => "Dutch",
2563         "pl_PL" => "Polish",
2564         "sv_SE" => "Swedish",
2565         "zh_CN" => "Chinese",
2566         "ru_RU" => "Russian");
2567   
2568   $tmp2= array(
2569         "de_DE" => _("German"),
2570         "fr_FR" => _("French"),
2571         "it_IT" => _("Italian"),
2572         "es_ES" => _("Spanish"),
2573         "en_US" => _("English"),
2574         "nl_NL" => _("Dutch"),
2575         "pl_PL" => _("Polish"),
2576         "sv_SE" => _("Swedish"),
2577         "zh_CN" => _("Chinese"),
2578         "ru_RU" => _("Russian"));
2580   $ret = array();
2581   if($languages_in_own_language){
2583     $old_lang = setlocale(LC_ALL, 0);
2584     foreach($tmp as $key => $name){
2585       $lang = $key.".UTF-8";
2586       setlocale(LC_ALL, $lang);
2587       if($strip_region_tag){
2588         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2589       }else{
2590         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2591       }
2592     }
2593     setlocale(LC_ALL, $old_lang);
2594   }else{
2595     foreach($tmp as $key => $name){
2596       if($strip_region_tag){
2597         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2598       }else{
2599         $ret[$key] = _($name);
2600       }
2601     }
2602   }
2603   return($ret);
2607 /* Check if $ip1 and $ip2 represents a valid IP range 
2608  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2609  */
2610 function is_ip_range($ip1,$ip2)
2612   if(!is_ip($ip1) || !is_ip($ip2)){
2613     return(FALSE);
2614   }else{
2615     $ar1 = split("\.",$ip1);
2616     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2618     $ar2 = split("\.",$ip2);
2619     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2620     return($var1 < $var2);
2621   }
2625 /* Check if the specified IP address $address is inside the given network */
2626 function is_in_network($network, $netmask, $address)
2628   $nw= split('\.', $network);
2629   $nm= split('\.', $netmask);
2630   $ad= split('\.', $address);
2632   /* Generate inverted netmask */
2633   for ($i= 0; $i<4; $i++){
2634     $ni[$i]= 255-$nm[$i];
2635     $la[$i]= $nw[$i] | $ni[$i];
2636   }
2638   /* Transform to integer */
2639   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2640   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2641   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2643   return ($first < $curr&& $last > $curr);
2647 /* Returns contents of the given POST variable and check magic quotes settings */
2648 function get_post($name)
2650   if(!isset($_POST[$name])){
2651     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2652     return(FALSE);
2653   }
2654   if(get_magic_quotes_gpc()){
2655     return(stripcslashes($_POST[$name]));
2656   }else{
2657     return($_POST[$name]);
2658   }
2661 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2662 ?>