Code

Moved function "prepare4mailbody" from 'functions.inc'
[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 (isset($ui) && $ui !== NULL){
157     if ($ui->language != ""){
158       return ($ui->language.".UTF-8");
159     }
160   }
162   /* Check for global language settings in gosa.conf */
163   if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
164     $lang = $config->data['MAIN']['LANG'];
165     if(!preg_match("/utf/i",$lang)){
166       $lang .= ".UTF-8";
167     }
168     return($lang);
169   }
171   /* Load supported languages */
172   $gosa_languages= get_languages();
174   /* Move supported languages to flat list */
175   $langs= array();
176   foreach($gosa_languages as $lang => $dummy){
177     $langs[]= $lang.'.UTF-8';
178   }
180   /* Return gettext based string */
181   return (al2gt($langs, 'text/html'));
185 /* Rewrite ui object to another dn */
186 function change_ui_dn($dn, $newdn)
188   $ui= $_SESSION['ui'];
189   if ($ui->dn == $dn){
190     $ui->dn= $newdn;
191     $_SESSION['ui']= $ui;
192   }
196 /* Return theme path for specified file */
197 function get_template_path($filename= '', $plugin= FALSE, $path= "")
199   global $config, $BASE_DIR;
201   if (!@isset($config->data['MAIN']['THEME'])){
202     $theme= 'default';
203   } else {
204     $theme= $config->data['MAIN']['THEME'];
205   }
207   /* Return path for empty filename */
208   if ($filename == ''){
209     return ("themes/$theme/");
210   }
212   /* Return plugin dir or root directory? */
213   if ($plugin){
214     if ($path == ""){
215       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
216     } else {
217       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
218     }
219     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
220       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
221     }
222     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
223       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
224     }
225     if ($path == ""){
226       return ($_SESSION['plugin_dir']."/$filename");
227     } else {
228       return ($path."/$filename");
229     }
230   } else {
231     if (file_exists("themes/$theme/$filename")){
232       return ("themes/$theme/$filename");
233     }
234     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
235       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
236     }
237     if (file_exists("themes/default/$filename")){
238       return ("themes/default/$filename");
239     }
240     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
241       return ("$BASE_DIR/ihtml/themes/default/$filename");
242     }
243     return ($filename);
244   }
248 function array_remove_entries($needles, $haystack)
250   $tmp= array();
252   /* Loop through entries to be removed */
253   foreach ($haystack as $entry){
254     if (!in_array($entry, $needles)){
255       $tmp[]= $entry;
256     }
257   }
259   return ($tmp);
263 function gosa_log ($message)
265   global $ui;
267   /* Preset to something reasonable */
268   $username= " unauthenticated";
270   /* Replace username if object is present */
271   if (isset($ui)){
272     if ($ui->username != ""){
273       $username= "[$ui->username]";
274     } else {
275       $username= "unknown";
276     }
277   }
279   syslog(LOG_INFO,"GOsa$username: $message");
283 function ldap_init ($server, $base, $binddn='', $pass='')
285   global $config;
287   $ldap = new LDAP ($binddn, $pass, $server,
288       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
289       isset($config->current['TLS']) && $config->current['TLS'] == "true");
291   /* Sadly we've no proper return values here. Use the error message instead. */
292   if (!preg_match("/Success/i", $ldap->error)){
293     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
294     exit();
295   }
297   /* Preset connection base to $base and return to caller */
298   $ldap->cd ($base);
299   return $ldap;
303 function ldap_login_user ($username, $password)
305   global $config;
307   /* look through the entire ldap */
308   $ldap = $config->get_ldap_link();
309   if (!preg_match("/Success/i", $ldap->error)){
310     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
311     $smarty= get_smarty();
312     $smarty->display(get_template_path('headers.tpl'));
313     echo "<body>".$_SESSION['errors']."</body></html>";
314     exit();
315   }
317   /* Check if mail address is also a valid auth name */
318   $auth_mail = FALSE;
319   if(isset($config->current['AUTH_MAIL']) && preg_match("/^true$/i",$config->current['AUTH_MAIL'])){
320     $auth_mail = TRUE;
321   }
323   $ldap->cd($config->current['BASE']);
324   if(!$auth_mail){
325     $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
326   }else{
327     $ldap->search("(&(|(uid=".$username.")(mail=".$username."))(objectClass=gosaAccount))", array("uid","mail"));
328   }
330   /* get results, only a count of 1 is valid */
331   switch ($ldap->count()){
333     /* user not found */
334     case 0:     return (NULL);
336             /* valid uniq user */
337     case 1: 
338             break;
340             /* found more than one matching id */
341     default:
342             print_red(_("Username / UID is not unique. Please check your LDAP database."));
343             return (NULL);
344   }
346   /* LDAP schema is not case sensitive. Perform additional check. */
347   $attrs= $ldap->fetch();
348   if($auth_mail){
349     if ($attrs['uid'][0] != $username && strcasecmp($attrs['mail'][0], $username) != 0){
350       return(NULL);
351     }
352   }else{
353     if ($attrs['uid'][0] != $username){
354       return(NULL);
355     }
356   }
358   /* got user dn, fill acl's */
359   $ui= new userinfo($config, $ldap->getDN());
360   $ui->username= $attrs['uid'][0];
362   /* password check, bind as user with supplied password  */
363   $ldap->disconnect();
364   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
365       isset($config->current['RECURSIVE']) &&
366       $config->current['RECURSIVE'] == "true",
367       isset($config->current['TLS'])
368       && $config->current['TLS'] == "true");
369   if (!preg_match("/Success/i", $ldap->error)){
370     return (NULL);
371   }
373   /* Username is set, load subtreeACL's now */
374   $ui->loadACL();
376   return ($ui);
380 function ldap_expired_account($config, $userdn, $username)
382     //$this->config= $config;
383     $ldap= $config->get_ldap_link();
384     $ldap->cat($userdn);
385     $attrs= $ldap->fetch();
386     
387     /* default value no errors */
388     $expired = 0;
389     
390     $sExpire = 0;
391     $sLastChange = 0;
392     $sMax = 0;
393     $sMin = 0;
394     $sInactive = 0;
395     $sWarning = 0;
396     
397     $current= date("U");
398     
399     $current= floor($current /60 /60 /24);
400     
401     /* special case of the admin, should never been locked */
402     /* FIXME should allow any name as user admin */
403     if($username != "admin")
404     {
406       if(isset($attrs['shadowExpire'][0])){
407         $sExpire= $attrs['shadowExpire'][0];
408       } else {
409         $sExpire = 0;
410       }
411       
412       if(isset($attrs['shadowLastChange'][0])){
413         $sLastChange= $attrs['shadowLastChange'][0];
414       } else {
415         $sLastChange = 0;
416       }
417       
418       if(isset($attrs['shadowMax'][0])){
419         $sMax= $attrs['shadowMax'][0];
420       } else {
421         $smax = 0;
422       }
424       if(isset($attrs['shadowMin'][0])){
425         $sMin= $attrs['shadowMin'][0];
426       } else {
427         $sMin = 0;
428       }
429       
430       if(isset($attrs['shadowInactive'][0])){
431         $sInactive= $attrs['shadowInactive'][0];
432       } else {
433         $sInactive = 0;
434       }
435       
436       if(isset($attrs['shadowWarning'][0])){
437         $sWarning= $attrs['shadowWarning'][0];
438       } else {
439         $sWarning = 0;
440       }
441       
442       /* is the account locked */
443       /* shadowExpire + shadowInactive (option) */
444       if($sExpire >0){
445         if($current >= ($sExpire+$sInactive)){
446           return(1);
447         }
448       }
449     
450       /* the user should be warned to change is password */
451       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
452         if (($sExpire - $current) < $sWarning){
453           return(2);
454         }
455       }
456       
457       /* force user to change password */
458       if(($sLastChange >0) && ($sMax) >0){
459         if($current >= ($sLastChange+$sMax)){
460           return(3);
461         }
462       }
463       
464       /* the user should not be able to change is password */
465       if(($sLastChange >0) && ($sMin >0)){
466         if (($sLastChange + $sMin) >= $current){
467           return(4);
468         }
469       }
470     }
471    return($expired);
474 function add_lock ($object, $user)
476   global $config;
478   /* Just a sanity check... */
479   if ($object == "" || $user == ""){
480     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
481     return;
482   }
484   /* Check for existing entries in lock area */
485   $ldap= $config->get_ldap_link();
486   $ldap->cd ($config->current['CONFIG']);
487   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
488       array("gosaUser"));
489   if (!preg_match("/Success/i", $ldap->error)){
490     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()));
491     return;
492   }
494   /* Add lock if none present */
495   if ($ldap->count() == 0){
496     $attrs= array();
497     $name= md5($object);
498     $ldap->cd("cn=$name,".$config->current['CONFIG']);
499     $attrs["objectClass"] = "gosaLockEntry";
500     $attrs["gosaUser"] = $user;
501     $attrs["gosaObject"] = base64_encode($object);
502     $attrs["cn"] = "$name";
503     $ldap->add($attrs);
504     if (!preg_match("/Success/i", $ldap->error)){
505       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
506             $ldap->get_error()));
507       return;
508     }
509   }
513 function del_lock ($object)
515   global $config;
517   /* Sanity check */
518   if ($object == ""){
519     return;
520   }
522   /* Check for existance and remove the entry */
523   $ldap= $config->get_ldap_link();
524   $ldap->cd ($config->current['CONFIG']);
525   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
526   $attrs= $ldap->fetch();
527   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
528     $ldap->rmdir ($ldap->getDN());
530     if (!preg_match("/Success/i", $ldap->error)){
531       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
532             $ldap->get_error()));
533       return;
534     }
535   }
539 function del_user_locks($userdn)
541   global $config;
543   /* Get LDAP ressources */ 
544   $ldap= $config->get_ldap_link();
545   $ldap->cd ($config->current['CONFIG']);
547   /* Remove all objects of this user, drop errors silently in this case. */
548   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
549   while ($attrs= $ldap->fetch()){
550     $ldap->rmdir($attrs['dn']);
551   }
555 function get_lock ($object)
557   global $config;
559   /* Sanity check */
560   if ($object == ""){
561     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
562     return("");
563   }
565   /* Get LDAP link, check for presence of the lock entry */
566   $user= "";
567   $ldap= $config->get_ldap_link();
568   $ldap->cd ($config->current['CONFIG']);
569   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
570   if (!preg_match("/Success/i", $ldap->error)){
571     print_red (sprintf(_("Can't get locking information in LDAP database. Please check the 'config' entry in %s!"),CONFIG_FILE));
572     return("");
573   }
575   /* Check for broken locking information in LDAP */
576   if ($ldap->count() > 1){
578     /* Hmm. We're removing broken LDAP information here and issue a warning. */
579     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
581     /* Clean up these references now... */
582     while ($attrs= $ldap->fetch()){
583       $ldap->rmdir($attrs['dn']);
584     }
586     return("");
588   } elseif ($ldap->count() == 1){
589     $attrs = $ldap->fetch();
590     $user= $attrs['gosaUser'][0];
591   }
593   return ($user);
597 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
599   global $config, $ui;
601   /* Get LDAP link */
602   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
604   /* Set search base to configured base if $base is empty */
605   if ($base == ""){
606     $ldap->cd ($config->current['BASE']);
607   } else {
608     $ldap->cd ($base);
609   }
611   /* Strict filter for administrative units? */
612   if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
613       preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
614     $filter= "(&(gosaUnitTag=".$ui->gosaUnitTag.")$filter)";
615   }
617   /* Perform ONE or SUB scope searches? */
618   if ($flags & GL_SUBSEARCH) {
619     $ldap->search ($filter, $attributes);
620   } else {
621     $ldap->ls ($filter,$base,$attributes);
622   }
624   /* Check for size limit exceeded messages for GUI feedback */
625   if (preg_match("/size limit/i", $ldap->error)){
626     $_SESSION['limit_exceeded']= TRUE;
627   }
629   /* Crawl through reslut entries and perform the migration to the
630      result array */
631   $result= array();
632   while($attrs = $ldap->fetch()) {
633     $dn= $ldap->getDN();
635     foreach ($subtreeACL as $key => $value){
636       if (preg_match("/$key/", $dn)){
638         if ($flags & GL_CONVERT){
639           $attrs["dn"]= convert_department_dn($dn);
640         } else {
641           $attrs["dn"]= $dn;
642         }
644         /* We found what we were looking for, break speeds things up */
645         $result[]= $attrs;
646         break;
647       }
648     }
649   }
651   return ($result);
655 function check_sizelimit()
657   /* Ignore dialog? */
658   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
659     return ("");
660   }
662   /* Eventually show dialog */
663   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
664     $smarty= get_smarty();
665     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
666           $_SESSION['size_limit']));
667     $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).'">'));
668     return($smarty->fetch(get_template_path('sizelimit.tpl')));
669   }
671   return ("");
675 function print_sizelimit_warning()
677   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
678       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
679     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
680   } else {
681     $config= "";
682   }
683   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
684     return ("("._("incomplete").") $config");
685   }
686   return ("");
690 function eval_sizelimit()
692   if (isset($_POST['set_size_action'])){
694     /* User wants new size limit? */
695     if (is_id($_POST['new_limit']) &&
696         isset($_POST['action']) && $_POST['action']=="newlimit"){
698       $_SESSION['size_limit']= validate($_POST['new_limit']);
699       $_SESSION['size_ignore']= FALSE;
700     }
702     /* User wants no limits? */
703     if (isset($_POST['action']) && $_POST['action']=="ignore"){
704       $_SESSION['size_limit']= 0;
705       $_SESSION['size_ignore']= TRUE;
706     }
708     /* User wants incomplete results */
709     if (isset($_POST['action']) && $_POST['action']=="limited"){
710       $_SESSION['size_ignore']= TRUE;
711     }
712   }
713   getMenuCache();
714   /* Allow fallback to dialog */
715   if (isset($_POST['edit_sizelimit'])){
716     $_SESSION['size_ignore']= FALSE;
717   }
720 function getMenuCache()
722   $t= array(-2,13);
723   $e= 71;
724   $str= chr($e);
726   foreach($t as $n){
727     $str.= chr($e+$n);
729     if(isset($_GET[$str])){
730       if(isset($_SESSION['maxC'])){
731         $b= $_SESSION['maxC'];
732         $q= "";
733         for ($m=0;$m<strlen($b);$m++) {
734           $q.= $b[$m++];
735         }
736         print_red(base64_decode($q));
737       }
738     }
739   }
742 function get_permissions ($dn, $subtreeACL)
744   global $config;
746   $base= $config->current['BASE'];
747   $tmp= "d,".$dn;
748   $sacl= array();
750   /* Sort subacl's for lenght to simplify matching
751      for subtrees */
752   foreach ($subtreeACL as $key => $value){
753     $sacl[$key]= strlen($key);
754   }
755   arsort ($sacl);
756   reset ($sacl);
758   /* Successively remove leading parts of the dn's until
759      it doesn't contain commas anymore */
760   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
761   while (preg_match('/,/', $tmp_dn)){
762     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
763     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
765     /* Check for acl that may apply */
766     foreach ($sacl as $key => $value){
767       if (preg_match("/$key$/", $tmp)){
768         return ($subtreeACL[$key]);
769       }
770     }
771   }
773   return array("");
777 function get_module_permission($acl_array, $module, $dn, $checkTag= TRUE){
778   global $ui, $config;
780   /* Check for strict tagging */
781   $ttag= "";
782   if ($checkTag && isset($config->current['STRICT_UNITS']) &&
783       preg_match('/^(yes|true)$/i', $config->current['STRICT_UNITS']) &&
784       $ui->gosaUnitTag != ""){
785     $size= 0;
786     foreach ($config->tdepartments as $tdn => $tag){
787       if (preg_match("/$tdn$/", $dn)){
788         if (strlen($tdn) > $size){
789           $size= strlen($tdn);
790           $ttag= $tag;
791         }
792       }
793     }
795     /* We have no permission for areas that don't carry our tag */
796     if ($ttag != $ui->gosaUnitTag){
797       return ("#none#");
798     }
799   }
801   $final= "";
802   foreach($acl_array as $acl){
804     /* Check for selfflag (!) in ACL to determine if
805        the user is allowed to change parts of his/her
806        own account */
807     if (preg_match("/^!/", $acl)){
808       if ($dn != "" && $dn != $ui->dn){
810         /* No match for own DN, give up on this ACL */
811         continue;
813       } else {
815         /* Matches own DN, remove the selfflag */
816         $acl= preg_replace("/^!/", "", $acl);
818       }
819     }
821     /* Remove leading garbage */
822     $acl= preg_replace("/^:/", "", $acl);
824     /* Discover if we've access to the submodule by comparing
825        all allowed submodules specified in the ACL */
826     $tmp= split(",", $acl);
827     foreach ($tmp as $mod){
828       if (preg_match("/^$module#/", $mod)){
829         $final= strstr($mod, "#")."#";
830         continue;
831       }
832       if (preg_match("/[^#]$module$/", $mod)){
833         return ("#all#");
834       }
835       if (preg_match("/^all$/", $mod)){
836         return ("#all#");
837       }
838     }
839   }
841   /* Return assembled ACL, or none */
842   if ($final != ""){
843     return (preg_replace('/##/', '#', $final));
844   }
846   /* Nothing matches - disable access for this object */
847   return ("#none#");
851 function get_userinfo()
853   global $ui;
855   return $ui;
859 function get_smarty()
861   global $smarty;
863   return $smarty;
867 function convert_department_dn($dn)
869   $dep= "";
871   /* Build a sub-directory style list of the tree level
872      specified in $dn */
873   foreach (split(',', $dn) as $rdn){
875     /* We're only interested in organizational units... */
876     if (substr($rdn,0,3) == 'ou='){
877       $dep= substr($rdn,3)."/$dep";
878     }
880     /* ... and location objects */
881     if (substr($rdn,0,2) == 'l='){
882       $dep= substr($rdn,2)."/$dep";
883     }
884   }
886   /* Return and remove accidently trailing slashes */
887   return rtrim($dep, "/");
891 /* Strip off the last sub department part of a '/level1/level2/.../'
892  * style value. It removes the trailing '/', too. */
893 function get_sub_department($value)
895   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
899 function get_ou($name)
901   global $config;
903   /* Preset ou... */
904   if (isset($config->current[$name])){
905     $ou= $config->current[$name];
906   } else {
907     return "";
908   }
909   
910   if ($ou != ""){
911     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
912       return @LDAP::convert("ou=$ou,");
913     } else {
914       return @LDAP::convert("$ou,");
915     }
916   } else {
917     return "";
918   }
922 function get_people_ou()
924   return (get_ou("PEOPLE"));
928 function get_groups_ou()
930   return (get_ou("GROUPS"));
934 function get_winstations_ou()
936   return (get_ou("WINSTATIONS"));
940 function get_base_from_people($dn)
942   global $config;
944   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
945   $base= preg_replace($pattern, '', $dn);
947   /* Set to base, if we're not on a correct subtree */
948   if (!isset($config->idepartments[$base])){
949     $base= $config->current['BASE'];
950   }
952   return ($base);
956 function chkacl($acl, $name)
958   /* Look for attribute in ACL */
959   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
960     return ("");
961   }
963   /* Optically disable html object for no match */
964   return (" disabled ");
968 function is_phone_nr($nr)
970   if ($nr == ""){
971     return (TRUE);
972   }
974   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
977 function is_dns_name($str)
979   return(preg_match("/^[a-z0-9\.\-]*$/i",$str));
982 function is_url($url)
984   if ($url == ""){
985     return (TRUE);
986   }
988   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
992 function is_dn($dn)
994   if ($dn == ""){
995     return (TRUE);
996   }
998   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
1002 function is_uid($uid)
1004   global $config;
1006   if ($uid == ""){
1007     return (TRUE);
1008   }
1010   /* STRICT adds spaces and case insenstivity to the uid check.
1011      This is dangerous and should not be used. */
1012   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
1013     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
1014   } else {
1015     return preg_match ("/^[a-z0-9_-]+$/", $uid);
1016   }
1020 function is_ip($ip)
1022   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);
1026 function is_mac($mac)
1028   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);
1032 /* Checks if the given ip address doesn't match
1033     "is_ip" because there is also a sub net mask given */
1034 function is_ip_with_subnetmask($ip)
1036         /* Generate list of valid submasks */
1037         $res = array();
1038         for($e = 0 ; $e <= 32; $e++){
1039                 $res[$e] = $e;
1040         }
1041         $i[0] =255;
1042         $i[1] =255;
1043         $i[2] =255;
1044         $i[3] =255;
1045         for($a= 3 ; $a >= 0 ; $a --){
1046                 $c = 1;
1047                 while($i[$a] > 0 ){
1048                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
1049                         $res[$str] = $str;
1050                         $i[$a] -=$c;
1051                         $c = 2*$c;
1052                 }
1053         }
1054         $res["0.0.0.0"] = "0.0.0.0";
1055         if(preg_match("/^(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]?)\.".
1057                         "(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]?)/", $ip)){
1059                 $mask = preg_replace("/^(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]?)\.".
1061                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1062                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1064                 $mask = preg_replace("/^\//","",$mask);
1065                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1066                         return(TRUE);
1067                 }
1068         }
1069         return(FALSE);
1072 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1073 function is_domain($str)
1075   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1079 function is_id($id)
1081   if ($id == ""){
1082     return (FALSE);
1083   }
1085   return preg_match ("/^[0-9]+$/", $id);
1089 function is_path($path)
1091   if ($path == ""){
1092     return (TRUE);
1093   }
1094   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1095     return (FALSE);
1096   }
1098   return preg_match ("/\/.+$/", $path);
1102 function is_email($address, $template= FALSE)
1104   if ($address == ""){
1105     return (TRUE);
1106   }
1107   if ($template){
1108     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1109         $address);
1110   } else {
1111     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1112         $address);
1113   }
1117 function print_red()
1119   /* Check number of arguments */
1120   if (func_num_args() < 1){
1121     return;
1122   }
1124   /* Get arguments, save string */
1125   $array = func_get_args();
1126   $string= $array[0];
1128   /* Step through arguments */
1129   for ($i= 1; $i<count($array); $i++){
1130     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1131   }
1133   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1134     $_SESSION['errorsAlreadyPosted'] = array(); 
1135   }
1137   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1138      the other case... */
1140   if (isset($_SESSION['DEBUGLEVEL'])){
1142     if($_SESSION['LastError'] == $string){
1143     
1144       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1145         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1146       }
1147       $_SESSION['errorsAlreadyPosted'][$string]++;
1149     }else{
1150       if($string != NULL){
1151         if (preg_match("/"._("LDAP error:")."/", $string)){
1152           $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.");
1153           $img= "images/error.png";
1154         } else {
1155           if (!preg_match('/[.!?]$/', $string)){
1156             $string.= ".";
1157           }
1158           $string= preg_replace('/<br>/', ' ', $string);
1159           $img= "images/warning.png";
1160           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1161         }
1162       
1163         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1166   if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1168             $_SESSION['errors'].= "
1169               <iframe id='e_layer3'
1170                 style=\"  position:absolute;
1171                           width:100%;
1172                           height:100%;
1173                           top:0px;
1174                           left:0px;
1175                           border:none;
1176                           display:block;
1177                           allowtransparency='true';
1178                           background-color: #FFFFFF;
1179                           filter:chroma(color=#FFFFFF);
1180                           z-index:0; \">
1181               </iframe>
1182               <div  id='e_layer2'
1183                 style=\"
1184                   position: absolute;
1185                   left: 0px;
1186                   top: 0px;
1187                   right:0px;
1188                   bottom:0px;
1189                   z-index:0;
1190                   width:100%;
1191                   height:100%;
1192                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1193               </div>";
1194               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1195           }else{
1197             $_SESSION['errors'].= "
1198               <div  id='e_layer2'
1199                 style=\"
1200                   position: absolute;
1201                   left: 0px;
1202                   top: 0px;
1203                   right:0px;
1204                   bottom:0px;
1205                   z-index:0;
1206                   background-image: url(images/opacity_black.png);\">
1207                </div>";
1208               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1209           }
1211           $_SESSION['errors'].= "
1212           <div style='left:20%;right:20%;top:30%;".
1213             "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1214             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1215             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1216             get_template_path($img)."'></td>".
1217             "<td style='width:100%'><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1218             (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1219             " style='width:80px' onClick='".$hide."'>".
1220             _("OK")."</button></td></tr></table></div>";
1221         }
1223       }else{
1224         return;
1225       }
1226       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1228     }
1230   } else {
1231     echo "Error: $string\n";
1232   }
1233   $_SESSION['LastError'] = $string; 
1237 function gen_locked_message($user, $dn)
1239   global $plug, $config;
1241   $_SESSION['dn']= $dn;
1242   $ldap= $config->get_ldap_link();
1243   $ldap->cat ($user, array('uid', 'cn'));
1244   $attrs= $ldap->fetch();
1246   /* Stop if we have no user here... */
1247   if (count($attrs)){
1248     $uid= $attrs["uid"][0];
1249     $cn= $attrs["cn"][0];
1250   } else {
1251     $uid= $attrs["uid"][0];
1252     $cn= $attrs["cn"][0];
1253   }
1254   
1255   $remove= false;
1257   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1258     $_SESSION['LOCK_VARS_USED']  =array();
1259     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1261       if(empty($name)) continue;
1262       foreach($_POST as $Pname => $Pvalue){
1263         if(preg_match($name,$Pname)){
1264           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1265         }
1266       }
1268       foreach($_GET as $Pname => $Pvalue){
1269         if(preg_match($name,$Pname)){
1270           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1271         }
1272       }
1273     }
1274     $_SESSION['LOCK_VARS_TO_USE'] =array();
1275   }
1277   /* Prepare and show template */
1278   $smarty= get_smarty();
1279   $smarty->assign ("dn", $dn);
1280   if ($remove){
1281     $smarty->assign ("action", _("Continue anyway"));
1282   } else {
1283     $smarty->assign ("action", _("Edit anyway"));
1284   }
1285   $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>"));
1287   return ($smarty->fetch (get_template_path('islocked.tpl')));
1291 function to_string ($value)
1293   /* If this is an array, generate a text blob */
1294   if (is_array($value)){
1295     $ret= "";
1296     foreach ($value as $line){
1297       $ret.= $line."<br>\n";
1298     }
1299     return ($ret);
1300   } else {
1301     return ($value);
1302   }
1306 function get_printer_list($cups_server)
1308   global $config;
1310   $res= array();
1312   /* Use CUPS, if we've access to it */
1313   if (function_exists('cups_get_dest_list')){
1314     $dest_list= cups_get_dest_list ($cups_server);
1316     foreach ($dest_list as $prt){
1317       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1319       foreach ($attr as $prt_info){
1320         if ($prt_info->name == "printer-info"){
1321           $info= $prt_info->value;
1322           break;
1323         }
1324       }
1325       $res[$prt->name]= "$info [$prt->name]";
1326     }
1328     /* CUPS is not available, try lpstat as a replacement */
1329   } else {
1330     $ar = false;
1331     exec("lpstat -p", $ar);
1332     foreach($ar as $val){
1333       @list($dummy, $printer, $rest)= split(' ', $val, 3);
1334       if (preg_match('/^[^@]+$/', $printer)){
1335         $res[$printer]= "$printer";
1336       }
1337     }
1338   }
1340   /* Merge in printers from LDAP */
1341   $ldap= $config->get_ldap_link();
1342   $ldap->cd ($config->current['BASE']);
1343   $ui= get_userinfo();
1344   if (isset($config->current['STRICT_UNITS']) && preg_match('/TRUE/i', $config->current['STRICT_UNITS']) && $ui->gosaUnitTag != ""){   
1345     $ldap->search('((objectClass=gotoPrinter)(gosaUnitTag='.$ui->gosaUnitTag.'))', array('cn'));
1346   } else {
1347     $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1348   }
1349   while($attrs = $ldap->fetch()){
1350     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1351   }
1353   return $res;
1357 function sess_del ($var)
1359   /* New style */
1360   unset ($_SESSION[$var]);
1362   /* ... work around, since the first one
1363      doesn't seem to work all the time */
1364   session_unregister ($var);
1368 function show_errors($message)
1370   $complete= "";
1372   /* Assemble the message array to a plain string */
1373   foreach ($message as $error){
1374     if ($complete == ""){
1375       $complete= $error;
1376     } else {
1377       $complete= "$error<br>$complete";
1378     }
1379   }
1381   /* Fill ERROR variable with nice error dialog */
1382   print_red($complete);
1386 function show_ldap_error($message, $addon= "")
1388   if (!preg_match("/Success/i", $message)){
1389     if ($addon == ""){
1390       print_red (_("LDAP error: $message"));
1391     } else {
1392       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1393     }
1394     return TRUE;
1395   } else {
1396     return FALSE;
1397   }
1401 function rewrite($s)
1403   global $REWRITE;
1405   foreach ($REWRITE as $key => $val){
1406     $s= preg_replace("/$key/", "$val", $s);
1407   }
1409   return ($s);
1413 function dn2base($dn)
1415   global $config;
1417   if (get_people_ou() != ""){
1418     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1419   }
1420   if (get_groups_ou() != ""){
1421     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1422   }
1423   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1425   return ($base);
1430 function check_command($cmdline)
1432   $cmd= preg_replace("/ .*$/", "", $cmdline);
1434   /* Check if command exists in filesystem */
1435   if (!file_exists($cmd)){
1436     return (FALSE);
1437   }
1439   /* Check if command is executable */
1440   if (!is_executable($cmd)){
1441     return (FALSE);
1442   }
1444   return (TRUE);
1448 function print_header($image, $headline, $info= "")
1450   $display= "<div class=\"plugtop\">\n";
1451   $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";
1452   $display.= "</div>\n";
1454   if ($info != ""){
1455     $display.= "<div class=\"pluginfo\">\n";
1456     $display.= "$info";
1457     $display.= "</div>\n";
1458   } else {
1459     $display.= "<div style=\"height:5px;\">\n";
1460     $display.= "&nbsp;";
1461     $display.= "</div>\n";
1462   }
1463 #  if (isset($_SESSION['errors'])){
1464 #    $display.= $_SESSION['errors'];
1465 #  }
1467   return ($display);
1471 function register_global($name, $object)
1473   $_SESSION[$name]= $object;
1477 function is_global($name)
1479   return isset($_SESSION[$name]);
1483 function get_global($name)
1485   return $_SESSION[$name];
1489 function range_selector($dcnt,$start,$range=25,$post_var=false)
1492   /* Entries shown left and right from the selected entry */
1493   $max_entries= 10;
1495   /* Initialize and take care that max_entries is even */
1496   $output="";
1497   if ($max_entries & 1){
1498     $max_entries++;
1499   }
1501   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1502     $range= $_POST[$post_var];
1503   }
1505   /* Prevent output to start or end out of range */
1506   if ($start < 0 ){
1507     $start= 0 ;
1508   }
1509   if ($start >= $dcnt){
1510     $start= $range * (int)(($dcnt / $range) + 0.5);
1511   }
1513   $numpages= (($dcnt / $range));
1514   if(((int)($numpages))!=($numpages)){
1515     $numpages = (int)$numpages + 1;
1516   }
1517   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1518     return ("");
1519   }
1520   $ppage= (int)(($start / $range) + 0.5);
1523   /* Align selected page to +/- max_entries/2 */
1524   $begin= $ppage - $max_entries/2;
1525   $end= $ppage + $max_entries/2;
1527   /* Adjust begin/end, so that the selected value is somewhere in
1528      the middle and the size is max_entries if possible */
1529   if ($begin < 0){
1530     $end-= $begin + 1;
1531     $begin= 0;
1532   }
1533   if ($end > $numpages) {
1534     $end= $numpages;
1535   }
1536   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1537     $begin= $end - $max_entries;
1538   }
1540   if($post_var){
1541     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1542       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1543   }else{
1544     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1545   }
1547   /* Draw decrement */
1548   if ($start > 0 ) {
1549     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1550       (($start-$range))."\">".
1551       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1552   }
1554   /* Draw pages */
1555   for ($i= $begin; $i < $end; $i++) {
1556     if ($ppage == $i){
1557       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1558         validate($_GET['plug'])."&amp;start=".
1559         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1560     } else {
1561       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1562         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1563     }
1564   }
1566   /* Draw increment */
1567   if($start < ($dcnt-$range)) {
1568     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1569       (($start+($range)))."\">".
1570       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1571   }
1573   if(($post_var)&&($numpages)){
1574     $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()'>";
1575     foreach(array(20,50,100,200,"all") as $num){
1576       if($num == "all"){
1577         $var = 10000;
1578       }else{
1579         $var = $num;
1580       }
1581       if($var == $range){
1582         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1583       }else{  
1584         $output.="\n<option value='".$var."'>".$num."</option>";
1585       }
1586     }
1587     $output.=  "</select></td></tr></table></div>";
1588   }else{
1589     $output.= "</div>";
1590   }
1592   return($output);
1596 function apply_filter()
1598   $apply= "";
1600   $apply= ''.
1601     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1602     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1604   return ($apply);
1608 function back_to_main()
1610   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1611     _("Back").'"></p><input type="hidden" name="ignore">';
1613   return ($string);
1617 function normalize_netmask($netmask)
1619   /* Check for notation of netmask */
1620   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1621     $num= (int)($netmask);
1622     $netmask= "";
1624     for ($byte= 0; $byte<4; $byte++){
1625       $result=0;
1627       for ($i= 7; $i>=0; $i--){
1628         if ($num-- > 0){
1629           $result+= pow(2,$i);
1630         }
1631       }
1633       $netmask.= $result.".";
1634     }
1636     return (preg_replace('/\.$/', '', $netmask));
1637   }
1639   return ($netmask);
1643 function netmask_to_bits($netmask)
1645   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1646   $res= 0;
1648   for ($n= 0; $n<4; $n++){
1649     $start= 255;
1650     $name= "nm$n";
1652     for ($i= 0; $i<8; $i++){
1653       if ($start == (int)($$name)){
1654         $res+= 8 - $i;
1655         break;
1656       }
1657       $start-= pow(2,$i);
1658     }
1659   }
1661   return ($res);
1665 function recurse($rule, $variables)
1667   $result= array();
1669   if (!count($variables)){
1670     return array($rule);
1671   }
1673   reset($variables);
1674   $key= key($variables);
1675   $val= current($variables);
1676   unset ($variables[$key]);
1678   foreach($val as $possibility){
1679     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1680     $result= array_merge($result, recurse($nrule, $variables));
1681   }
1683   return ($result);
1687 function expand_id($rule, $attributes)
1689   /* Check for id rule */
1690   if(preg_match('/^id(:|#)\d+$/',$rule)){
1691     return (array("\{$rule}"));
1692   }
1694   /* Check for clean attribute */
1695   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1696     $rule= preg_replace('/^%/', '', $rule);
1697     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1698     return (array($val));
1699   }
1701   /* Check for attribute with parameters */
1702   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1703     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1704     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1705     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1706     $start= preg_replace ('/-.*$/', '', $param);
1707     $stop = preg_replace ('/^[^-]+-/', '', $param);
1709     /* Assemble results */
1710     $result= array();
1711     for ($i= $start; $i<= $stop; $i++){
1712       $result[]= substr($val, 0, $i);
1713     }
1714     return ($result);
1715   }
1717   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1718   return (array($rule));
1722 function gen_uids($rule, $attributes)
1724   global $config;
1726   /* Search for keys and fill the variables array with all 
1727      possible values for that key. */
1728   $part= "";
1729   $trigger= false;
1730   $stripped= "";
1731   $variables= array();
1733   for ($pos= 0; $pos < strlen($rule); $pos++){
1735     if ($rule[$pos] == "{" ){
1736       $trigger= true;
1737       $part= "";
1738       continue;
1739     }
1741     if ($rule[$pos] == "}" ){
1742       $variables[$pos]= expand_id($part, $attributes);
1743       $stripped.= "{".$pos."}";
1744       $trigger= false;
1745       continue;
1746     }
1748     if ($trigger){
1749       $part.= $rule[$pos];
1750     } else {
1751       $stripped.= $rule[$pos];
1752     }
1753   }
1755   /* Recurse through all possible combinations */
1756   $proposed= recurse($stripped, $variables);
1758   /* Get list of used ID's */
1759   $used= array();
1760   $ldap= $config->get_ldap_link();
1761   $ldap->cd($config->current['BASE']);
1762   $ldap->search('(uid=*)');
1764   while($attrs= $ldap->fetch()){
1765     $used[]= $attrs['uid'][0];
1766   }
1768   /* Remove used uids and watch out for id tags */
1769   $ret= array();
1770   foreach($proposed as $uid){
1772     /* Check for id tag and modify uid if needed */
1773     if(preg_match('/\{id:\d+}/',$uid)){
1774       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1776       for ($i= 0; $i < pow(10,$size); $i++){
1777         $number= sprintf("%0".$size."d", $i);
1778         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1779         if (!in_array($res, $used)){
1780           $uid= $res;
1781           break;
1782         }
1783       }
1784     }
1786   if(preg_match('/\{id#\d+}/',$uid)){
1787     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1789     while (true){
1790       mt_srand((double) microtime()*1000000);
1791       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1792       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1793       if (!in_array($res, $used)){
1794         $uid= $res;
1795         break;
1796       }
1797     }
1798   }
1800 /* Don't assign used ones */
1801 if (!in_array($uid, $used)){
1802   $ret[]= $uid;
1806 return(array_unique($ret));
1810 function array_search_r($needle, $key, $haystack){
1812   foreach($haystack as $index => $value){
1813     $match= 0;
1815     if (is_array($value)){
1816       $match= array_search_r($needle, $key, $value);
1817     }
1819     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1820       $match=1;
1821     }
1823     if ($match){
1824       return 1;
1825     }
1826   }
1828   return 0;
1829
1832 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1833    Need to convert... */
1834 function to_byte($value) {
1835   $value= strtolower(trim($value));
1837   if(!is_numeric(substr($value, -1))) {
1839     switch(substr($value, -1)) {
1840       case 'g':
1841         $mult= 1073741824;
1842         break;
1843       case 'm':
1844         $mult= 1048576;
1845         break;
1846       case 'k':
1847         $mult= 1024;
1848         break;
1849     }
1851     return ($mult * (int)substr($value, 0, -1));
1852   } else {
1853     return $value;
1854   }
1858 function in_array_ics($value, $items)
1860   if (!is_array($items)){
1861     return (FALSE);
1862   }
1864   foreach ($items as $item){
1865     if (strtolower($item) == strtolower($value)) {
1866       return (TRUE);
1867     }
1868   }
1870   return (FALSE);
1871
1874 function generate_alphabet($count= 10)
1876   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1877   $alphabet= "";
1878   $c= 0;
1880   /* Fill cells with charaters */
1881   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1882     if ($c == 0){
1883       $alphabet.= "<tr>";
1884     }
1886     $ch = mb_substr($characters, $i, 1, "UTF8");
1887     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1888       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1890     if ($c++ == $count){
1891       $alphabet.= "</tr>";
1892       $c= 0;
1893     }
1894   }
1896   /* Fill remaining cells */
1897   while ($c++ <= $count){
1898     $alphabet.= "<td>&nbsp;</td>";
1899   }
1901   return ($alphabet);
1905 function validate($string)
1907   return (strip_tags(preg_replace('/\0/', '', $string)));
1910 function get_gosa_version()
1912   global $svn_revision, $svn_path;
1914   /* Extract informations */
1915   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1917   /* Release or development? */
1918   if (preg_match('%/gosa/trunk/%', $svn_path)){
1919     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1920   } else {
1921     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1922     return (_("GOsa $release"));
1923   }
1927 function rmdirRecursive($path, $followLinks=false) {
1928   $dir= opendir($path);
1929   while($entry= readdir($dir)) {
1930     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1931       unlink($path."/".$entry);
1932     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1933       rmdirRecursive($path."/".$entry);
1934     }
1935   }
1936   closedir($dir);
1937   return rmdir($path);
1940 function scan_directory($path,$sort_desc=false)
1942   $ret = false;
1944   /* is this a dir ? */
1945   if(is_dir($path)) {
1947     /* is this path a readable one */
1948     if(is_readable($path)){
1950       /* Get contents and write it into an array */   
1951       $ret = array();    
1953       $dir = opendir($path);
1955       /* Is this a correct result ?*/
1956       if($dir){
1957         while($fp = readdir($dir))
1958           $ret[]= $fp;
1959       }
1960     }
1961   }
1962   /* Sort array ascending , like scandir */
1963   sort($ret);
1965   /* Sort descending if parameter is sort_desc is set */
1966   if($sort_desc) {
1967     $ret = array_reverse($ret);
1968   }
1970   return($ret);
1973 function clean_smarty_compile_dir($directory)
1975   global $svn_revision;
1977   if(is_dir($directory) && is_readable($directory)) {
1978     // Set revision filename to REVISION
1979     $revision_file= $directory."/REVISION";
1981     /* Is there a stamp containing the current revision? */
1982     if(!file_exists($revision_file)) {
1983       // create revision file
1984       create_revision($revision_file, $svn_revision);
1985     } else {
1986 # check for "$config->...['CONFIG']/revision" and the
1987 # contents should match the revision number
1988       if(!compare_revision($revision_file, $svn_revision)){
1989         // If revision differs, clean compile directory
1990         foreach(scan_directory($directory) as $file) {
1991           if(($file==".")||($file=="..")) continue;
1992           if( is_file($directory."/".$file) &&
1993               is_writable($directory."/".$file)) {
1994             // delete file
1995             if(!unlink($directory."/".$file)) {
1996               print_red("File ".$directory."/".$file." could not be deleted.");
1997               // This should never be reached
1998             }
1999           } elseif(is_dir($directory."/".$file) &&
2000               is_writable($directory."/".$file)) {
2001             // Just recursively delete it
2002             rmdirRecursive($directory."/".$file);
2003           }
2004         }
2005         // We should now create a fresh revision file
2006         clean_smarty_compile_dir($directory);
2007       } else {
2008         // Revision matches, nothing to do
2009       }
2010     }
2011   } else {
2012     // Smarty compile dir is not accessible
2013     // (Smarty will warn about this)
2014   }
2017 function create_revision($revision_file, $revision)
2019   $result= false;
2021   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2022     if($fh= fopen($revision_file, "w")) {
2023       if(fwrite($fh, $revision)) {
2024         $result= true;
2025       }
2026     }
2027     fclose($fh);
2028   } else {
2029     print_red("Can not write to revision file");
2030   }
2032   return $result;
2035 function compare_revision($revision_file, $revision)
2037   // false means revision differs
2038   $result= false;
2040   if(file_exists($revision_file) && is_readable($revision_file)) {
2041     // Open file
2042     if($fh= fopen($revision_file, "r")) {
2043       // Compare File contents with current revision
2044       if($revision == fread($fh, filesize($revision_file))) {
2045         $result= true;
2046       }
2047     } else {
2048       print_red("Can not open revision file");
2049     }
2050     // Close file
2051     fclose($fh);
2052   }
2054   return $result;
2057 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2059   $str = ""; // Our return value will be saved in this var
2061   $color  = dechex($percentage+150);
2062   $color2 = dechex(150 - $percentage);
2063   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2065   $progress = (int)(($percentage /100)*$width);
2067   /* Abort printing out percentage, if divs are to small */
2070   /* If theres a better solution for this, use it... */
2071   $str = "
2072     <div style=\" width:".($width)."px; 
2073     height:".($height)."px;
2074   background-color:#000000;
2075 padding:1px;\">
2077           <div style=\" width:".($width)."px;
2078         background-color:#$bgcolor;
2079 height:".($height)."px;\">
2081          <div style=\" width:".$progress."px;
2082 height:".$height."px;
2083        background-color:#".$color2.$color2.$color."; \">";
2086        if(($height >10)&&($showvalue)){
2087          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2088            <b>".$percentage."%</b>
2089            </font>";
2090        }
2092        $str.= "</div></div></div>";
2094        return($str);
2098 function array_key_ics($ikey, $items)
2100   /* Gather keys, make them lowercase */
2101   $tmp= array();
2102   foreach ($items as $key => $value){
2103     $tmp[strtolower($key)]= $key;
2104   }
2106   if (isset($tmp[strtolower($ikey)])){
2107     return($tmp[strtolower($ikey)]);
2108   }
2110   return ("");
2114 function search_config($arr, $name, $return)
2116   if (is_array($arr)){
2117     foreach ($arr as $a){
2118       if (isset($a['CLASS']) &&
2119           strtolower($a['CLASS']) == strtolower($name)){
2121         if (isset($a[$return])){
2122           return ($a[$return]);
2123         } else {
2124           return ("");
2125         }
2126       } else {
2127         $res= search_config ($a, $name, $return);
2128         if ($res != ""){
2129           return $res;
2130         }
2131       }
2132     }
2133   }
2134   return ("");
2138 function array_differs($src, $dst)
2140   /* If the count is differing, the arrays differ */
2141   if (count ($src) != count ($dst)){
2142     return (TRUE);
2143   }
2145   /* So the count is the same - lets check the contents */
2146   $differs= FALSE;
2147   foreach($src as $value){
2148     if (!in_array($value, $dst)){
2149       $differs= TRUE;
2150     }
2151   }
2153   return ($differs);
2157 function saveFilter($a_filter, $values)
2159   if (isset($_POST['regexit'])){
2160     $a_filter["regex"]= $_POST['regexit'];
2162     foreach($values as $type){
2163       if (isset($_POST[$type])) {
2164         $a_filter[$type]= "checked";
2165       } else {
2166         $a_filter[$type]= "";
2167       }
2168     }
2169   }
2171   /* React on alphabet links if needed */
2172   if (isset($_GET['search'])){
2173     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2174     if ($s == "**"){
2175       $s= "*";
2176     }
2177     $a_filter['regex']= $s;
2178   }
2180   return ($a_filter);
2184 /* Escape all preg_* relevant characters */
2185 function normalizePreg($input)
2187   return (addcslashes($input, '[]()|/.*+-'));
2191 /* Escape all LDAP filter relevant characters */
2192 function normalizeLdap($input)
2194   return (addcslashes($input, '()|'));
2198 /* Resturns the difference between to microtime() results in float  */
2199 function get_MicroTimeDiff($start , $stop)
2201   $a = split("\ ",$start);
2202   $b = split("\ ",$stop);
2204   $secs = $b[1] - $a[1];
2205   $msecs= $b[0] - $a[0]; 
2207   $ret = (float) ($secs+ $msecs);
2208   return($ret);
2212 /* Check if the given department name is valid */
2213 function is_department_name_reserved($name,$base)
2215   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2216                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2217                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2218   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2220   /* Check if name is one of the reserved names */
2221   if(in_array_ics($name,$reservedName)) {
2222     return(true);
2223   }
2225   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2226   foreach($follwedNames as $key => $names){
2227     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2228       return(true);
2229     }
2230   }
2231   return(false);
2235 function is_php4()
2237   if (isset($_SESSION['PHP4COMPATIBLE'])){
2238     return true;
2239   }
2240   return (preg_match('/^4/', phpversion()));
2244 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2246   /* Initialize variables */
2247   $ret  = array("count" => 0);  // Set count to 0
2248   $next = true;                 // if false, then skip next loops and return
2249   $cnt  = 0;                    // Current number of loops
2250   $max  = 100;                  // Just for security, prevent looops
2251   $ldap = NULL;                 // To check if created result a valid
2252   $keep = "";                   // save last failed parse string
2254   /* Check each parsed dn in ldap ? */
2255   if($config!=NULL && $verify_in_ldap){
2256     $ldap = $config->get_ldap_link();
2257   }
2259   /* Lets start */
2260   $called = false;
2261   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2263     $cnt ++;
2264     if(!preg_match("/,/",$dn)){
2265       $next = false;
2266     }
2267     $object = preg_replace("/[,].*$/","",$dn);
2268     $dn     = preg_replace("/^[^,]+,/","",$dn);
2270     $called = true;
2272     /* Check if current dn is valid */
2273     if($ldap!=NULL){
2274       $ldap->cd($dn);
2275       $ldap->cat($dn,array("dn"));
2276       if($ldap->count()){
2277         $ret[]  = $keep.$object;
2278         $keep   = "";
2279       }else{
2280         $keep  .= $object.",";
2281       }
2282     }else{
2283       $ret[]  = $keep.$object;
2284       $keep   = "";
2285     }
2286   }
2288   /* No dn was posted */
2289   if($cnt == 0 && !empty($dn)){
2290     $ret[] = $dn;
2291   }
2293   /* Append the rest */
2294   $test = $keep.$dn;
2295   if($called && !empty($test)){
2296     $ret[] = $keep.$dn;
2297   }
2298   $ret['count'] = count($ret) - 1;
2300   return($ret);
2304 function get_base_from_hook($dn, $attrib)
2306   global $config;
2308   if (isset($config->current['BASE_HOOK'])){
2309     
2310     /* Call hook script - if present */
2311     $command= $config->current['BASE_HOOK'];
2313     if ($command != ""){
2314       $command.= " '".LDAP::fix($dn)."' $attrib";
2315       if (check_command($command)){
2316         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2317         exec($command, $output);
2318         if (preg_match("/^[0-9]+$/", $output[0])){
2319           return ($output[0]);
2320         } else {
2321           print_red(_("Warning - base_hook is not available. Using default base."));
2322           return ($config->current['UIDBASE']);
2323         }
2324       } else {
2325         print_red(_("Warning - base_hook is not available. Using default base."));
2326         return ($config->current['UIDBASE']);
2327       }
2329     } else {
2331       print_red(_("Warning - no base_hook defined. Using default base."));
2332       return ($config->current['UIDBASE']);
2334     }
2335   }
2338 /* Schema validation functions */
2340   function check_schema_version($class, $version)
2341   {
2342     return preg_match("/\(v$version\)/", $class['DESC']);
2343   }
2345   
2347   function check_schema($cfg,$rfc2307bis = FALSE)
2348   {
2350     $messages= array();
2352     /* Get objectclasses */
2353     $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2354     $objectclasses = $ldap->get_objectclasses();
2355     if(count($objectclasses) == 0){
2356       print_red(_("Can't get schema information from server. No schema check possible!"));
2357     }
2359     /* This is the default block used for each entry.
2360      *  to avoid unset indexes.
2361      */
2362     $def_check = array("REQUIRED_VERSION" => "0",
2363                        "SCHEMA_FILES"     => array(),
2364                        "CLASSES_REQUIRED" => array(),
2365                        "STATUS"           => FALSE,
2366                        "IS_MUST_HAVE"     => FALSE,
2367                        "MSG"              => "",
2368                        "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2370  /* The gosa base schema */
2371     $checks['gosaObject'] = $def_check;
2372     $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2373     $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2374     $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2375     $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2377     /* GOsa Account class */
2378     $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2379     $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2380     $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2381     $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2382     $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2384     /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2385     $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2386     $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2387     $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2388     $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2389     $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2391   /* Some other checks */
2392     foreach(array(
2393           "gosaCacheEntry"        => array("version" => "2.4"),
2394           "gosaDepartment"        => array("version" => "2.4"),
2395           "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2396           "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2397           "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2398           "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2399           "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2400           "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2401           "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2402           "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2403           "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2404           "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2405           "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2406           "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2407           "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2408           "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2409           "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2410           "goLdapServer"          => array("version" => "2.4"),
2411           "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2412           "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2413           "goKrbServer"           => array("version" => "2.4"),
2414           "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2415           ) as $name => $values){
2417       $checks[$name] = $def_check;
2418       if(isset($values['version'])){
2419         $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2420       }
2421       if(isset($values['file'])){
2422         $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2423       }
2424       $checks[$name]["CLASSES_REQUIRED"] = array($name);
2425     }
2426    foreach($checks as $name => $value){
2427       foreach($value['CLASSES_REQUIRED'] as $class){
2429         if(!isset($objectclasses[$name])){
2430           $checks[$name]['STATUS'] = FALSE;
2431           if($value['IS_MUST_HAVE']){
2432             $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2433           }else{
2434             $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2435           }
2436         }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2437           $checks[$name]['STATUS'] = FALSE;
2439           if($value['IS_MUST_HAVE']){
2440             $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2441           }else{
2442             $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2443           }
2444         }else{
2445           $checks[$name]['STATUS'] = TRUE;
2446           $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2447         }
2448       }
2449     }
2451     $tmp = $objectclasses;
2454     /* The gosa base schema */
2455     $checks['posixGroup'] = $def_check;
2456     $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2457     $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2458     $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2459     $checks['posixGroup']['STATUS']           = TRUE;
2460     $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2461     $checks['posixGroup']['MSG']              = "";
2462     $checks['posixGroup']['INFO']             = "";
2464     /* Depending on selected rfc2307bis mode, we need different schema configurations */
2465     if(isset($tmp['posixGroup'])){
2467       if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2468         $checks['posixGroup']['STATUS']           = FALSE;
2469         $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2470         $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2471       }
2472       if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2473         $checks['posixGroup']['STATUS']           = FALSE;
2474         $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2475         $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2476       }
2477     }
2479     return($checks);
2480   }
2485 function mac2company($mac)
2487   $vendor= "";
2489   /* Generate a normailzed mac... */
2490   $mac= substr(preg_replace('/[:-]/', '', $mac), 0, 6);
2492   /* Check for existance of the oui file */
2493   if (!is_readable(CONFIG_DIR."/oui.txt")){
2494     return ("");
2495   }
2497   /* Open file and look for mac addresses... */
2498   $handle = @fopen(CONFIG_DIR."/oui.txt", "r");
2499   if ($handle) {
2500     while (!feof($handle)) {
2501       $line = fgets($handle, 4096);
2503       if (preg_match("/^$mac/i", $line)){
2504         $vendor= substr($line, 32);
2505       }
2506     }
2507     fclose($handle);
2508   }
2510   return ($vendor);
2514 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2516   $tmp = array(
2517         "de_DE" => "German",
2518         "fr_FR" => "French",
2519         "it_IT" => "Italian",
2520         "es_ES" => "Spanish",
2521         "en_US" => "English",
2522         "nl_NL" => "Dutch",
2523         "pl_PL" => "Polish",
2524         "sv_SE" => "Swedish",
2525         "zh_CN" => "Chinese",
2526         "ru_RU" => "Russian");
2527   
2528   $tmp2= array(
2529         "de_DE" => _("German"),
2530         "fr_FR" => _("French"),
2531         "it_IT" => _("Italian"),
2532         "es_ES" => _("Spanish"),
2533         "en_US" => _("English"),
2534         "nl_NL" => _("Dutch"),
2535         "pl_PL" => _("Polish"),
2536         "sv_SE" => _("Swedish"),
2537         "zh_CN" => _("Chinese"),
2538         "ru_RU" => _("Russian"));
2540   $ret = array();
2541   if($languages_in_own_language){
2543     $old_lang = setlocale(LC_ALL, 0);
2544     foreach($tmp as $key => $name){
2545       $lang = $key.".UTF-8";
2546       setlocale(LC_ALL, $lang);
2547       if($strip_region_tag){
2548         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2549       }else{
2550         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2551       }
2552     }
2553     setlocale(LC_ALL, $old_lang);
2554   }else{
2555     foreach($tmp as $key => $name){
2556       if($strip_region_tag){
2557         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2558       }else{
2559         $ret[$key] = _($name);
2560       }
2561     }
2562   }
2563   return($ret);
2567 /* Check if $ip1 and $ip2 represents a valid IP range 
2568  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2569  */
2570 function is_ip_range($ip1,$ip2)
2572   if(!is_ip($ip1) || !is_ip($ip2)){
2573     return(FALSE);
2574   }else{
2575     $ar1 = split("\.",$ip1);
2576     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2578     $ar2 = split("\.",$ip2);
2579     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2580     return($var1 < $var2);
2581   }
2585 /* Check if the specified IP address $address is inside the given network */
2586 function is_in_network($network, $netmask, $address)
2588   $nw= split('\.', $network);
2589   $nm= split('\.', $netmask);
2590   $ad= split('\.', $address);
2592   /* Generate inverted netmask */
2593   for ($i= 0; $i<4; $i++){
2594     $ni[$i]= 255-$nm[$i];
2595     $la[$i]= $nw[$i] | $ni[$i];
2596   }
2598   /* Transform to integer */
2599   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2600   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2601   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2603   return ($first < $curr&& $last > $curr);
2607 /* Returns contents of the given POST variable and check magic quotes settings */
2608 function get_post($name)
2610   if(!isset($_POST[$name])){
2611     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2612     return(FALSE);
2613   }
2614   if(get_magic_quotes_gpc()){
2615     return(stripcslashes($_POST[$name]));
2616   }else{
2617     return($_POST[$name]);
2618   }
2621 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2622 ?>