Code

same for gosa+samba3.schema.
[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 /* Allow setting the config patih in the apache configuration
22    e.g.  SetEnv CONFIG_FILE /etc/path
23  */
24 if(!isset($_SERVER['CONFIG_DIR'])){
25   define ("CONFIG_DIR", "/etc/gosa");
26 }else{
27   define ("CONFIG_DIR",$_SERVER['CONFIG_DIR']);
28 }
30 /* Allow setting the config file in the apache configuration
31     e.g.  SetEnv CONFIG_FILE gosa.conf.2.5
32  */
33 if(!isset($_SERVER['CONFIG_FILE'])){
34   define ("CONFIG_FILE", "gosa.conf");
35 }else{
36   define ("CONFIG_FILE",$_SERVER['CONFIG_FILE']);
37 }
39 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
40 define ("HELP_BASEDIR", "/var/www/doc/");
42 /* Define get_list flags */
43 define("GL_NONE",      0);
44 define("GL_SUBSEARCH", 1);
45 define("GL_SIZELIMIT", 2);
46 define("GL_CONVERT"  , 4);
48 /* Define globals for revision comparing */
49 $svn_path = '$HeadURL$';
50 $svn_revision = '$Revision$';
52 /* Include required files */
53 require_once ("class_ldap.inc");
54 require_once ("class_config.inc");
55 require_once ("class_userinfo.inc");
56 require_once ("class_plugin.inc");
57 require_once ("class_dhcpPlugin.inc");
58 require_once ("class_pluglist.inc");
59 require_once ("class_tabs.inc");
60 require_once ("class_mail-methods.inc");
61 require_once("class_password-methods.inc");
62 require_once ("functions_debug.inc");
63 require_once ("functions_dns.inc");
64 require_once ("accept-to-gettext.inc");
65 require_once ("class_MultiSelectWindow.inc");
67 /* Define constants for debugging */
68 define ("DEBUG_TRACE",   1);
69 define ("DEBUG_LDAP",    2);
70 define ("DEBUG_MYSQL",   4);
71 define ("DEBUG_SHELL",   8);
72 define ("DEBUG_POST",   16);
73 define ("DEBUG_SESSION",32);
74 define ("DEBUG_CONFIG", 64);
76 /* Rewrite german 'umlauts' and spanish 'accents'
77    to get better results */
78 $REWRITE= array( "ä" => "ae",
79     "ö" => "oe",
80     "ü" => "ue",
81     "Ä" => "Ae",
82     "Ö" => "Oe",
83     "Ü" => "Ue",
84     "ß" => "ss",
85     "á" => "a",
86     "é" => "e",
87     "í" => "i",
88     "ó" => "o",
89     "ú" => "u",
90     "Á" => "A",
91     "É" => "E",
92     "Í" => "I",
93     "Ó" => "O",
94     "Ú" => "U",
95     "ñ" => "ny",
96     "Ñ" => "Ny" );
99 /* Function to include all class_ files starting at a
100    given directory base */
101 function get_dir_list($folder= ".")
103   $currdir=getcwd();
104   if ($folder){
105     chdir("$folder");
106   }
108   $dh = opendir(".");
109   while(false !== ($file = readdir($dh))){
111     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
112     // Skip all files and dirs in  "./.svn/" we don't need any information from them
113     // Skip all Template, so they won't be checked twice in the following preg_matches   
114     // Skip . / ..
116     // Result  : from 1023 ms to 490 ms   i think thats great...
117     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
118       continue;
121     /* Recurse through all "common" directories */
122     if(is_dir($file) &&$file!="CVS"){
123       get_dir_list($file);
124       continue;
125     }
127     /* Include existing class_ files */
128     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
129       require_once($file);
130     }
131   }
133   closedir($dh);
134   chdir($currdir);
138 /* Create seed with microseconds */
139 function make_seed() {
140   list($usec, $sec) = explode(' ', microtime());
141   return (float) $sec + ((float) $usec * 100000);
145 /* Debug level action */
146 function DEBUG($level, $line, $function, $file, $data, $info="")
148   if ($_SESSION['DEBUGLEVEL'] & $level){
149     $output= "DEBUG[$level] ";
150     if ($function != ""){
151       $output.= "($file:$function():$line) - $info: ";
152     } else {
153       $output.= "($file:$line) - $info: ";
154     }
155     echo $output;
156     if (is_array($data)){
157       print_a($data);
158     } else {
159       echo "'$data'";
160     }
161     echo "<br>";
162   }
166 function get_browser_language()
168   /* Try to use users primary language */
169   global $config;
170   $ui= get_userinfo();
171   if (isset($ui) && $ui !== NULL){
172     if ($ui->language != ""){
173       return ($ui->language.".UTF-8");
174     }
175   }
177   /* Check for global language settings in gosa.conf */
178   if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
179     $lang = $config->data['MAIN']['LANG'];
180     if(!preg_match("/utf/i",$lang)){
181       $lang .= ".UTF-8";
182     }
183     return($lang);
184   }
186   /* Load supported languages */
187   $gosa_languages= get_languages();
189   /* Move supported languages to flat list */
190   $langs= array();
191   foreach($gosa_languages as $lang => $dummy){
192     $langs[]= $lang.'.UTF-8';
193   }
195   /* Return gettext based string */
196   return (al2gt($langs, 'text/html'));
200 /* Rewrite ui object to another dn */
201 function change_ui_dn($dn, $newdn)
203   $ui= $_SESSION['ui'];
204   if ($ui->dn == $dn){
205     $ui->dn= $newdn;
206     $_SESSION['ui']= $ui;
207   }
211 /* Return theme path for specified file */
212 function get_template_path($filename= '', $plugin= FALSE, $path= "")
214   global $config, $BASE_DIR;
216   if (!@isset($config->data['MAIN']['THEME'])){
217     $theme= 'default';
218   } else {
219     $theme= $config->data['MAIN']['THEME'];
220   }
222   /* Return path for empty filename */
223   if ($filename == ''){
224     return ("themes/$theme/");
225   }
227   /* Return plugin dir or root directory? */
228   if ($plugin){
229     if ($path == ""){
230       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
231     } else {
232       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
233     }
234     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
235       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
236     }
237     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
238       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
239     }
240     if ($path == ""){
241       return ($_SESSION['plugin_dir']."/$filename");
242     } else {
243       return ($path."/$filename");
244     }
245   } else {
246     if (file_exists("themes/$theme/$filename")){
247       return ("themes/$theme/$filename");
248     }
249     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
250       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
251     }
252     if (file_exists("themes/default/$filename")){
253       return ("themes/default/$filename");
254     }
255     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
256       return ("$BASE_DIR/ihtml/themes/default/$filename");
257     }
258     return ($filename);
259   }
263 function array_remove_entries($needles, $haystack)
265   $tmp= array();
267   /* Loop through entries to be removed */
268   foreach ($haystack as $entry){
269     if (!in_array($entry, $needles)){
270       $tmp[]= $entry;
271     }
272   }
274   return ($tmp);
278 function gosa_log ($message)
280   global $ui;
282   /* Preset to something reasonable */
283   $username= " unauthenticated";
285   /* Replace username if object is present */
286   if (isset($ui)){
287     if ($ui->username != ""){
288       $username= "[$ui->username]";
289     } else {
290       $username= "unknown";
291     }
292   }
294   syslog(LOG_INFO,"GOsa$username: $message");
298 function ldap_init ($server, $base, $binddn='', $pass='')
300   global $config;
302   $ldap = new LDAP ($binddn, $pass, $server,
303       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
304       isset($config->current['TLS']) && $config->current['TLS'] == "true");
306   /* Sadly we've no proper return values here. Use the error message instead. */
307   if (!preg_match("/Success/i", $ldap->error)){
308     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
309     exit();
310   }
312   /* Preset connection base to $base and return to caller */
313   $ldap->cd ($base);
314   return $ldap;
318 function ldap_login_user ($username, $password)
320   global $config;
322   /* look through the entire ldap */
323   $ldap = $config->get_ldap_link();
324   if (!preg_match("/Success/i", $ldap->error)){
325     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
326     $smarty= get_smarty();
327     $smarty->display(get_template_path('headers.tpl'));
328     echo "<body>".$_SESSION['errors']."</body></html>";
329     exit();
330   }
332   /* Check if mail address is also a valid auth name */
333   $auth_mail = FALSE;
334   if(isset($config->current['AUTH_MAIL']) && preg_match("/^true$/i",$config->current['AUTH_MAIL'])){
335     $auth_mail = TRUE;
336   }
338   $ldap->cd($config->current['BASE']);
339   if(!$auth_mail){
340     $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
341   }else{
342     $ldap->search("(&(|(uid=".$username.")(mail=".$username."))(objectClass=gosaAccount))", array("uid","mail"));
343   }
345   /* get results, only a count of 1 is valid */
346   switch ($ldap->count()){
348     /* user not found */
349     case 0:     return (NULL);
351             /* valid uniq user */
352     case 1: 
353             break;
355             /* found more than one matching id */
356     default:
357             print_red(_("Username / UID is not unique. Please check your LDAP database."));
358             return (NULL);
359   }
361   /* LDAP schema is not case sensitive. Perform additional check. */
362   $attrs= $ldap->fetch();
363   if($auth_mail){
364     if ($attrs['uid'][0] != $username && strcasecmp($attrs['mail'][0], $username) != 0){
365       return(NULL);
366     }
367   }else{
368     if ($attrs['uid'][0] != $username){
369       return(NULL);
370     }
371   }
373   /* got user dn, fill acl's */
374   $ui= new userinfo($config, $ldap->getDN());
375   $ui->username= $attrs['uid'][0];
377   /* password check, bind as user with supplied password  */
378   $ldap->disconnect();
379   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
380       isset($config->current['RECURSIVE']) &&
381       $config->current['RECURSIVE'] == "true",
382       isset($config->current['TLS'])
383       && $config->current['TLS'] == "true");
384   if (!preg_match("/Success/i", $ldap->error)){
385     return (NULL);
386   }
388   /* Username is set, load subtreeACL's now */
389   $ui->loadACL();
391   return ($ui);
395 function ldap_expired_account($config, $userdn, $username)
397     //$this->config= $config;
398     $ldap= $config->get_ldap_link();
399     $ldap->cat($userdn);
400     $attrs= $ldap->fetch();
401     
402     /* default value no errors */
403     $expired = 0;
404     
405     $sExpire = 0;
406     $sLastChange = 0;
407     $sMax = 0;
408     $sMin = 0;
409     $sInactive = 0;
410     $sWarning = 0;
411     
412     $current= date("U");
413     
414     $current= floor($current /60 /60 /24);
415     
416     /* special case of the admin, should never been locked */
417     /* FIXME should allow any name as user admin */
418     if($username != "admin")
419     {
421       if(isset($attrs['shadowExpire'][0])){
422         $sExpire= $attrs['shadowExpire'][0];
423       } else {
424         $sExpire = 0;
425       }
426       
427       if(isset($attrs['shadowLastChange'][0])){
428         $sLastChange= $attrs['shadowLastChange'][0];
429       } else {
430         $sLastChange = 0;
431       }
432       
433       if(isset($attrs['shadowMax'][0])){
434         $sMax= $attrs['shadowMax'][0];
435       } else {
436         $smax = 0;
437       }
439       if(isset($attrs['shadowMin'][0])){
440         $sMin= $attrs['shadowMin'][0];
441       } else {
442         $sMin = 0;
443       }
444       
445       if(isset($attrs['shadowInactive'][0])){
446         $sInactive= $attrs['shadowInactive'][0];
447       } else {
448         $sInactive = 0;
449       }
450       
451       if(isset($attrs['shadowWarning'][0])){
452         $sWarning= $attrs['shadowWarning'][0];
453       } else {
454         $sWarning = 0;
455       }
456       
457       /* is the account locked */
458       /* shadowExpire + shadowInactive (option) */
459       if($sExpire >0){
460         if($current >= ($sExpire+$sInactive)){
461           return(1);
462         }
463       }
464     
465       /* the user should be warned to change is password */
466       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
467         if (($sExpire - $current) < $sWarning){
468           return(2);
469         }
470       }
471       
472       /* force user to change password */
473       if(($sLastChange >0) && ($sMax) >0){
474         if($current >= ($sLastChange+$sMax)){
475           return(3);
476         }
477       }
478       
479       /* the user should not be able to change is password */
480       if(($sLastChange >0) && ($sMin >0)){
481         if (($sLastChange + $sMin) >= $current){
482           return(4);
483         }
484       }
485     }
486    return($expired);
489 function add_lock ($object, $user)
491   global $config;
493   /* Just a sanity check... */
494   if ($object == "" || $user == ""){
495     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
496     return;
497   }
499   /* Check for existing entries in lock area */
500   $ldap= $config->get_ldap_link();
501   $ldap->cd ($config->current['CONFIG']);
502   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
503       array("gosaUser"));
504   if (!preg_match("/Success/i", $ldap->error)){
505     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()));
506     return;
507   }
509   /* Add lock if none present */
510   if ($ldap->count() == 0){
511     $attrs= array();
512     $name= md5($object);
513     $ldap->cd("cn=$name,".$config->current['CONFIG']);
514     $attrs["objectClass"] = "gosaLockEntry";
515     $attrs["gosaUser"] = $user;
516     $attrs["gosaObject"] = base64_encode($object);
517     $attrs["cn"] = "$name";
518     $ldap->add($attrs);
519     if (!preg_match("/Success/i", $ldap->error)){
520       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
521             $ldap->get_error()));
522       return;
523     }
524   }
528 function del_lock ($object)
530   global $config;
532   /* Sanity check */
533   if ($object == ""){
534     return;
535   }
537   /* Check for existance and remove the entry */
538   $ldap= $config->get_ldap_link();
539   $ldap->cd ($config->current['CONFIG']);
540   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
541   $attrs= $ldap->fetch();
542   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
543     $ldap->rmdir ($ldap->getDN());
545     if (!preg_match("/Success/i", $ldap->error)){
546       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
547             $ldap->get_error()));
548       return;
549     }
550   }
554 function del_user_locks($userdn)
556   global $config;
558   /* Get LDAP ressources */ 
559   $ldap= $config->get_ldap_link();
560   $ldap->cd ($config->current['CONFIG']);
562   /* Remove all objects of this user, drop errors silently in this case. */
563   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
564   while ($attrs= $ldap->fetch()){
565     $ldap->rmdir($attrs['dn']);
566   }
570 function get_lock ($object)
572   global $config;
574   /* Sanity check */
575   if ($object == ""){
576     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
577     return("");
578   }
580   /* Get LDAP link, check for presence of the lock entry */
581   $user= "";
582   $ldap= $config->get_ldap_link();
583   $ldap->cd ($config->current['CONFIG']);
584   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
585   if (!preg_match("/Success/i", $ldap->error)){
586     print_red (sprintf(_("Can't get locking information in LDAP database. Please check the 'config' entry in %s!"),CONFIG_FILE));
587     return("");
588   }
590   /* Check for broken locking information in LDAP */
591   if ($ldap->count() > 1){
593     /* Hmm. We're removing broken LDAP information here and issue a warning. */
594     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
596     /* Clean up these references now... */
597     while ($attrs= $ldap->fetch()){
598       $ldap->rmdir($attrs['dn']);
599     }
601     return("");
603   } elseif ($ldap->count() == 1){
604     $attrs = $ldap->fetch();
605     $user= $attrs['gosaUser'][0];
606   }
608   return ($user);
612 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
614   global $config, $ui;
616   /* Get LDAP link */
617   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
619   /* Set search base to configured base if $base is empty */
620   if ($base == ""){
621     $ldap->cd ($config->current['BASE']);
622   } else {
623     $ldap->cd ($base);
624   }
626   /* Strict filter for administrative units? */
627   if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
628       preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
629     $filter= "(&(gosaUnitTag=".$ui->gosaUnitTag.")$filter)";
630   }
632   /* Perform ONE or SUB scope searches? */
633   if ($flags & GL_SUBSEARCH) {
634     $ldap->search ($filter, $attributes);
635   } else {
636     $ldap->ls ($filter,$base,$attributes);
637   }
639   /* Check for size limit exceeded messages for GUI feedback */
640   if (preg_match("/size limit/i", $ldap->error)){
641     $_SESSION['limit_exceeded']= TRUE;
642   }
644   /* Crawl through reslut entries and perform the migration to the
645      result array */
646   $result= array();
647   while($attrs = $ldap->fetch()) {
648     $dn= $ldap->getDN();
650     foreach ($subtreeACL as $key => $value){
651       if (preg_match("/$key/", $dn)){
653         if ($flags & GL_CONVERT){
654           $attrs["dn"]= convert_department_dn($dn);
655         } else {
656           $attrs["dn"]= $dn;
657         }
659         /* We found what we were looking for, break speeds things up */
660         $result[]= $attrs;
661         break;
662       }
663     }
664   }
666   return ($result);
670 function check_sizelimit()
672   /* Ignore dialog? */
673   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
674     return ("");
675   }
677   /* Eventually show dialog */
678   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
679     $smarty= get_smarty();
680     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
681           $_SESSION['size_limit']));
682     $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).'">'));
683     return($smarty->fetch(get_template_path('sizelimit.tpl')));
684   }
686   return ("");
690 function print_sizelimit_warning()
692   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
693       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
694     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
695   } else {
696     $config= "";
697   }
698   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
699     return ("("._("incomplete").") $config");
700   }
701   return ("");
705 function eval_sizelimit()
707   if (isset($_POST['set_size_action'])){
709     /* User wants new size limit? */
710     if (is_id($_POST['new_limit']) &&
711         isset($_POST['action']) && $_POST['action']=="newlimit"){
713       $_SESSION['size_limit']= validate($_POST['new_limit']);
714       $_SESSION['size_ignore']= FALSE;
715     }
717     /* User wants no limits? */
718     if (isset($_POST['action']) && $_POST['action']=="ignore"){
719       $_SESSION['size_limit']= 0;
720       $_SESSION['size_ignore']= TRUE;
721     }
723     /* User wants incomplete results */
724     if (isset($_POST['action']) && $_POST['action']=="limited"){
725       $_SESSION['size_ignore']= TRUE;
726     }
727   }
728   getMenuCache();
729   /* Allow fallback to dialog */
730   if (isset($_POST['edit_sizelimit'])){
731     $_SESSION['size_ignore']= FALSE;
732   }
735 function getMenuCache()
737   $t= array(-2,13);
738   $e= 71;
739   $str= chr($e);
741   foreach($t as $n){
742     $str.= chr($e+$n);
744     if(isset($_GET[$str])){
745       if(isset($_SESSION['maxC'])){
746         $b= $_SESSION['maxC'];
747         $q= "";
748         for ($m=0;$m<strlen($b);$m++) {
749           $q.= $b[$m++];
750         }
751         print_red(base64_decode($q));
752       }
753     }
754   }
757 function get_permissions ($dn, $subtreeACL)
759   global $config;
761   $base= $config->current['BASE'];
762   $tmp= "d,".$dn;
763   $sacl= array();
765   /* Sort subacl's for lenght to simplify matching
766      for subtrees */
767   foreach ($subtreeACL as $key => $value){
768     $sacl[$key]= strlen($key);
769   }
770   arsort ($sacl);
771   reset ($sacl);
773   /* Successively remove leading parts of the dn's until
774      it doesn't contain commas anymore */
775   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
776   while (preg_match('/,/', $tmp_dn)){
777     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
778     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
780     /* Check for acl that may apply */
781     foreach ($sacl as $key => $value){
782       if (preg_match("/$key$/", $tmp)){
783         return ($subtreeACL[$key]);
784       }
785     }
786   }
788   return array("");
792 function get_module_permission($acl_array, $module, $dn, $checkTag= TRUE){
793   global $ui, $config;
795   /* Check for strict tagging */
796   $ttag= "";
797   if ($checkTag && isset($config->current['STRICT_UNITS']) &&
798       preg_match('/^(yes|true)$/i', $config->current['STRICT_UNITS']) &&
799       $ui->gosaUnitTag != ""){
800     $size= 0;
801     foreach ($config->tdepartments as $tdn => $tag){
802       if (preg_match("/$tdn$/", $dn)){
803         if (strlen($tdn) > $size){
804           $size= strlen($tdn);
805           $ttag= $tag;
806         }
807       }
808     }
810     /* We have no permission for areas that don't carry our tag */
811     if ($ttag != $ui->gosaUnitTag){
812       return ("#none#");
813     }
814   }
816   $final= "";
817   foreach($acl_array as $acl){
819     /* Check for selfflag (!) in ACL to determine if
820        the user is allowed to change parts of his/her
821        own account */
822     if (preg_match("/^!/", $acl)){
823       if ($dn != "" && $dn != $ui->dn){
825         /* No match for own DN, give up on this ACL */
826         continue;
828       } else {
830         /* Matches own DN, remove the selfflag */
831         $acl= preg_replace("/^!/", "", $acl);
833       }
834     }
836     /* Remove leading garbage */
837     $acl= preg_replace("/^:/", "", $acl);
839     /* Discover if we've access to the submodule by comparing
840        all allowed submodules specified in the ACL */
841     $tmp= split(",", $acl);
842     foreach ($tmp as $mod){
843       if (preg_match("/^$module#/", $mod)){
844         $final= strstr($mod, "#")."#";
845         continue;
846       }
847       if (preg_match("/[^#]$module$/", $mod)){
848         return ("#all#");
849       }
850       if (preg_match("/^all$/", $mod)){
851         return ("#all#");
852       }
853     }
854   }
856   /* Return assembled ACL, or none */
857   if ($final != ""){
858     return (preg_replace('/##/', '#', $final));
859   }
861   /* Nothing matches - disable access for this object */
862   return ("#none#");
866 function get_userinfo()
868   global $ui;
870   return $ui;
874 function get_smarty()
876   global $smarty;
878   return $smarty;
882 function convert_department_dn($dn)
884   $dep= "";
886   /* Build a sub-directory style list of the tree level
887      specified in $dn */
888   foreach (split(',', $dn) as $rdn){
890     /* We're only interested in organizational units... */
891     if (substr($rdn,0,3) == 'ou='){
892       $dep= substr($rdn,3)."/$dep";
893     }
895     /* ... and location objects */
896     if (substr($rdn,0,2) == 'l='){
897       $dep= substr($rdn,2)."/$dep";
898     }
899   }
901   /* Return and remove accidently trailing slashes */
902   return rtrim($dep, "/");
906 /* Strip off the last sub department part of a '/level1/level2/.../'
907  * style value. It removes the trailing '/', too. */
908 function get_sub_department($value)
910   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
914 function get_ou($name)
916   global $config;
918   /* Preset ou... */
919   if (isset($config->current[$name])){
920     $ou= $config->current[$name];
921   } else {
922     return "";
923   }
924   
925   if ($ou != ""){
926     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
927       return @LDAP::convert("ou=$ou,");
928     } else {
929       return @LDAP::convert("$ou,");
930     }
931   } else {
932     return "";
933   }
937 function get_people_ou()
939   return (get_ou("PEOPLE"));
943 function get_groups_ou()
945   return (get_ou("GROUPS"));
949 function get_winstations_ou()
951   return (get_ou("WINSTATIONS"));
955 function get_base_from_people($dn)
957   global $config;
959   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
960   $base= preg_replace($pattern, '', $dn);
962   /* Set to base, if we're not on a correct subtree */
963   if (!isset($config->idepartments[$base])){
964     $base= $config->current['BASE'];
965   }
967   return ($base);
971 function chkacl($acl, $name)
973   /* Look for attribute in ACL */
974   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
975     return ("");
976   }
978   /* Optically disable html object for no match */
979   return (" disabled ");
983 function is_phone_nr($nr)
985   if ($nr == ""){
986     return (TRUE);
987   }
989   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
992 function is_dns_name($str)
994   return(preg_match("/^[a-z0-9\.\-]*$/i",$str));
997 function is_url($url)
999   if ($url == ""){
1000     return (TRUE);
1001   }
1003   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
1007 function is_dn($dn)
1009   if ($dn == ""){
1010     return (TRUE);
1011   }
1013   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
1017 function is_uid($uid)
1019   global $config;
1021   if ($uid == ""){
1022     return (TRUE);
1023   }
1025   /* STRICT adds spaces and case insenstivity to the uid check.
1026      This is dangerous and should not be used. */
1027   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
1028     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
1029   } else {
1030     return preg_match ("/^[a-z0-9_-]+$/", $uid);
1031   }
1035 function is_ip($ip)
1037   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);
1041 function is_mac($mac)
1043   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);
1047 /* Checks if the given ip address doesn't match
1048     "is_ip" because there is also a sub net mask given */
1049 function is_ip_with_subnetmask($ip)
1051         /* Generate list of valid submasks */
1052         $res = array();
1053         for($e = 0 ; $e <= 32; $e++){
1054                 $res[$e] = $e;
1055         }
1056         $i[0] =255;
1057         $i[1] =255;
1058         $i[2] =255;
1059         $i[3] =255;
1060         for($a= 3 ; $a >= 0 ; $a --){
1061                 $c = 1;
1062                 while($i[$a] > 0 ){
1063                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
1064                         $res[$str] = $str;
1065                         $i[$a] -=$c;
1066                         $c = 2*$c;
1067                 }
1068         }
1069         $res["0.0.0.0"] = "0.0.0.0";
1070         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1071                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1072                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1073                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
1074                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1075                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1076                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1077                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1079                 $mask = preg_replace("/^\//","",$mask);
1080                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1081                         return(TRUE);
1082                 }
1083         }
1084         return(FALSE);
1087 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1088 function is_domain($str)
1090   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1094 function is_id($id)
1096   if ($id == ""){
1097     return (FALSE);
1098   }
1100   return preg_match ("/^[0-9]+$/", $id);
1104 function is_path($path)
1106   if ($path == ""){
1107     return (TRUE);
1108   }
1109   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1110     return (FALSE);
1111   }
1113   return preg_match ("/\/.+$/", $path);
1117 function is_email($address, $template= FALSE)
1119   if ($address == ""){
1120     return (TRUE);
1121   }
1122   if ($template){
1123     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1124         $address);
1125   } else {
1126     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1127         $address);
1128   }
1132 function print_red()
1134   /* Check number of arguments */
1135   if (func_num_args() < 1){
1136     return;
1137   }
1139   /* Get arguments, save string */
1140   $array = func_get_args();
1141   $string= $array[0];
1143   /* Step through arguments */
1144   for ($i= 1; $i<count($array); $i++){
1145     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1146   }
1148   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1149     $_SESSION['errorsAlreadyPosted'] = array(); 
1150   }
1152   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1153      the other case... */
1155   if (isset($_SESSION['DEBUGLEVEL'])){
1157     if($_SESSION['LastError'] == $string){
1158     
1159       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1160         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1161       }
1162       $_SESSION['errorsAlreadyPosted'][$string]++;
1164     }else{
1165       if($string != NULL){
1166         if (preg_match("/"._("LDAP error:")."/", $string)){
1167           $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.");
1168           $img= "images/error.png";
1169         } else {
1170           if (!preg_match('/[.!?]$/', $string)){
1171             $string.= ".";
1172           }
1173           $string= preg_replace('/<br>/', ' ', $string);
1174           $img= "images/warning.png";
1175           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1176         }
1177       
1178         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1181   if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1183             $_SESSION['errors'].= "
1184               <iframe id='e_layer3'
1185                 style=\"  position:absolute;
1186                           width:100%;
1187                           height:100%;
1188                           top:0px;
1189                           left:0px;
1190                           border:none;
1191                           display:block;
1192                           allowtransparency='true';
1193                           background-color: #FFFFFF;
1194                           filter:chroma(color=#FFFFFF);
1195                           z-index:0; \">
1196               </iframe>
1197               <div  id='e_layer2'
1198                 style=\"
1199                   position: absolute;
1200                   left: 0px;
1201                   top: 0px;
1202                   right:0px;
1203                   bottom:0px;
1204                   z-index:0;
1205                   width:100%;
1206                   height:100%;
1207                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1208               </div>";
1209               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1210           }else{
1212             $_SESSION['errors'].= "
1213               <div  id='e_layer2'
1214                 style=\"
1215                   position: absolute;
1216                   left: 0px;
1217                   top: 0px;
1218                   right:0px;
1219                   bottom:0px;
1220                   z-index:0;
1221                   background-image: url(images/opacity_black.png);\">
1222                </div>";
1223               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1224           }
1226           $_SESSION['errors'].= "
1227           <div style='left:20%;right:20%;top:30%;".
1228             "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1229             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1230             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1231             get_template_path($img)."'></td>".
1232             "<td style='width:100%'><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1233             (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1234             " style='width:80px' onClick='".$hide."'>".
1235             _("OK")."</button></td></tr></table></div>";
1236         }
1238       }else{
1239         return;
1240       }
1241       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1243     }
1245   } else {
1246     echo "Error: $string\n";
1247   }
1248   $_SESSION['LastError'] = $string; 
1252 function gen_locked_message($user, $dn)
1254   global $plug, $config;
1256   $_SESSION['dn']= $dn;
1257   $ldap= $config->get_ldap_link();
1258   $ldap->cat ($user, array('uid', 'cn'));
1259   $attrs= $ldap->fetch();
1261   /* Stop if we have no user here... */
1262   if (count($attrs)){
1263     $uid= $attrs["uid"][0];
1264     $cn= $attrs["cn"][0];
1265   } else {
1266     $uid= $attrs["uid"][0];
1267     $cn= $attrs["cn"][0];
1268   }
1269   
1270   $remove= false;
1272   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1273     $_SESSION['LOCK_VARS_USED']  =array();
1274     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1276       if(empty($name)) continue;
1277       foreach($_POST as $Pname => $Pvalue){
1278         if(preg_match($name,$Pname)){
1279           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1280         }
1281       }
1283       foreach($_GET as $Pname => $Pvalue){
1284         if(preg_match($name,$Pname)){
1285           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1286         }
1287       }
1288     }
1289     $_SESSION['LOCK_VARS_TO_USE'] =array();
1290   }
1292   /* Prepare and show template */
1293   $smarty= get_smarty();
1294   $smarty->assign ("dn", $dn);
1295   if ($remove){
1296     $smarty->assign ("action", _("Continue anyway"));
1297   } else {
1298     $smarty->assign ("action", _("Edit anyway"));
1299   }
1300   $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>"));
1302   return ($smarty->fetch (get_template_path('islocked.tpl')));
1306 function to_string ($value)
1308   /* If this is an array, generate a text blob */
1309   if (is_array($value)){
1310     $ret= "";
1311     foreach ($value as $line){
1312       $ret.= $line."<br>\n";
1313     }
1314     return ($ret);
1315   } else {
1316     return ($value);
1317   }
1321 function get_printer_list($cups_server)
1323   global $config;
1325   $res= array();
1327   /* Use CUPS, if we've access to it */
1328   if (function_exists('cups_get_dest_list')){
1329     $dest_list= cups_get_dest_list ($cups_server);
1331     foreach ($dest_list as $prt){
1332       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1334       foreach ($attr as $prt_info){
1335         if ($prt_info->name == "printer-info"){
1336           $info= $prt_info->value;
1337           break;
1338         }
1339       }
1340       $res[$prt->name]= "$info [$prt->name]";
1341     }
1343     /* CUPS is not available, try lpstat as a replacement */
1344   } else {
1345     $ar = false;
1346     exec("lpstat -p", $ar);
1347     foreach($ar as $val){
1348       @list($dummy, $printer, $rest)= split(' ', $val, 3);
1349       if (preg_match('/^[^@]+$/', $printer)){
1350         $res[$printer]= "$printer";
1351       }
1352     }
1353   }
1355   /* Merge in printers from LDAP */
1356   $ldap= $config->get_ldap_link();
1357   $ldap->cd ($config->current['BASE']);
1358   $ui= get_userinfo();
1359   if (isset($config->current['STRICT_UNITS']) && preg_match('/TRUE/i', $config->current['STRICT_UNITS']) && $ui->gosaUnitTag != ""){   
1360     $ldap->search('((objectClass=gotoPrinter)(gosaUnitTag='.$ui->gosaUnitTag.'))', array('cn'));
1361   } else {
1362     $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1363   }
1364   while($attrs = $ldap->fetch()){
1365     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1366   }
1368   return $res;
1372 function sess_del ($var)
1374   /* New style */
1375   unset ($_SESSION[$var]);
1377   /* ... work around, since the first one
1378      doesn't seem to work all the time */
1379   session_unregister ($var);
1383 function show_errors($message)
1385   $complete= "";
1387   /* Assemble the message array to a plain string */
1388   foreach ($message as $error){
1389     if ($complete == ""){
1390       $complete= $error;
1391     } else {
1392       $complete= "$error<br>$complete";
1393     }
1394   }
1396   /* Fill ERROR variable with nice error dialog */
1397   print_red($complete);
1401 function show_ldap_error($message, $addon= "")
1403   if (!preg_match("/Success/i", $message)){
1404     if ($addon == ""){
1405       print_red (_("LDAP error: $message"));
1406     } else {
1407       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1408     }
1409     return TRUE;
1410   } else {
1411     return FALSE;
1412   }
1416 function rewrite($s)
1418   global $REWRITE;
1420   foreach ($REWRITE as $key => $val){
1421     $s= preg_replace("/$key/", "$val", $s);
1422   }
1424   return ($s);
1428 function dn2base($dn)
1430   global $config;
1432   if (get_people_ou() != ""){
1433     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1434   }
1435   if (get_groups_ou() != ""){
1436     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1437   }
1438   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1440   return ($base);
1445 function check_command($cmdline)
1447   $cmd= preg_replace("/ .*$/", "", $cmdline);
1449   /* Check if command exists in filesystem */
1450   if (!file_exists($cmd)){
1451     return (FALSE);
1452   }
1454   /* Check if command is executable */
1455   if (!is_executable($cmd)){
1456     return (FALSE);
1457   }
1459   return (TRUE);
1463 function print_header($image, $headline, $info= "")
1465   $display= "<div class=\"plugtop\">\n";
1466   $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";
1467   $display.= "</div>\n";
1469   if ($info != ""){
1470     $display.= "<div class=\"pluginfo\">\n";
1471     $display.= "$info";
1472     $display.= "</div>\n";
1473   } else {
1474     $display.= "<div style=\"height:5px;\">\n";
1475     $display.= "&nbsp;";
1476     $display.= "</div>\n";
1477   }
1478 #  if (isset($_SESSION['errors'])){
1479 #    $display.= $_SESSION['errors'];
1480 #  }
1482   return ($display);
1486 function register_global($name, $object)
1488   $_SESSION[$name]= $object;
1492 function is_global($name)
1494   return isset($_SESSION[$name]);
1498 function get_global($name)
1500   return $_SESSION[$name];
1504 function range_selector($dcnt,$start,$range=25,$post_var=false)
1507   /* Entries shown left and right from the selected entry */
1508   $max_entries= 10;
1510   /* Initialize and take care that max_entries is even */
1511   $output="";
1512   if ($max_entries & 1){
1513     $max_entries++;
1514   }
1516   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1517     $range= $_POST[$post_var];
1518   }
1520   /* Prevent output to start or end out of range */
1521   if ($start < 0 ){
1522     $start= 0 ;
1523   }
1524   if ($start >= $dcnt){
1525     $start= $range * (int)(($dcnt / $range) + 0.5);
1526   }
1528   $numpages= (($dcnt / $range));
1529   if(((int)($numpages))!=($numpages)){
1530     $numpages = (int)$numpages + 1;
1531   }
1532   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1533     return ("");
1534   }
1535   $ppage= (int)(($start / $range) + 0.5);
1538   /* Align selected page to +/- max_entries/2 */
1539   $begin= $ppage - $max_entries/2;
1540   $end= $ppage + $max_entries/2;
1542   /* Adjust begin/end, so that the selected value is somewhere in
1543      the middle and the size is max_entries if possible */
1544   if ($begin < 0){
1545     $end-= $begin + 1;
1546     $begin= 0;
1547   }
1548   if ($end > $numpages) {
1549     $end= $numpages;
1550   }
1551   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1552     $begin= $end - $max_entries;
1553   }
1555   if($post_var){
1556     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1557       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1558   }else{
1559     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1560   }
1562   /* Draw decrement */
1563   if ($start > 0 ) {
1564     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1565       (($start-$range))."\">".
1566       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1567   }
1569   /* Draw pages */
1570   for ($i= $begin; $i < $end; $i++) {
1571     if ($ppage == $i){
1572       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1573         validate($_GET['plug'])."&amp;start=".
1574         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1575     } else {
1576       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1577         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1578     }
1579   }
1581   /* Draw increment */
1582   if($start < ($dcnt-$range)) {
1583     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1584       (($start+($range)))."\">".
1585       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1586   }
1588   if(($post_var)&&($numpages)){
1589     $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()'>";
1590     foreach(array(20,50,100,200,"all") as $num){
1591       if($num == "all"){
1592         $var = 10000;
1593       }else{
1594         $var = $num;
1595       }
1596       if($var == $range){
1597         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1598       }else{  
1599         $output.="\n<option value='".$var."'>".$num."</option>";
1600       }
1601     }
1602     $output.=  "</select></td></tr></table></div>";
1603   }else{
1604     $output.= "</div>";
1605   }
1607   return($output);
1611 function apply_filter()
1613   $apply= "";
1615   $apply= ''.
1616     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1617     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1619   return ($apply);
1623 function back_to_main()
1625   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1626     _("Back").'"></p><input type="hidden" name="ignore">';
1628   return ($string);
1632 function normalize_netmask($netmask)
1634   /* Check for notation of netmask */
1635   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1636     $num= (int)($netmask);
1637     $netmask= "";
1639     for ($byte= 0; $byte<4; $byte++){
1640       $result=0;
1642       for ($i= 7; $i>=0; $i--){
1643         if ($num-- > 0){
1644           $result+= pow(2,$i);
1645         }
1646       }
1648       $netmask.= $result.".";
1649     }
1651     return (preg_replace('/\.$/', '', $netmask));
1652   }
1654   return ($netmask);
1658 function netmask_to_bits($netmask)
1660   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1661   $res= 0;
1663   for ($n= 0; $n<4; $n++){
1664     $start= 255;
1665     $name= "nm$n";
1667     for ($i= 0; $i<8; $i++){
1668       if ($start == (int)($$name)){
1669         $res+= 8 - $i;
1670         break;
1671       }
1672       $start-= pow(2,$i);
1673     }
1674   }
1676   return ($res);
1680 function recurse($rule, $variables)
1682   $result= array();
1684   if (!count($variables)){
1685     return array($rule);
1686   }
1688   reset($variables);
1689   $key= key($variables);
1690   $val= current($variables);
1691   unset ($variables[$key]);
1693   foreach($val as $possibility){
1694     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1695     $result= array_merge($result, recurse($nrule, $variables));
1696   }
1698   return ($result);
1702 function expand_id($rule, $attributes)
1704   /* Check for id rule */
1705   if(preg_match('/^id(:|#)\d+$/',$rule)){
1706     return (array("\{$rule}"));
1707   }
1709   /* Check for clean attribute */
1710   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1711     $rule= preg_replace('/^%/', '', $rule);
1712     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1713     return (array($val));
1714   }
1716   /* Check for attribute with parameters */
1717   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1718     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1719     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1720     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1721     $start= preg_replace ('/-.*$/', '', $param);
1722     $stop = preg_replace ('/^[^-]+-/', '', $param);
1724     /* Assemble results */
1725     $result= array();
1726     for ($i= $start; $i<= $stop; $i++){
1727       $result[]= substr($val, 0, $i);
1728     }
1729     return ($result);
1730   }
1732   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1733   return (array($rule));
1737 function gen_uids($rule, $attributes)
1739   global $config;
1741   /* Search for keys and fill the variables array with all 
1742      possible values for that key. */
1743   $part= "";
1744   $trigger= false;
1745   $stripped= "";
1746   $variables= array();
1748   for ($pos= 0; $pos < strlen($rule); $pos++){
1750     if ($rule[$pos] == "{" ){
1751       $trigger= true;
1752       $part= "";
1753       continue;
1754     }
1756     if ($rule[$pos] == "}" ){
1757       $variables[$pos]= expand_id($part, $attributes);
1758       $stripped.= "{".$pos."}";
1759       $trigger= false;
1760       continue;
1761     }
1763     if ($trigger){
1764       $part.= $rule[$pos];
1765     } else {
1766       $stripped.= $rule[$pos];
1767     }
1768   }
1770   /* Recurse through all possible combinations */
1771   $proposed= recurse($stripped, $variables);
1773   /* Get list of used ID's */
1774   $used= array();
1775   $ldap= $config->get_ldap_link();
1776   $ldap->cd($config->current['BASE']);
1777   $ldap->search('(uid=*)');
1779   while($attrs= $ldap->fetch()){
1780     $used[]= $attrs['uid'][0];
1781   }
1783   /* Remove used uids and watch out for id tags */
1784   $ret= array();
1785   foreach($proposed as $uid){
1787     /* Check for id tag and modify uid if needed */
1788     if(preg_match('/\{id:\d+}/',$uid)){
1789       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1791       for ($i= 0; $i < pow(10,$size); $i++){
1792         $number= sprintf("%0".$size."d", $i);
1793         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1794         if (!in_array($res, $used)){
1795           $uid= $res;
1796           break;
1797         }
1798       }
1799     }
1801   if(preg_match('/\{id#\d+}/',$uid)){
1802     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1804     while (true){
1805       mt_srand((double) microtime()*1000000);
1806       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1807       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1808       if (!in_array($res, $used)){
1809         $uid= $res;
1810         break;
1811       }
1812     }
1813   }
1815 /* Don't assign used ones */
1816 if (!in_array($uid, $used)){
1817   $ret[]= $uid;
1821 return(array_unique($ret));
1825 function array_search_r($needle, $key, $haystack){
1827   foreach($haystack as $index => $value){
1828     $match= 0;
1830     if (is_array($value)){
1831       $match= array_search_r($needle, $key, $value);
1832     }
1834     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1835       $match=1;
1836     }
1838     if ($match){
1839       return 1;
1840     }
1841   }
1843   return 0;
1844
1847 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1848    Need to convert... */
1849 function to_byte($value) {
1850   $value= strtolower(trim($value));
1852   if(!is_numeric(substr($value, -1))) {
1854     switch(substr($value, -1)) {
1855       case 'g':
1856         $mult= 1073741824;
1857         break;
1858       case 'm':
1859         $mult= 1048576;
1860         break;
1861       case 'k':
1862         $mult= 1024;
1863         break;
1864     }
1866     return ($mult * (int)substr($value, 0, -1));
1867   } else {
1868     return $value;
1869   }
1873 function in_array_ics($value, $items)
1875   if (!is_array($items)){
1876     return (FALSE);
1877   }
1879   foreach ($items as $item){
1880     if (strtolower($item) == strtolower($value)) {
1881       return (TRUE);
1882     }
1883   }
1885   return (FALSE);
1886
1889 function generate_alphabet($count= 10)
1891   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1892   $alphabet= "";
1893   $c= 0;
1895   /* Fill cells with charaters */
1896   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1897     if ($c == 0){
1898       $alphabet.= "<tr>";
1899     }
1901     $ch = mb_substr($characters, $i, 1, "UTF8");
1902     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1903       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1905     if ($c++ == $count){
1906       $alphabet.= "</tr>";
1907       $c= 0;
1908     }
1909   }
1911   /* Fill remaining cells */
1912   while ($c++ <= $count){
1913     $alphabet.= "<td>&nbsp;</td>";
1914   }
1916   return ($alphabet);
1920 function validate($string)
1922   return (strip_tags(preg_replace('/\0/', '', $string)));
1925 function get_gosa_version()
1927   global $svn_revision, $svn_path;
1929   /* Extract informations */
1930   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1932   /* Release or development? */
1933   if (preg_match('%/gosa/trunk/%', $svn_path)){
1934     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1935   } else {
1936     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1937     return (_("GOsa $release"));
1938   }
1942 function rmdirRecursive($path, $followLinks=false) {
1943   $dir= opendir($path);
1944   while($entry= readdir($dir)) {
1945     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1946       unlink($path."/".$entry);
1947     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1948       rmdirRecursive($path."/".$entry);
1949     }
1950   }
1951   closedir($dir);
1952   return rmdir($path);
1955 function scan_directory($path,$sort_desc=false)
1957   $ret = false;
1959   /* is this a dir ? */
1960   if(is_dir($path)) {
1962     /* is this path a readable one */
1963     if(is_readable($path)){
1965       /* Get contents and write it into an array */   
1966       $ret = array();    
1968       $dir = opendir($path);
1970       /* Is this a correct result ?*/
1971       if($dir){
1972         while($fp = readdir($dir))
1973           $ret[]= $fp;
1974       }
1975     }
1976   }
1977   /* Sort array ascending , like scandir */
1978   sort($ret);
1980   /* Sort descending if parameter is sort_desc is set */
1981   if($sort_desc) {
1982     $ret = array_reverse($ret);
1983   }
1985   return($ret);
1988 function clean_smarty_compile_dir($directory)
1990   global $svn_revision;
1992   if(is_dir($directory) && is_readable($directory)) {
1993     // Set revision filename to REVISION
1994     $revision_file= $directory."/REVISION";
1996     /* Is there a stamp containing the current revision? */
1997     if(!file_exists($revision_file)) {
1998       // create revision file
1999       create_revision($revision_file, $svn_revision);
2000     } else {
2001 # check for "$config->...['CONFIG']/revision" and the
2002 # contents should match the revision number
2003       if(!compare_revision($revision_file, $svn_revision)){
2004         // If revision differs, clean compile directory
2005         foreach(scan_directory($directory) as $file) {
2006           if(($file==".")||($file=="..")) continue;
2007           if( is_file($directory."/".$file) &&
2008               is_writable($directory."/".$file)) {
2009             // delete file
2010             if(!unlink($directory."/".$file)) {
2011               print_red("File ".$directory."/".$file." could not be deleted.");
2012               // This should never be reached
2013             }
2014           } elseif(is_dir($directory."/".$file) &&
2015               is_writable($directory."/".$file)) {
2016             // Just recursively delete it
2017             rmdirRecursive($directory."/".$file);
2018           }
2019         }
2020         // We should now create a fresh revision file
2021         clean_smarty_compile_dir($directory);
2022       } else {
2023         // Revision matches, nothing to do
2024       }
2025     }
2026   } else {
2027     // Smarty compile dir is not accessible
2028     // (Smarty will warn about this)
2029   }
2032 function create_revision($revision_file, $revision)
2034   $result= false;
2036   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2037     if($fh= fopen($revision_file, "w")) {
2038       if(fwrite($fh, $revision)) {
2039         $result= true;
2040       }
2041     }
2042     fclose($fh);
2043   } else {
2044     print_red("Can not write to revision file");
2045   }
2047   return $result;
2050 function compare_revision($revision_file, $revision)
2052   // false means revision differs
2053   $result= false;
2055   if(file_exists($revision_file) && is_readable($revision_file)) {
2056     // Open file
2057     if($fh= fopen($revision_file, "r")) {
2058       // Compare File contents with current revision
2059       if($revision == fread($fh, filesize($revision_file))) {
2060         $result= true;
2061       }
2062     } else {
2063       print_red("Can not open revision file");
2064     }
2065     // Close file
2066     fclose($fh);
2067   }
2069   return $result;
2072 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2074   $str = ""; // Our return value will be saved in this var
2076   $color  = dechex($percentage+150);
2077   $color2 = dechex(150 - $percentage);
2078   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2080   $progress = (int)(($percentage /100)*$width);
2082   /* If theres a better solution for this, use it... */
2083   $str = "\n   <div style=\" width:".($width)."px; ";
2084   $str.= "\n       height:".($height)."px; ";
2085   $str.= "\n       background-color:#000000; ";
2086   $str.= "\n       padding:1px;\" > ";
2088   $str.= "\n     <div style=\" width:".($width)."px; ";
2089   $str.= "\n         background-color:#$bgcolor; ";
2090   $str.= "\n         height:".($height)."px;\" > ";
2093   if(($height >10)&&($showvalue)){
2094     $str.= "\n   <font style=\"font-size:".($height-2)."px; ";
2095     $str.= "\n     color:#FF0000; align:middle; ";
2096     $str.= "\n     padding-left:".((int)(($width*0.4)))."px; \"> ";
2097     $str.= "\n     <b>".$percentage."%</b> ";
2098     $str.= "\n   </font> ";
2099   }
2101   $str.= "\n       <div style=\" width:".$progress."px; ";
2102   $str.= "\n         height:".$height."px; ";
2103   $str.= "\n         background-color:#".$color2.$color2.$color."; \" >";
2104   $str.= "\n       </div>";
2105   $str.= "\n     </div>";
2106   $str.= "\n   </div>";
2108   return($str);
2112 function array_key_ics($ikey, $items)
2114   /* Gather keys, make them lowercase */
2115   $tmp= array();
2116   foreach ($items as $key => $value){
2117     $tmp[strtolower($key)]= $key;
2118   }
2120   if (isset($tmp[strtolower($ikey)])){
2121     return($tmp[strtolower($ikey)]);
2122   }
2124   return ("");
2128 function search_config($arr, $name, $return)
2130   if (is_array($arr)){
2131     foreach ($arr as $a){
2132       if (isset($a['CLASS']) &&
2133           strtolower($a['CLASS']) == strtolower($name)){
2135         if (isset($a[$return])){
2136           return ($a[$return]);
2137         } else {
2138           return ("");
2139         }
2140       } else {
2141         $res= search_config ($a, $name, $return);
2142         if ($res != ""){
2143           return $res;
2144         }
2145       }
2146     }
2147   }
2148   return ("");
2152 function array_differs($src, $dst)
2154   /* If the count is differing, the arrays differ */
2155   if (count ($src) != count ($dst)){
2156     return (TRUE);
2157   }
2159   /* So the count is the same - lets check the contents */
2160   $differs= FALSE;
2161   foreach($src as $value){
2162     if (!in_array($value, $dst)){
2163       $differs= TRUE;
2164     }
2165   }
2167   return ($differs);
2171 function saveFilter($a_filter, $values)
2173   if (isset($_POST['regexit'])){
2174     $a_filter["regex"]= $_POST['regexit'];
2176     foreach($values as $type){
2177       if (isset($_POST[$type])) {
2178         $a_filter[$type]= "checked";
2179       } else {
2180         $a_filter[$type]= "";
2181       }
2182     }
2183   }
2185   /* React on alphabet links if needed */
2186   if (isset($_GET['search'])){
2187     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2188     if ($s == "**"){
2189       $s= "*";
2190     }
2191     $a_filter['regex']= $s;
2192   }
2194   return ($a_filter);
2198 /* Escape all preg_* relevant characters */
2199 function normalizePreg($input)
2201   return (addcslashes($input, '[]()|/.*+-'));
2205 /* Escape all LDAP filter relevant characters */
2206 function normalizeLdap($input)
2208   return (addcslashes($input, '()|'));
2212 /* Resturns the difference between to microtime() results in float  */
2213 function get_MicroTimeDiff($start , $stop)
2215   $a = split("\ ",$start);
2216   $b = split("\ ",$stop);
2218   $secs = $b[1] - $a[1];
2219   $msecs= $b[0] - $a[0]; 
2221   $ret = (float) ($secs+ $msecs);
2222   return($ret);
2226 /* Check if the given department name is valid */
2227 function is_department_name_reserved($name,$base)
2229   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2230                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2231                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2232   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2234   /* Check if name is one of the reserved names */
2235   if(in_array_ics($name,$reservedName)) {
2236     return(true);
2237   }
2239   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2240   foreach($follwedNames as $key => $names){
2241     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2242       return(true);
2243     }
2244   }
2245   return(false);
2249 function is_php4()
2251   if (isset($_SESSION['PHP4COMPATIBLE'])){
2252     return true;
2253   }
2254   return (preg_match('/^4/', phpversion()));
2258 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2260   /* Initialize variables */
2261   $ret  = array("count" => 0);  // Set count to 0
2262   $next = true;                 // if false, then skip next loops and return
2263   $cnt  = 0;                    // Current number of loops
2264   $max  = 100;                  // Just for security, prevent looops
2265   $ldap = NULL;                 // To check if created result a valid
2266   $keep = "";                   // save last failed parse string
2268   /* Check each parsed dn in ldap ? */
2269   if($config!=NULL && $verify_in_ldap){
2270     $ldap = $config->get_ldap_link();
2271   }
2273   /* Lets start */
2274   $called = false;
2275   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2277     $cnt ++;
2278     if(!preg_match("/,/",$dn)){
2279       $next = false;
2280     }
2281     $object = preg_replace("/[,].*$/","",$dn);
2282     $dn     = preg_replace("/^[^,]+,/","",$dn);
2284     $called = true;
2286     /* Check if current dn is valid */
2287     if($ldap!=NULL){
2288       $ldap->cd($dn);
2289       $ldap->cat($dn,array("dn"));
2290       if($ldap->count()){
2291         $ret[]  = $keep.$object;
2292         $keep   = "";
2293       }else{
2294         $keep  .= $object.",";
2295       }
2296     }else{
2297       $ret[]  = $keep.$object;
2298       $keep   = "";
2299     }
2300   }
2302   /* No dn was posted */
2303   if($cnt == 0 && !empty($dn)){
2304     $ret[] = $dn;
2305   }
2307   /* Append the rest */
2308   $test = $keep.$dn;
2309   if($called && !empty($test)){
2310     $ret[] = $keep.$dn;
2311   }
2312   $ret['count'] = count($ret) - 1;
2314   return($ret);
2318 function get_base_from_hook($dn, $attrib)
2320   global $config;
2322   if (isset($config->current['BASE_HOOK'])){
2323     
2324     /* Call hook script - if present */
2325     $command= $config->current['BASE_HOOK'];
2327     if ($command != ""){
2328       $command.= " '".@LDAP::fix($dn)."' $attrib";
2329       if (check_command($command)){
2330         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2331         exec($command, $output);
2332         if (preg_match("/^[0-9]+$/", $output[0])){
2333           return ($output[0]);
2334         } else {
2335           print_red(_("Warning - base_hook is not available. Using default base."));
2336           return ($config->current['UIDBASE']);
2337         }
2338       } else {
2339         print_red(_("Warning - base_hook is not available. Using default base."));
2340         return ($config->current['UIDBASE']);
2341       }
2343     } else {
2345       print_red(_("Warning - no base_hook defined. Using default base."));
2346       return ($config->current['UIDBASE']);
2348     }
2349   }
2352 /* Schema validation functions */
2354   function check_schema_version($class, $version)
2355   {
2356     return preg_match("/\(v$version\)/", $class['DESC']);
2357   }
2359   
2361   function check_schema($cfg,$rfc2307bis = FALSE)
2362   {
2364     $messages= array();
2366     /* Get objectclasses */
2367     $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2368     $objectclasses = $ldap->get_objectclasses();
2369     if(count($objectclasses) == 0){
2370       print_red(_("Can't get schema information from server. No schema check possible!"));
2371     }
2373     /* This is the default block used for each entry.
2374      *  to avoid unset indexes.
2375      */
2376     $def_check = array("REQUIRED_VERSION" => "0",
2377                        "SCHEMA_FILES"     => array(),
2378                        "CLASSES_REQUIRED" => array(),
2379                        "STATUS"           => FALSE,
2380                        "IS_MUST_HAVE"     => FALSE,
2381                        "MSG"              => "",
2382                        "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2384  /* The gosa base schema */
2385     $checks['gosaObject'] = $def_check;
2386     $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2387     $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2388     $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2389     $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2391     /* GOsa Account class */
2392     $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2393     $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2394     $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2395     $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2396     $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2398     /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2399     $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2400     $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2401     $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2402     $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2403     $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2405   /* Some other checks */
2406     foreach(array(
2407           "gosaCacheEntry"        => array("version" => "2.4"),
2408           "gosaDepartment"        => array("version" => "2.4"),
2409           "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2410           "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2411           "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2412           "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2413           "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2414           "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2415           "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2416           "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2417           "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2418           "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2419           "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2420           "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2421           "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2422           "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2423           "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2424           "goLdapServer"          => array("version" => "2.4"),
2425           "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2426           "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2427           "goKrbServer"           => array("version" => "2.4"),
2428           "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2429           ) as $name => $values){
2431       $checks[$name] = $def_check;
2432       if(isset($values['version'])){
2433         $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2434       }
2435       if(isset($values['file'])){
2436         $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2437       }
2438       $checks[$name]["CLASSES_REQUIRED"] = array($name);
2439     }
2440    foreach($checks as $name => $value){
2441       foreach($value['CLASSES_REQUIRED'] as $class){
2443         if(!isset($objectclasses[$name])){
2444           $checks[$name]['STATUS'] = FALSE;
2445           if($value['IS_MUST_HAVE']){
2446             $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2447           }else{
2448             $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2449           }
2450         }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2451           $checks[$name]['STATUS'] = FALSE;
2453           if($value['IS_MUST_HAVE']){
2454             $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2455           }else{
2456             $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2457           }
2458         }else{
2459           $checks[$name]['STATUS'] = TRUE;
2460           $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2461         }
2462       }
2463     }
2465     $tmp = $objectclasses;
2468     /* The gosa base schema */
2469     $checks['posixGroup'] = $def_check;
2470     $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2471     $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2472     $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2473     $checks['posixGroup']['STATUS']           = TRUE;
2474     $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2475     $checks['posixGroup']['MSG']              = "";
2476     $checks['posixGroup']['INFO']             = "";
2478     /* Depending on selected rfc2307bis mode, we need different schema configurations */
2479     if(isset($tmp['posixGroup'])){
2481       if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2482         $checks['posixGroup']['STATUS']           = FALSE;
2483         $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2484         $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2485       }
2486       if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2487         $checks['posixGroup']['STATUS']           = FALSE;
2488         $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2489         $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2490       }
2491     }
2493     return($checks);
2494   }
2499 function mac2company($mac)
2501   $vendor= "";
2503   /* Generate a normailzed mac... */
2504   $mac= substr(preg_replace('/[:-]/', '', $mac), 0, 6);
2506   /* Check for existance of the oui file */
2507   if (!is_readable(CONFIG_DIR."/oui.txt")){
2508     return ("");
2509   }
2511   /* Open file and look for mac addresses... */
2512   $handle = @fopen(CONFIG_DIR."/oui.txt", "r");
2513   if ($handle) {
2514     while (!feof($handle)) {
2515       $line = fgets($handle, 4096);
2517       if (preg_match("/^$mac/i", $line)){
2518         $vendor= substr($line, 32);
2519       }
2520     }
2521     fclose($handle);
2522   }
2524   return ($vendor);
2528 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2530   $tmp = array(
2531         "de_DE" => "German",
2532         "fr_FR" => "French",
2533         "it_IT" => "Italian",
2534         "es_ES" => "Spanish",
2535         "en_US" => "English",
2536         "nl_NL" => "Dutch",
2537         "pl_PL" => "Polish",
2538         "sv_SE" => "Swedish",
2539         "zh_CN" => "Chinese",
2540         "ru_RU" => "Russian");
2541   
2542   $tmp2= array(
2543         "de_DE" => _("German"),
2544         "fr_FR" => _("French"),
2545         "it_IT" => _("Italian"),
2546         "es_ES" => _("Spanish"),
2547         "en_US" => _("English"),
2548         "nl_NL" => _("Dutch"),
2549         "pl_PL" => _("Polish"),
2550         "sv_SE" => _("Swedish"),
2551         "zh_CN" => _("Chinese"),
2552         "ru_RU" => _("Russian"));
2554   $ret = array();
2555   if($languages_in_own_language){
2557     $old_lang = setlocale(LC_ALL, 0);
2558     foreach($tmp as $key => $name){
2559       $lang = $key.".UTF-8";
2560       setlocale(LC_ALL, $lang);
2561       if($strip_region_tag){
2562         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2563       }else{
2564         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2565       }
2566     }
2567     setlocale(LC_ALL, $old_lang);
2568   }else{
2569     foreach($tmp as $key => $name){
2570       if($strip_region_tag){
2571         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2572       }else{
2573         $ret[$key] = _($name);
2574       }
2575     }
2576   }
2577   return($ret);
2581 /* Check if $ip1 and $ip2 represents a valid IP range 
2582  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2583  */
2584 function is_ip_range($ip1,$ip2)
2586   if(!is_ip($ip1) || !is_ip($ip2)){
2587     return(FALSE);
2588   }else{
2589     $ar1 = split("\.",$ip1);
2590     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2592     $ar2 = split("\.",$ip2);
2593     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2594     return($var1 < $var2);
2595   }
2599 /* Check if the specified IP address $address is inside the given network */
2600 function is_in_network($network, $netmask, $address)
2602   $nw= split('\.', $network);
2603   $nm= split('\.', $netmask);
2604   $ad= split('\.', $address);
2606   /* Generate inverted netmask */
2607   for ($i= 0; $i<4; $i++){
2608     $ni[$i]= 255-$nm[$i];
2609     $la[$i]= $nw[$i] | $ni[$i];
2610   }
2612   /* Transform to integer */
2613   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2614   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2615   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2617   return ($first < $curr&& $last > $curr);
2621 /* Add a given objectClass to an attrs entry */
2622 function add_objectClass($classes, &$attrs)
2624         if (is_array($classes)){
2625                 $list= $classes;
2626         } else {
2627                 $list= array($classes);
2628         }
2630         foreach ($list as $class){
2631                 $attrs['objectClass'][]= $class;
2632         }
2636 /* Removes a given objectClass from the attrs entry */
2637 function remove_objectClass($classes, &$attrs)
2639         if (isset($attrs['objectClass'])){
2640                 /* Array? */
2641                 if (is_array($classes)){
2642                         $list= $classes;
2643                 } else {
2644                         $list= array($classes);
2645                 }
2647                 $tmp= array();
2648                 foreach ($attrs['objectClass'] as $oc) {
2649                         foreach ($list as $class){
2650                                 if ($oc != $class){
2651                                         $tmp[]= $oc;
2652                                 }
2653                         }
2654                 }
2655                 $attrs['objectClass']= $tmp;
2656         }
2660 function cred_encrypt($input, $password) {
2662   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2663   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2665   return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2669 function cred_decrypt($input,$password) {
2670   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2671   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2673   return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2677 /* Returns contents of the given POST variable and check magic quotes settings */
2678 function get_post($name)
2680   if(!isset($_POST[$name])){
2681     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2682     return(FALSE);
2683   }
2684   if(get_magic_quotes_gpc()){
2685     return(stripcslashes($_POST[$name]));
2686   }else{
2687     return($_POST[$name]);
2688   }
2691 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2692 ?>