Code

git-svn-id: https://oss.gonicus.de/repositories/gosa/branches/2.5-plugins@13585 594d3...
[gosa.git] / vhost-apache2 / 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: https://oss.gonicus.de/repositories/gosa/branches/2.5/include/functions.inc $';
50 $svn_revision = '$Revision: 12286 $';
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 ("functions_apache.inc");
65 require_once ("accept-to-gettext.inc");
66 require_once ("class_MultiSelectWindow.inc");
68 /* Define constants for debugging */
69 define ("DEBUG_TRACE",   1);
70 define ("DEBUG_LDAP",    2);
71 define ("DEBUG_MYSQL",   4);
72 define ("DEBUG_SHELL",   8);
73 define ("DEBUG_POST",   16);
74 define ("DEBUG_SESSION",32);
75 define ("DEBUG_CONFIG", 64);
77 /* Rewrite german 'umlauts' and spanish 'accents'
78    to get better results */
79 $REWRITE= array( "ä" => "ae",
80     "ö" => "oe",
81     "ü" => "ue",
82     "Ä" => "Ae",
83     "Ö" => "Oe",
84     "Ü" => "Ue",
85     "ß" => "ss",
86     "á" => "a",
87     "é" => "e",
88     "í" => "i",
89     "ó" => "o",
90     "ú" => "u",
91     "Á" => "A",
92     "É" => "E",
93     "Í" => "I",
94     "Ó" => "O",
95     "Ú" => "U",
96     "ñ" => "ny",
97     "Ñ" => "Ny" );
100 /* Function to include all class_ files starting at a
101    given directory base */
102 function get_dir_list($folder= ".")
104   $currdir=getcwd();
105   if ($folder){
106     chdir("$folder");
107   }
109   $dh = opendir(".");
110   while(false !== ($file = readdir($dh))){
112     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
113     // Skip all files and dirs in  "./.svn/" we don't need any information from them
114     // Skip all Template, so they won't be checked twice in the following preg_matches   
115     // Skip . / ..
117     // Result  : from 1023 ms to 490 ms   i think thats great...
118     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
119       continue;
122     /* Recurse through all "common" directories */
123     if(is_dir($file) &&$file!="CVS"){
124       get_dir_list($file);
125       continue;
126     }
128     /* Include existing class_ files */
129     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
130       require_once($file);
131     }
132   }
134   closedir($dh);
135   chdir($currdir);
139 /* Create seed with microseconds */
140 function make_seed() {
141   list($usec, $sec) = explode(' ', microtime());
142   return (float) $sec + ((float) $usec * 100000);
146 /* Debug level action */
147 function DEBUG($level, $line, $function, $file, $data, $info="")
149   if ($_SESSION['DEBUGLEVEL'] & $level){
150     $output= "DEBUG[$level] ";
151     if ($function != ""){
152       $output.= "($file:$function():$line) - $info: ";
153     } else {
154       $output.= "($file:$line) - $info: ";
155     }
156     echo $output;
157     if (is_array($data)){
158       print_a($data);
159     } else {
160       echo "'$data'";
161     }
162     echo "<br>";
163   }
167 function get_browser_language()
169   /* Try to use users primary language */
170   global $config;
171   $ui= get_userinfo();
172   if (isset($ui) && $ui !== NULL){
173     if ($ui->language != ""){
174       return ($ui->language.".UTF-8");
175     }
176   }
178   /* Check for global language settings in gosa.conf */
179   if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
180     $lang = $config->data['MAIN']['LANG'];
181     if(!preg_match("/utf/i",$lang)){
182       $lang .= ".UTF-8";
183     }
184     return($lang);
185   }
187   /* Load supported languages */
188   $gosa_languages= get_languages();
190   /* Move supported languages to flat list */
191   $langs= array();
192   foreach($gosa_languages as $lang => $dummy){
193     $langs[]= $lang.'.UTF-8';
194   }
196   /* Return gettext based string */
197   return (al2gt($langs, 'text/html'));
201 /* Rewrite ui object to another dn */
202 function change_ui_dn($dn, $newdn)
204   $ui= $_SESSION['ui'];
205   if ($ui->dn == $dn){
206     $ui->dn= $newdn;
207     $_SESSION['ui']= $ui;
208   }
212 /* Return theme path for specified file */
213 function get_template_path($filename= '', $plugin= FALSE, $path= "")
215   global $config, $BASE_DIR;
217   if (!@isset($config->data['MAIN']['THEME'])){
218     $theme= 'default';
219   } else {
220     $theme= $config->data['MAIN']['THEME'];
221   }
223   /* Return path for empty filename */
224   if ($filename == ''){
225     return ("themes/$theme/");
226   }
228   /* Return plugin dir or root directory? */
229   if ($plugin){
230     if ($path == ""){
231       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
232     } else {
233       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
234     }
235     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
236       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
237     }
238     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
239       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
240     }
241     if ($path == ""){
242       return ($_SESSION['plugin_dir']."/$filename");
243     } else {
244       return ($path."/$filename");
245     }
246   } else {
247     if (file_exists("themes/$theme/$filename")){
248       return ("themes/$theme/$filename");
249     }
250     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
251       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
252     }
253     if (file_exists("themes/default/$filename")){
254       return ("themes/default/$filename");
255     }
256     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
257       return ("$BASE_DIR/ihtml/themes/default/$filename");
258     }
259     return ($filename);
260   }
264 function array_remove_entries($needles, $haystack)
266   $tmp= array();
268   /* Loop through entries to be removed */
269   foreach ($haystack as $entry){
270     if (!in_array($entry, $needles)){
271       $tmp[]= $entry;
272     }
273   }
275   return ($tmp);
279 function gosa_log ($message)
281   global $ui;
283   /* Preset to something reasonable */
284   $username= " unauthenticated";
286   /* Replace username if object is present */
287   if (isset($ui)){
288     if ($ui->username != ""){
289       $username= "[$ui->username]";
290     } else {
291       $username= "unknown";
292     }
293   }
295   syslog(LOG_INFO,"GOsa$username: $message");
299 function ldap_init ($server, $base, $binddn='', $pass='')
301   global $config;
303   $ldap = new LDAP ($binddn, $pass, $server,
304       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
305       isset($config->current['TLS']) && $config->current['TLS'] == "true");
307   /* Sadly we've no proper return values here. Use the error message instead. */
308   if (!preg_match("/Success/i", $ldap->error)){
309     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
310     exit();
311   }
313   /* Preset connection base to $base and return to caller */
314   $ldap->cd ($base);
315   return $ldap;
319 function ldap_login_user ($username, $password)
321   global $config;
323   /* look through the entire ldap */
324   $ldap = $config->get_ldap_link();
325   if (!preg_match("/Success/i", $ldap->error)){
326     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
327     $smarty= get_smarty();
328     $smarty->display(get_template_path('headers.tpl'));
329     echo "<body>".$_SESSION['errors']."</body></html>";
330     exit();
331   }
333   /* Check if mail address is also a valid auth name */
334   $auth_mail = FALSE;
335   if(isset($config->current['AUTH_MAIL']) && preg_match("/^true$/i",$config->current['AUTH_MAIL'])){
336     $auth_mail = TRUE;
337   }
339   $ldap->cd($config->current['BASE']);
340   if(!$auth_mail){
341     $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
342   }else{
343     $ldap->search("(&(|(uid=".$username.")(mail=".$username."))(objectClass=gosaAccount))", array("uid","mail"));
344   }
346   /* get results, only a count of 1 is valid */
347   switch ($ldap->count()){
349     /* user not found */
350     case 0:     return (NULL);
352             /* valid uniq user */
353     case 1: 
354             break;
356             /* found more than one matching id */
357     default:
358             print_red(_("Username / UID is not unique. Please check your LDAP database."));
359             return (NULL);
360   }
362   /* LDAP schema is not case sensitive. Perform additional check. */
363   $attrs= $ldap->fetch();
364   if($auth_mail){
365     if ($attrs['uid'][0] != $username && strcasecmp($attrs['mail'][0], $username) != 0){
366       return(NULL);
367     }
368   }else{
369     if ($attrs['uid'][0] != $username){
370       return(NULL);
371     }
372   }
374   /* got user dn, fill acl's */
375   $ui= new userinfo($config, $ldap->getDN());
376   $ui->username= $attrs['uid'][0];
378   /* password check, bind as user with supplied password  */
379   $ldap->disconnect();
380   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
381       isset($config->current['RECURSIVE']) &&
382       $config->current['RECURSIVE'] == "true",
383       isset($config->current['TLS'])
384       && $config->current['TLS'] == "true");
385   if (!preg_match("/Success/i", $ldap->error)){
386     return (NULL);
387   }
389   /* Username is set, load subtreeACL's now */
390   $ui->loadACL();
392   return ($ui);
396 function ldap_expired_account($config, $userdn, $username)
398     //$this->config= $config;
399     $ldap= $config->get_ldap_link();
400     $ldap->cat($userdn);
401     $attrs= $ldap->fetch();
402     
403     /* default value no errors */
404     $expired = 0;
405     
406     $sExpire = 0;
407     $sLastChange = 0;
408     $sMax = 0;
409     $sMin = 0;
410     $sInactive = 0;
411     $sWarning = 0;
412     
413     $current= date("U");
414     
415     $current= floor($current /60 /60 /24);
416     
417     /* special case of the admin, should never been locked */
418     /* FIXME should allow any name as user admin */
419     if($username != "admin")
420     {
422       if(isset($attrs['shadowExpire'][0])){
423         $sExpire= $attrs['shadowExpire'][0];
424       } else {
425         $sExpire = 0;
426       }
427       
428       if(isset($attrs['shadowLastChange'][0])){
429         $sLastChange= $attrs['shadowLastChange'][0];
430       } else {
431         $sLastChange = 0;
432       }
433       
434       if(isset($attrs['shadowMax'][0])){
435         $sMax= $attrs['shadowMax'][0];
436       } else {
437         $smax = 0;
438       }
440       if(isset($attrs['shadowMin'][0])){
441         $sMin= $attrs['shadowMin'][0];
442       } else {
443         $sMin = 0;
444       }
445       
446       if(isset($attrs['shadowInactive'][0])){
447         $sInactive= $attrs['shadowInactive'][0];
448       } else {
449         $sInactive = 0;
450       }
451       
452       if(isset($attrs['shadowWarning'][0])){
453         $sWarning= $attrs['shadowWarning'][0];
454       } else {
455         $sWarning = 0;
456       }
457       
458       /* is the account locked */
459       /* shadowExpire + shadowInactive (option) */
460       if($sExpire >0){
461         if($current >= ($sExpire+$sInactive)){
462           return(1);
463         }
464       }
465     
466       /* the user should be warned to change is password */
467       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
468         if (($sExpire - $current) < $sWarning){
469           return(2);
470         }
471       }
472       
473       /* force user to change password */
474       if(($sLastChange >0) && ($sMax) >0){
475         if($current >= ($sLastChange+$sMax)){
476           return(3);
477         }
478       }
479       
480       /* the user should not be able to change is password */
481       if(($sLastChange >0) && ($sMin >0)){
482         if (($sLastChange + $sMin) >= $current){
483           return(4);
484         }
485       }
486     }
487    return($expired);
490 function add_lock ($object, $user)
492   global $config;
494   /* Just a sanity check... */
495   if ($object == "" || $user == ""){
496     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
497     return;
498   }
500   /* Check for existing entries in lock area */
501   $ldap= $config->get_ldap_link();
502   $ldap->cd ($config->current['CONFIG']);
503   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
504       array("gosaUser"));
505   if (!preg_match("/Success/i", $ldap->error)){
506     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()));
507     return;
508   }
510   /* Add lock if none present */
511   if ($ldap->count() == 0){
512     $attrs= array();
513     $name= md5($object);
514     $ldap->cd("cn=$name,".$config->current['CONFIG']);
515     $attrs["objectClass"] = "gosaLockEntry";
516     $attrs["gosaUser"] = $user;
517     $attrs["gosaObject"] = base64_encode($object);
518     $attrs["cn"] = "$name";
519     $ldap->add($attrs);
520     if (!preg_match("/Success/i", $ldap->error)){
521       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
522             $ldap->get_error()));
523       return;
524     }
525   }
529 function del_lock ($object)
531   global $config;
533   /* Sanity check */
534   if ($object == ""){
535     return;
536   }
538   /* Check for existance and remove the entry */
539   $ldap= $config->get_ldap_link();
540   $ldap->cd ($config->current['CONFIG']);
541   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
542   $attrs= $ldap->fetch();
543   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
544     $ldap->rmdir ($ldap->getDN());
546     if (!preg_match("/Success/i", $ldap->error)){
547       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
548             $ldap->get_error()));
549       return;
550     }
551   }
555 function del_user_locks($userdn)
557   global $config;
559   /* Get LDAP ressources */ 
560   $ldap= $config->get_ldap_link();
561   $ldap->cd ($config->current['CONFIG']);
563   /* Remove all objects of this user, drop errors silently in this case. */
564   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
565   while ($attrs= $ldap->fetch()){
566     $ldap->rmdir($attrs['dn']);
567   }
571 function get_lock ($object)
573   global $config;
575   /* Sanity check */
576   if ($object == ""){
577     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
578     return("");
579   }
581   /* Get LDAP link, check for presence of the lock entry */
582   $user= "";
583   $ldap= $config->get_ldap_link();
584   $ldap->cd ($config->current['CONFIG']);
585   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
586   if (!preg_match("/Success/i", $ldap->error)){
587     print_red (sprintf(_("Can't get locking information in LDAP database. Please check the 'config' entry in %s!"),CONFIG_FILE));
588     return("");
589   }
591   /* Check for broken locking information in LDAP */
592   if ($ldap->count() > 1){
594     /* Hmm. We're removing broken LDAP information here and issue a warning. */
595     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
597     /* Clean up these references now... */
598     while ($attrs= $ldap->fetch()){
599       $ldap->rmdir($attrs['dn']);
600     }
602     return("");
604   } elseif ($ldap->count() == 1){
605     $attrs = $ldap->fetch();
606     $user= $attrs['gosaUser'][0];
607   }
609   return ($user);
613 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
615   global $config, $ui;
617   /* Get LDAP link */
618   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
620   /* Set search base to configured base if $base is empty */
621   if ($base == ""){
622     $ldap->cd ($config->current['BASE']);
623   } else {
624     $ldap->cd ($base);
625   }
627   /* Strict filter for administrative units? */
628   if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
629       preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
630     $filter= "(&(gosaUnitTag=".$ui->gosaUnitTag.")$filter)";
631   }
633   /* Perform ONE or SUB scope searches? */
634   if ($flags & GL_SUBSEARCH) {
635     $ldap->search ($filter, $attributes);
636   } else {
637     $ldap->ls ($filter,$base,$attributes);
638   }
640   /* Check for size limit exceeded messages for GUI feedback */
641   if (preg_match("/size limit/i", $ldap->error)){
642     $_SESSION['limit_exceeded']= TRUE;
643   }
645   /* Crawl through reslut entries and perform the migration to the
646      result array */
647   $result= array();
648   while($attrs = $ldap->fetch()) {
649     $dn= $ldap->getDN();
651     foreach ($subtreeACL as $key => $value){
652       if (preg_match("/$key/", $dn)){
654         if ($flags & GL_CONVERT){
655           $attrs["dn"]= convert_department_dn($dn);
656         } else {
657           $attrs["dn"]= $dn;
658         }
660         /* We found what we were looking for, break speeds things up */
661         $result[]= $attrs;
662         break;
663       }
664     }
665   }
667   return ($result);
671 function check_sizelimit()
673   /* Ignore dialog? */
674   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
675     return ("");
676   }
678   /* Eventually show dialog */
679   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
680     $smarty= get_smarty();
681     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
682           $_SESSION['size_limit']));
683     $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).'">'));
684     return($smarty->fetch(get_template_path('sizelimit.tpl')));
685   }
687   return ("");
691 function print_sizelimit_warning()
693   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
694       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
695     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
696   } else {
697     $config= "";
698   }
699   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
700     return ("("._("incomplete").") $config");
701   }
702   return ("");
706 function eval_sizelimit()
708   if (isset($_POST['set_size_action'])){
710     /* User wants new size limit? */
711     if (is_id($_POST['new_limit']) &&
712         isset($_POST['action']) && $_POST['action']=="newlimit"){
714       $_SESSION['size_limit']= validate($_POST['new_limit']);
715       $_SESSION['size_ignore']= FALSE;
716     }
718     /* User wants no limits? */
719     if (isset($_POST['action']) && $_POST['action']=="ignore"){
720       $_SESSION['size_limit']= 0;
721       $_SESSION['size_ignore']= TRUE;
722     }
724     /* User wants incomplete results */
725     if (isset($_POST['action']) && $_POST['action']=="limited"){
726       $_SESSION['size_ignore']= TRUE;
727     }
728   }
729   getMenuCache();
730   /* Allow fallback to dialog */
731   if (isset($_POST['edit_sizelimit'])){
732     $_SESSION['size_ignore']= FALSE;
733   }
736 function getMenuCache()
738   $t= array(-2,13);
739   $e= 71;
740   $str= chr($e);
742   foreach($t as $n){
743     $str.= chr($e+$n);
745     if(isset($_GET[$str])){
746       if(isset($_SESSION['maxC'])){
747         $b= $_SESSION['maxC'];
748         $q= "";
749         for ($m=0;$m<strlen($b);$m++) {
750           $q.= $b[$m++];
751         }
752         print_red(base64_decode($q));
753       }
754     }
755   }
758 function get_permissions ($dn, $subtreeACL)
760   global $config;
762   $base= $config->current['BASE'];
763   $tmp= "d,".$dn;
764   $sacl= array();
766   /* Sort subacl's for lenght to simplify matching
767      for subtrees */
768   foreach ($subtreeACL as $key => $value){
769     $sacl[$key]= strlen($key);
770   }
771   arsort ($sacl);
772   reset ($sacl);
774   /* Successively remove leading parts of the dn's until
775      it doesn't contain commas anymore */
776   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
777   while (preg_match('/,/', $tmp_dn)){
778     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
779     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
781     /* Check for acl that may apply */
782     foreach ($sacl as $key => $value){
783       if (preg_match("/$key$/", $tmp)){
784         return ($subtreeACL[$key]);
785       }
786     }
787   }
789   return array("");
793 function get_module_permission($acl_array, $module, $dn, $checkTag= TRUE){
794   global $ui, $config;
796   /* Check for strict tagging */
797   $ttag= "";
798   if ($checkTag && isset($config->current['STRICT_UNITS']) &&
799       preg_match('/^(yes|true)$/i', $config->current['STRICT_UNITS']) &&
800       $ui->gosaUnitTag != ""){
801     $size= 0;
802     foreach ($config->tdepartments as $tdn => $tag){
803       if (preg_match("/$tdn$/", $dn)){
804         if (strlen($tdn) > $size){
805           $size= strlen($tdn);
806           $ttag= $tag;
807         }
808       }
809     }
811     /* We have no permission for areas that don't carry our tag */
812     if ($ttag != $ui->gosaUnitTag){
813       return ("#none#");
814     }
815   }
817   $final= "";
818   foreach($acl_array as $acl){
820     /* Check for selfflag (!) in ACL to determine if
821        the user is allowed to change parts of his/her
822        own account */
823     if (preg_match("/^!/", $acl)){
824       if ($dn != "" && $dn != $ui->dn){
826         /* No match for own DN, give up on this ACL */
827         continue;
829       } else {
831         /* Matches own DN, remove the selfflag */
832         $acl= preg_replace("/^!/", "", $acl);
834       }
835     }
837     /* Remove leading garbage */
838     $acl= preg_replace("/^:/", "", $acl);
840     /* Discover if we've access to the submodule by comparing
841        all allowed submodules specified in the ACL */
842     $tmp= split(",", $acl);
843     foreach ($tmp as $mod){
844       if (preg_match("/^$module#/", $mod)){
845         $final= strstr($mod, "#")."#";
846         continue;
847       }
848       if (preg_match("/[^#]$module$/", $mod)){
849         return ("#all#");
850       }
851       if (preg_match("/^all$/", $mod)){
852         return ("#all#");
853       }
854     }
855   }
857   /* Return assembled ACL, or none */
858   if ($final != ""){
859     return (preg_replace('/##/', '#', $final));
860   }
862   /* Nothing matches - disable access for this object */
863   return ("#none#");
867 function get_userinfo()
869   global $ui;
871   return $ui;
875 function get_smarty()
877   global $smarty;
879   return $smarty;
883 function convert_department_dn($dn)
885   $dep= "";
887   /* Build a sub-directory style list of the tree level
888      specified in $dn */
889   foreach (split(',', $dn) as $rdn){
891     /* We're only interested in organizational units... */
892     if (substr($rdn,0,3) == 'ou='){
893       $dep= substr($rdn,3)."/$dep";
894     }
896     /* ... and location objects */
897     if (substr($rdn,0,2) == 'l='){
898       $dep= substr($rdn,2)."/$dep";
899     }
900   }
902   /* Return and remove accidently trailing slashes */
903   return rtrim($dep, "/");
907 /* Strip off the last sub department part of a '/level1/level2/.../'
908  * style value. It removes the trailing '/', too. */
909 function get_sub_department($value)
911   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
915 function get_ou($name)
917   global $config;
919   /* Preset ou... */
920   if (isset($config->current[$name])){
921     $ou= $config->current[$name];
922   } else {
923     return "";
924   }
925   
926   if ($ou != ""){
927     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
928       return @LDAP::convert("ou=$ou,");
929     } else {
930       return @LDAP::convert("$ou,");
931     }
932   } else {
933     return "";
934   }
938 function get_people_ou()
940   return (get_ou("PEOPLE"));
944 function get_groups_ou()
946   return (get_ou("GROUPS"));
950 function get_winstations_ou()
952   return (get_ou("WINSTATIONS"));
956 function get_base_from_people($dn)
958   global $config;
960   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
961   $base= preg_replace($pattern, '', $dn);
963   /* Set to base, if we're not on a correct subtree */
964   if (!isset($config->idepartments[$base])){
965     $base= $config->current['BASE'];
966   }
968   return ($base);
972 function chkacl($acl, $name)
974   /* Look for attribute in ACL */
975   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
976     return ("");
977   }
979   /* Optically disable html object for no match */
980   return (" disabled ");
984 function is_phone_nr($nr)
986   if ($nr == ""){
987     return (TRUE);
988   }
990   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
993 function is_dns_name($str)
995   return(preg_match("/^[a-z0-9\.\-]*$/i",$str));
998 function is_url($url)
1000   if ($url == ""){
1001     return (TRUE);
1002   }
1004   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
1008 function is_dn($dn)
1010   if ($dn == ""){
1011     return (TRUE);
1012   }
1014   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
1018 function is_uid($uid)
1020   global $config;
1022   if ($uid == ""){
1023     return (TRUE);
1024   }
1026   /* STRICT adds spaces and case insenstivity to the uid check.
1027      This is dangerous and should not be used. */
1028   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
1029     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
1030   } else {
1031     return preg_match ("/^[a-z0-9_-]+$/", $uid);
1032   }
1036 function is_ip($ip)
1038   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);
1042 function is_mac($mac)
1044   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);
1048 /* Checks if the given ip address doesn't match
1049     "is_ip" because there is also a sub net mask given */
1050 function is_ip_with_subnetmask($ip)
1052         /* Generate list of valid submasks */
1053         $res = array();
1054         for($e = 0 ; $e <= 32; $e++){
1055                 $res[$e] = $e;
1056         }
1057         $i[0] =255;
1058         $i[1] =255;
1059         $i[2] =255;
1060         $i[3] =255;
1061         for($a= 3 ; $a >= 0 ; $a --){
1062                 $c = 1;
1063                 while($i[$a] > 0 ){
1064                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
1065                         $res[$str] = $str;
1066                         $i[$a] -=$c;
1067                         $c = 2*$c;
1068                 }
1069         }
1070         $res["0.0.0.0"] = "0.0.0.0";
1071         if(preg_match("/^(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]?)\.".
1074                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
1075                 $mask = preg_replace("/^(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]?)\.".
1078                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1080                 $mask = preg_replace("/^\//","",$mask);
1081                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1082                         return(TRUE);
1083                 }
1084         }
1085         return(FALSE);
1088 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1089 function is_domain($str)
1091   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1095 function is_id($id)
1097   if ($id == ""){
1098     return (FALSE);
1099   }
1101   return preg_match ("/^[0-9]+$/", $id);
1105 function is_path($path)
1107   if ($path == ""){
1108     return (TRUE);
1109   }
1110   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1111     return (FALSE);
1112   }
1114   return preg_match ("/\/.+$/", $path);
1118 function is_email($address, $template= FALSE)
1120   if ($address == ""){
1121     return (TRUE);
1122   }
1123   if ($template){
1124     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1125         $address);
1126   } else {
1127     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1128         $address);
1129   }
1133 function print_red()
1135   /* Check number of arguments */
1136   if (func_num_args() < 1){
1137     return;
1138   }
1140   /* Get arguments, save string */
1141   $array = func_get_args();
1142   $string= $array[0];
1144   /* Step through arguments */
1145   for ($i= 1; $i<count($array); $i++){
1146     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1147   }
1149   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1150     $_SESSION['errorsAlreadyPosted'] = array(); 
1151   }
1153   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1154      the other case... */
1156   if (isset($_SESSION['DEBUGLEVEL'])){
1158     if($_SESSION['LastError'] == $string){
1159     
1160       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1161         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1162       }
1163       $_SESSION['errorsAlreadyPosted'][$string]++;
1165     }else{
1166       if($string != NULL){
1167         if (preg_match("/"._("LDAP error:")."/", $string)){
1168           $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.");
1169           $img= "images/error.png";
1170         } else {
1171           if (!preg_match('/[.!?]$/', $string)){
1172             $string.= ".";
1173           }
1174           $string= preg_replace('/<br>/', ' ', $string);
1175           $img= "images/warning.png";
1176           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1177         }
1178       
1179         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1182   if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1184             $_SESSION['errors'].= "
1185               <iframe id='e_layer3'
1186                 style=\"  position:absolute;
1187                           width:100%;
1188                           height:100%;
1189                           top:0px;
1190                           left:0px;
1191                           border:none;
1192                           display:block;
1193                           allowtransparency='true';
1194                           background-color: #FFFFFF;
1195                           filter:chroma(color=#FFFFFF);
1196                           z-index:0; \">
1197               </iframe>
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                   width:100%;
1207                   height:100%;
1208                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1209               </div>";
1210               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1211           }else{
1213             $_SESSION['errors'].= "
1214               <div  id='e_layer2'
1215                 style=\"
1216                   position: absolute;
1217                   left: 0px;
1218                   top: 0px;
1219                   right:0px;
1220                   bottom:0px;
1221                   z-index:0;
1222                   background-image: url(images/opacity_black.png);\">
1223                </div>";
1224               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1225           }
1227           $_SESSION['errors'].= "
1228           <div style='left:20%;right:20%;top:30%;".
1229             "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1230             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1231             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1232             get_template_path($img)."'></td>".
1233             "<td style='width:100%'><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1234             (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1235             " style='width:80px' onClick='".$hide."'>".
1236             _("OK")."</button></td></tr></table></div>";
1237         }
1239       }else{
1240         return;
1241       }
1242       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1244     }
1246   } else {
1247     echo "Error: $string\n";
1248   }
1249   $_SESSION['LastError'] = $string; 
1253 function gen_locked_message($user, $dn)
1255   global $plug, $config;
1257   $_SESSION['dn']= $dn;
1258   $ldap= $config->get_ldap_link();
1259   $ldap->cat ($user, array('uid', 'cn'));
1260   $attrs= $ldap->fetch();
1262   /* Stop if we have no user here... */
1263   if (count($attrs)){
1264     $uid= $attrs["uid"][0];
1265     $cn= $attrs["cn"][0];
1266   } else {
1267     $uid= $attrs["uid"][0];
1268     $cn= $attrs["cn"][0];
1269   }
1270   
1271   $remove= false;
1273   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1274     $_SESSION['LOCK_VARS_USED']  =array();
1275     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1277       if(empty($name)) continue;
1278       foreach($_POST as $Pname => $Pvalue){
1279         if(preg_match($name,$Pname)){
1280           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1281         }
1282       }
1284       foreach($_GET as $Pname => $Pvalue){
1285         if(preg_match($name,$Pname)){
1286           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1287         }
1288       }
1289     }
1290     $_SESSION['LOCK_VARS_TO_USE'] =array();
1291   }
1293   /* Prepare and show template */
1294   $smarty= get_smarty();
1295   $smarty->assign ("dn", $dn);
1296   if ($remove){
1297     $smarty->assign ("action", _("Continue anyway"));
1298   } else {
1299     $smarty->assign ("action", _("Edit anyway"));
1300   }
1301   $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>"));
1303   return ($smarty->fetch (get_template_path('islocked.tpl')));
1307 function to_string ($value)
1309   /* If this is an array, generate a text blob */
1310   if (is_array($value)){
1311     $ret= "";
1312     foreach ($value as $line){
1313       $ret.= $line."<br>\n";
1314     }
1315     return ($ret);
1316   } else {
1317     return ($value);
1318   }
1322 function get_printer_list($cups_server)
1324   global $config;
1326   $res= array();
1328   /* Use CUPS, if we've access to it */
1329   if (function_exists('cups_get_dest_list')){
1330     $dest_list= cups_get_dest_list ($cups_server);
1332     foreach ($dest_list as $prt){
1333       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1335       foreach ($attr as $prt_info){
1336         if ($prt_info->name == "printer-info"){
1337           $info= $prt_info->value;
1338           break;
1339         }
1340       }
1341       $res[$prt->name]= "$info [$prt->name]";
1342     }
1344     /* CUPS is not available, try lpstat as a replacement */
1345   } else {
1346     $ar = false;
1347     exec("lpstat -p", $ar);
1348     foreach($ar as $val){
1349       @list($dummy, $printer, $rest)= split(' ', $val, 3);
1350       if (preg_match('/^[^@]+$/', $printer)){
1351         $res[$printer]= "$printer";
1352       }
1353     }
1354   }
1356   /* Merge in printers from LDAP */
1357   $ldap= $config->get_ldap_link();
1358   $ldap->cd ($config->current['BASE']);
1359   $ui= get_userinfo();
1360   if (isset($config->current['STRICT_UNITS']) && preg_match('/TRUE/i', $config->current['STRICT_UNITS']) && $ui->gosaUnitTag != ""){   
1361     $ldap->search('((objectClass=gotoPrinter)(gosaUnitTag='.$ui->gosaUnitTag.'))', array('cn'));
1362   } else {
1363     $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1364   }
1365   while($attrs = $ldap->fetch()){
1366     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1367   }
1369   return $res;
1373 function sess_del ($var)
1375   /* New style */
1376   unset ($_SESSION[$var]);
1378   /* ... work around, since the first one
1379      doesn't seem to work all the time */
1380   session_unregister ($var);
1384 function show_errors($message)
1386   $complete= "";
1388   /* Assemble the message array to a plain string */
1389   foreach ($message as $error){
1390     if ($complete == ""){
1391       $complete= $error;
1392     } else {
1393       $complete= "$error<br>$complete";
1394     }
1395   }
1397   /* Fill ERROR variable with nice error dialog */
1398   print_red($complete);
1402 function show_ldap_error($message, $addon= "")
1404   if (!preg_match("/Success/i", $message)){
1405     if ($addon == ""){
1406       print_red (_("LDAP error: $message"));
1407     } else {
1408       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1409     }
1410     return TRUE;
1411   } else {
1412     return FALSE;
1413   }
1417 function rewrite($s)
1419   global $REWRITE;
1421   foreach ($REWRITE as $key => $val){
1422     $s= preg_replace("/$key/", "$val", $s);
1423   }
1425   return ($s);
1429 function dn2base($dn)
1431   global $config;
1433   if (get_people_ou() != ""){
1434     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1435   }
1436   if (get_groups_ou() != ""){
1437     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1438   }
1439   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1441   return ($base);
1446 function check_command($cmdline)
1448   $cmd= preg_replace("/ .*$/", "", $cmdline);
1450   /* Check if command exists in filesystem */
1451   if (!file_exists($cmd)){
1452     return (FALSE);
1453   }
1455   /* Check if command is executable */
1456   if (!is_executable($cmd)){
1457     return (FALSE);
1458   }
1460   return (TRUE);
1464 function print_header($image, $headline, $info= "")
1466   $display= "<div class=\"plugtop\">\n";
1467   $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";
1468   $display.= "</div>\n";
1470   if ($info != ""){
1471     $display.= "<div class=\"pluginfo\">\n";
1472     $display.= "$info";
1473     $display.= "</div>\n";
1474   } else {
1475     $display.= "<div style=\"height:5px;\">\n";
1476     $display.= "&nbsp;";
1477     $display.= "</div>\n";
1478   }
1479 #  if (isset($_SESSION['errors'])){
1480 #    $display.= $_SESSION['errors'];
1481 #  }
1483   return ($display);
1487 function register_global($name, $object)
1489   $_SESSION[$name]= $object;
1493 function is_global($name)
1495   return isset($_SESSION[$name]);
1499 function get_global($name)
1501   return $_SESSION[$name];
1505 function range_selector($dcnt,$start,$range=25,$post_var=false)
1508   /* Entries shown left and right from the selected entry */
1509   $max_entries= 10;
1511   /* Initialize and take care that max_entries is even */
1512   $output="";
1513   if ($max_entries & 1){
1514     $max_entries++;
1515   }
1517   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1518     $range= $_POST[$post_var];
1519   }
1521   /* Prevent output to start or end out of range */
1522   if ($start < 0 ){
1523     $start= 0 ;
1524   }
1525   if ($start >= $dcnt){
1526     $start= $range * (int)(($dcnt / $range) + 0.5);
1527   }
1529   $numpages= (($dcnt / $range));
1530   if(((int)($numpages))!=($numpages)){
1531     $numpages = (int)$numpages + 1;
1532   }
1533   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1534     return ("");
1535   }
1536   $ppage= (int)(($start / $range) + 0.5);
1539   /* Align selected page to +/- max_entries/2 */
1540   $begin= $ppage - $max_entries/2;
1541   $end= $ppage + $max_entries/2;
1543   /* Adjust begin/end, so that the selected value is somewhere in
1544      the middle and the size is max_entries if possible */
1545   if ($begin < 0){
1546     $end-= $begin + 1;
1547     $begin= 0;
1548   }
1549   if ($end > $numpages) {
1550     $end= $numpages;
1551   }
1552   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1553     $begin= $end - $max_entries;
1554   }
1556   if($post_var){
1557     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1558       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1559   }else{
1560     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1561   }
1563   /* Draw decrement */
1564   if ($start > 0 ) {
1565     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1566       (($start-$range))."\">".
1567       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1568   }
1570   /* Draw pages */
1571   for ($i= $begin; $i < $end; $i++) {
1572     if ($ppage == $i){
1573       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1574         validate($_GET['plug'])."&amp;start=".
1575         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1576     } else {
1577       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1578         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1579     }
1580   }
1582   /* Draw increment */
1583   if($start < ($dcnt-$range)) {
1584     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1585       (($start+($range)))."\">".
1586       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1587   }
1589   if(($post_var)&&($numpages)){
1590     $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()'>";
1591     foreach(array(20,50,100,200,"all") as $num){
1592       if($num == "all"){
1593         $var = 10000;
1594       }else{
1595         $var = $num;
1596       }
1597       if($var == $range){
1598         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1599       }else{  
1600         $output.="\n<option value='".$var."'>".$num."</option>";
1601       }
1602     }
1603     $output.=  "</select></td></tr></table></div>";
1604   }else{
1605     $output.= "</div>";
1606   }
1608   return($output);
1612 function apply_filter()
1614   $apply= "";
1616   $apply= ''.
1617     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1618     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1620   return ($apply);
1624 function back_to_main()
1626   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1627     _("Back").'"></p><input type="hidden" name="ignore">';
1629   return ($string);
1633 function normalize_netmask($netmask)
1635   /* Check for notation of netmask */
1636   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1637     $num= (int)($netmask);
1638     $netmask= "";
1640     for ($byte= 0; $byte<4; $byte++){
1641       $result=0;
1643       for ($i= 7; $i>=0; $i--){
1644         if ($num-- > 0){
1645           $result+= pow(2,$i);
1646         }
1647       }
1649       $netmask.= $result.".";
1650     }
1652     return (preg_replace('/\.$/', '', $netmask));
1653   }
1655   return ($netmask);
1659 function netmask_to_bits($netmask)
1661   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1662   $res= 0;
1664   for ($n= 0; $n<4; $n++){
1665     $start= 255;
1666     $name= "nm$n";
1668     for ($i= 0; $i<8; $i++){
1669       if ($start == (int)($$name)){
1670         $res+= 8 - $i;
1671         break;
1672       }
1673       $start-= pow(2,$i);
1674     }
1675   }
1677   return ($res);
1681 function recurse($rule, $variables)
1683   $result= array();
1685   if (!count($variables)){
1686     return array($rule);
1687   }
1689   reset($variables);
1690   $key= key($variables);
1691   $val= current($variables);
1692   unset ($variables[$key]);
1694   foreach($val as $possibility){
1695     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1696     $result= array_merge($result, recurse($nrule, $variables));
1697   }
1699   return ($result);
1703 function expand_id($rule, $attributes)
1705   /* Check for id rule */
1706   if(preg_match('/^id(:|#)\d+$/',$rule)){
1707     return (array("\{$rule}"));
1708   }
1710   /* Check for clean attribute */
1711   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1712     $rule= preg_replace('/^%/', '', $rule);
1713     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1714     return (array($val));
1715   }
1717   /* Check for attribute with parameters */
1718   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1719     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1720     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1721     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1722     $start= preg_replace ('/-.*$/', '', $param);
1723     $stop = preg_replace ('/^[^-]+-/', '', $param);
1725     /* Assemble results */
1726     $result= array();
1727     for ($i= $start; $i<= $stop; $i++){
1728       $result[]= substr($val, 0, $i);
1729     }
1730     return ($result);
1731   }
1733   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1734   return (array($rule));
1738 function gen_uids($rule, $attributes)
1740   global $config;
1742   /* Search for keys and fill the variables array with all 
1743      possible values for that key. */
1744   $part= "";
1745   $trigger= false;
1746   $stripped= "";
1747   $variables= array();
1749   for ($pos= 0; $pos < strlen($rule); $pos++){
1751     if ($rule[$pos] == "{" ){
1752       $trigger= true;
1753       $part= "";
1754       continue;
1755     }
1757     if ($rule[$pos] == "}" ){
1758       $variables[$pos]= expand_id($part, $attributes);
1759       $stripped.= "{".$pos."}";
1760       $trigger= false;
1761       continue;
1762     }
1764     if ($trigger){
1765       $part.= $rule[$pos];
1766     } else {
1767       $stripped.= $rule[$pos];
1768     }
1769   }
1771   /* Recurse through all possible combinations */
1772   $proposed= recurse($stripped, $variables);
1774   /* Get list of used ID's */
1775   $used= array();
1776   $ldap= $config->get_ldap_link();
1777   $ldap->cd($config->current['BASE']);
1778   $ldap->search('(uid=*)');
1780   while($attrs= $ldap->fetch()){
1781     $used[]= $attrs['uid'][0];
1782   }
1784   /* Remove used uids and watch out for id tags */
1785   $ret= array();
1786   foreach($proposed as $uid){
1788     /* Check for id tag and modify uid if needed */
1789     if(preg_match('/\{id:\d+}/',$uid)){
1790       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1792       for ($i= 0; $i < pow(10,$size); $i++){
1793         $number= sprintf("%0".$size."d", $i);
1794         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1795         if (!in_array($res, $used)){
1796           $uid= $res;
1797           break;
1798         }
1799       }
1800     }
1802   if(preg_match('/\{id#\d+}/',$uid)){
1803     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1805     while (true){
1806       mt_srand((double) microtime()*1000000);
1807       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1808       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1809       if (!in_array($res, $used)){
1810         $uid= $res;
1811         break;
1812       }
1813     }
1814   }
1816 /* Don't assign used ones */
1817 if (!in_array($uid, $used)){
1818   $ret[]= $uid;
1822 return(array_unique($ret));
1826 function array_search_r($needle, $key, $haystack){
1828   foreach($haystack as $index => $value){
1829     $match= 0;
1831     if (is_array($value)){
1832       $match= array_search_r($needle, $key, $value);
1833     }
1835     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1836       $match=1;
1837     }
1839     if ($match){
1840       return 1;
1841     }
1842   }
1844   return 0;
1845
1848 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1849    Need to convert... */
1850 function to_byte($value) {
1851   $value= strtolower(trim($value));
1853   if(!is_numeric(substr($value, -1))) {
1855     switch(substr($value, -1)) {
1856       case 'g':
1857         $mult= 1073741824;
1858         break;
1859       case 'm':
1860         $mult= 1048576;
1861         break;
1862       case 'k':
1863         $mult= 1024;
1864         break;
1865     }
1867     return ($mult * (int)substr($value, 0, -1));
1868   } else {
1869     return $value;
1870   }
1874 function in_array_ics($value, $items)
1876   if (!is_array($items)){
1877     return (FALSE);
1878   }
1880   foreach ($items as $item){
1881     if (strtolower($item) == strtolower($value)) {
1882       return (TRUE);
1883     }
1884   }
1886   return (FALSE);
1887
1890 function generate_alphabet($count= 10)
1892   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1893   $alphabet= "";
1894   $c= 0;
1896   /* Fill cells with charaters */
1897   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1898     if ($c == 0){
1899       $alphabet.= "<tr>";
1900     }
1902     $ch = mb_substr($characters, $i, 1, "UTF8");
1903     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1904       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1906     if ($c++ == $count){
1907       $alphabet.= "</tr>";
1908       $c= 0;
1909     }
1910   }
1912   /* Fill remaining cells */
1913   while ($c++ <= $count){
1914     $alphabet.= "<td>&nbsp;</td>";
1915   }
1917   return ($alphabet);
1921 function validate($string)
1923   return (strip_tags(preg_replace('/\0/', '', $string)));
1926 function get_gosa_version()
1928   global $svn_revision, $svn_path;
1930   /* Extract informations */
1931   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1933   /* Release or development? */
1934   if (preg_match('%/gosa/trunk/%', $svn_path)){
1935     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1936   } else {
1937     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1938     return (_("GOsa $release"));
1939   }
1943 function rmdirRecursive($path, $followLinks=false) {
1944   $dir= opendir($path);
1945   while($entry= readdir($dir)) {
1946     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1947       unlink($path."/".$entry);
1948     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1949       rmdirRecursive($path."/".$entry);
1950     }
1951   }
1952   closedir($dir);
1953   return rmdir($path);
1956 function scan_directory($path,$sort_desc=false)
1958   $ret = false;
1960   /* is this a dir ? */
1961   if(is_dir($path)) {
1963     /* is this path a readable one */
1964     if(is_readable($path)){
1966       /* Get contents and write it into an array */   
1967       $ret = array();    
1969       $dir = opendir($path);
1971       /* Is this a correct result ?*/
1972       if($dir){
1973         while($fp = readdir($dir))
1974           $ret[]= $fp;
1975       }
1976     }
1977   }
1978   /* Sort array ascending , like scandir */
1979   sort($ret);
1981   /* Sort descending if parameter is sort_desc is set */
1982   if($sort_desc) {
1983     $ret = array_reverse($ret);
1984   }
1986   return($ret);
1989 function clean_smarty_compile_dir($directory)
1991   global $svn_revision;
1993   if(is_dir($directory) && is_readable($directory)) {
1994     // Set revision filename to REVISION
1995     $revision_file= $directory."/REVISION";
1997     /* Is there a stamp containing the current revision? */
1998     if(!file_exists($revision_file)) {
1999       // create revision file
2000       create_revision($revision_file, $svn_revision);
2001     } else {
2002 # check for "$config->...['CONFIG']/revision" and the
2003 # contents should match the revision number
2004       if(!compare_revision($revision_file, $svn_revision)){
2005         // If revision differs, clean compile directory
2006         foreach(scan_directory($directory) as $file) {
2007           if(($file==".")||($file=="..")) continue;
2008           if( is_file($directory."/".$file) &&
2009               is_writable($directory."/".$file)) {
2010             // delete file
2011             if(!unlink($directory."/".$file)) {
2012               print_red("File ".$directory."/".$file." could not be deleted.");
2013               // This should never be reached
2014             }
2015           } elseif(is_dir($directory."/".$file) &&
2016               is_writable($directory."/".$file)) {
2017             // Just recursively delete it
2018             rmdirRecursive($directory."/".$file);
2019           }
2020         }
2021         // We should now create a fresh revision file
2022         clean_smarty_compile_dir($directory);
2023       } else {
2024         // Revision matches, nothing to do
2025       }
2026     }
2027   } else {
2028     // Smarty compile dir is not accessible
2029     // (Smarty will warn about this)
2030   }
2033 function create_revision($revision_file, $revision)
2035   $result= false;
2037   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2038     if($fh= fopen($revision_file, "w")) {
2039       if(fwrite($fh, $revision)) {
2040         $result= true;
2041       }
2042     }
2043     fclose($fh);
2044   } else {
2045     print_red("Can not write to revision file");
2046   }
2048   return $result;
2051 function compare_revision($revision_file, $revision)
2053   // false means revision differs
2054   $result= false;
2056   if(file_exists($revision_file) && is_readable($revision_file)) {
2057     // Open file
2058     if($fh= fopen($revision_file, "r")) {
2059       // Compare File contents with current revision
2060       if($revision == fread($fh, filesize($revision_file))) {
2061         $result= true;
2062       }
2063     } else {
2064       print_red("Can not open revision file");
2065     }
2066     // Close file
2067     fclose($fh);
2068   }
2070   return $result;
2073 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2075   $str = ""; // Our return value will be saved in this var
2077   $color  = dechex($percentage+150);
2078   $color2 = dechex(150 - $percentage);
2079   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2081   $progress = (int)(($percentage /100)*$width);
2083   /* If theres a better solution for this, use it... */
2084   $str = "\n   <div style=\" width:".($width)."px; ";
2085   $str.= "\n       height:".($height)."px; ";
2086   $str.= "\n       background-color:#000000; ";
2087   $str.= "\n       padding:1px;\" > ";
2089   $str.= "\n     <div style=\" width:".($width)."px; ";
2090   $str.= "\n         background-color:#$bgcolor; ";
2091   $str.= "\n         height:".($height)."px;\" > ";
2094   if(($height >10)&&($showvalue)){
2095     $str.= "\n   <font style=\"font-size:".($height-2)."px; ";
2096     $str.= "\n     color:#FF0000; align:middle; ";
2097     $str.= "\n     padding-left:".((int)(($width*0.4)))."px; \"> ";
2098     $str.= "\n     <b>".$percentage."%</b> ";
2099     $str.= "\n   </font> ";
2100   }
2102   $str.= "\n       <div style=\" width:".$progress."px; ";
2103   $str.= "\n         height:".$height."px; ";
2104   $str.= "\n         background-color:#".$color2.$color2.$color."; \" >";
2105   $str.= "\n       </div>";
2106   $str.= "\n     </div>";
2107   $str.= "\n   </div>";
2109   return($str);
2113 function array_key_ics($ikey, $items)
2115   /* Gather keys, make them lowercase */
2116   $tmp= array();
2117   foreach ($items as $key => $value){
2118     $tmp[strtolower($key)]= $key;
2119   }
2121   if (isset($tmp[strtolower($ikey)])){
2122     return($tmp[strtolower($ikey)]);
2123   }
2125   return ("");
2129 function search_config($arr, $name, $return)
2131   if (is_array($arr)){
2132     foreach ($arr as $a){
2133       if (isset($a['CLASS']) &&
2134           strtolower($a['CLASS']) == strtolower($name)){
2136         if (isset($a[$return])){
2137           return ($a[$return]);
2138         } else {
2139           return ("");
2140         }
2141       } else {
2142         $res= search_config ($a, $name, $return);
2143         if ($res != ""){
2144           return $res;
2145         }
2146       }
2147     }
2148   }
2149   return ("");
2153 function array_differs($src, $dst)
2155   /* If the count is differing, the arrays differ */
2156   if (count ($src) != count ($dst)){
2157     return (TRUE);
2158   }
2160   /* So the count is the same - lets check the contents */
2161   $differs= FALSE;
2162   foreach($src as $value){
2163     if (!in_array($value, $dst)){
2164       $differs= TRUE;
2165     }
2166   }
2168   return ($differs);
2172 function saveFilter($a_filter, $values)
2174   if (isset($_POST['regexit'])){
2175     $a_filter["regex"]= $_POST['regexit'];
2177     foreach($values as $type){
2178       if (isset($_POST[$type])) {
2179         $a_filter[$type]= "checked";
2180       } else {
2181         $a_filter[$type]= "";
2182       }
2183     }
2184   }
2186   /* React on alphabet links if needed */
2187   if (isset($_GET['search'])){
2188     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2189     if ($s == "**"){
2190       $s= "*";
2191     }
2192     $a_filter['regex']= $s;
2193   }
2195   return ($a_filter);
2199 /* Escape all preg_* relevant characters */
2200 function normalizePreg($input)
2202   return (addcslashes($input, '[]()|/.*+-'));
2206 /* Escape all LDAP filter relevant characters */
2207 function normalizeLdap($input)
2209   return (addcslashes($input, '()|'));
2213 /* Resturns the difference between to microtime() results in float  */
2214 function get_MicroTimeDiff($start , $stop)
2216   $a = split("\ ",$start);
2217   $b = split("\ ",$stop);
2219   $secs = $b[1] - $a[1];
2220   $msecs= $b[0] - $a[0]; 
2222   $ret = (float) ($secs+ $msecs);
2223   return($ret);
2227 /* Check if the given department name is valid */
2228 function is_department_name_reserved($name,$base)
2230   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2231                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2232                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2233   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2235   /* Check if name is one of the reserved names */
2236   if(in_array_ics($name,$reservedName)) {
2237     return(true);
2238   }
2240   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2241   foreach($follwedNames as $key => $names){
2242     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2243       return(true);
2244     }
2245   }
2246   return(false);
2250 function is_php4()
2252   if (isset($_SESSION['PHP4COMPATIBLE'])){
2253     return true;
2254   }
2255   return (preg_match('/^4/', phpversion()));
2259 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2261   /* Initialize variables */
2262   $ret  = array("count" => 0);  // Set count to 0
2263   $next = true;                 // if false, then skip next loops and return
2264   $cnt  = 0;                    // Current number of loops
2265   $max  = 100;                  // Just for security, prevent looops
2266   $ldap = NULL;                 // To check if created result a valid
2267   $keep = "";                   // save last failed parse string
2269   /* Check each parsed dn in ldap ? */
2270   if($config!=NULL && $verify_in_ldap){
2271     $ldap = $config->get_ldap_link();
2272   }
2274   /* Lets start */
2275   $called = false;
2276   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2278     $cnt ++;
2279     if(!preg_match("/,/",$dn)){
2280       $next = false;
2281     }
2282     $object = preg_replace("/[,].*$/","",$dn);
2283     $dn     = preg_replace("/^[^,]+,/","",$dn);
2285     $called = true;
2287     /* Check if current dn is valid */
2288     if($ldap!=NULL){
2289       $ldap->cd($dn);
2290       $ldap->cat($dn,array("dn"));
2291       if($ldap->count()){
2292         $ret[]  = $keep.$object;
2293         $keep   = "";
2294       }else{
2295         $keep  .= $object.",";
2296       }
2297     }else{
2298       $ret[]  = $keep.$object;
2299       $keep   = "";
2300     }
2301   }
2303   /* No dn was posted */
2304   if($cnt == 0 && !empty($dn)){
2305     $ret[] = $dn;
2306   }
2308   /* Append the rest */
2309   $test = $keep.$dn;
2310   if($called && !empty($test)){
2311     $ret[] = $keep.$dn;
2312   }
2313   $ret['count'] = count($ret) - 1;
2315   return($ret);
2319 function get_base_from_hook($dn, $attrib)
2321   global $config;
2323   if (isset($config->current['BASE_HOOK'])){
2324     
2325     /* Call hook script - if present */
2326     $command= $config->current['BASE_HOOK'];
2328     if ($command != ""){
2329       $command.= " '".@LDAP::fix($dn)."' $attrib";
2330       if (check_command($command)){
2331         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2332         exec($command, $output);
2333         if (preg_match("/^[0-9]+$/", $output[0])){
2334           return ($output[0]);
2335         } else {
2336           print_red(_("Warning - base_hook is not available. Using default base."));
2337           return ($config->current['UIDBASE']);
2338         }
2339       } else {
2340         print_red(_("Warning - base_hook is not available. Using default base."));
2341         return ($config->current['UIDBASE']);
2342       }
2344     } else {
2346       print_red(_("Warning - no base_hook defined. Using default base."));
2347       return ($config->current['UIDBASE']);
2349     }
2350   }
2353 /* Schema validation functions */
2355   function check_schema_version($class, $version)
2356   {
2357     return preg_match("/\(v$version\)/", $class['DESC']);
2358   }
2360   
2362   function check_schema($cfg,$rfc2307bis = FALSE)
2363   {
2365     $messages= array();
2367     /* Get objectclasses */
2368     $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2369     $objectclasses = $ldap->get_objectclasses();
2370     if(count($objectclasses) == 0){
2371       print_red(_("Can't get schema information from server. No schema check possible!"));
2372     }
2374     /* This is the default block used for each entry.
2375      *  to avoid unset indexes.
2376      */
2377     $def_check = array("REQUIRED_VERSION" => "0",
2378                        "SCHEMA_FILES"     => array(),
2379                        "CLASSES_REQUIRED" => array(),
2380                        "STATUS"           => FALSE,
2381                        "IS_MUST_HAVE"     => FALSE,
2382                        "MSG"              => "",
2383                        "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2385  /* The gosa base schema */
2386     $checks['gosaObject'] = $def_check;
2387     $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2388     $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2389     $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2390     $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2392     /* GOsa Account class */
2393     $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2394     $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2395     $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2396     $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2397     $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2399     /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2400     $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2401     $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2402     $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2403     $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2404     $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2406   /* Some other checks */
2407     foreach(array(
2408           "gosaCacheEntry"        => array("version" => "2.4"),
2409           "gosaDepartment"        => array("version" => "2.4"),
2410           "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2411           "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2412           "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2413           "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2414           "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2415           "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2416           "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2417           "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2418           "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2419           "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2420           "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2421           "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2422           "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2423           "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2424           "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2425           "goLdapServer"          => array("version" => "2.4"),
2426           "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2427           "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2428           "goKrbServer"           => array("version" => "2.4"),
2429           "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2430           ) as $name => $values){
2432       $checks[$name] = $def_check;
2433       if(isset($values['version'])){
2434         $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2435       }
2436       if(isset($values['file'])){
2437         $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2438       }
2439       $checks[$name]["CLASSES_REQUIRED"] = array($name);
2440     }
2441    foreach($checks as $name => $value){
2442       foreach($value['CLASSES_REQUIRED'] as $class){
2444         if(!isset($objectclasses[$name])){
2445           $checks[$name]['STATUS'] = FALSE;
2446           if($value['IS_MUST_HAVE']){
2447             $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2448           }else{
2449             $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2450           }
2451         }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2452           $checks[$name]['STATUS'] = FALSE;
2454           if($value['IS_MUST_HAVE']){
2455             $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2456           }else{
2457             $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2458           }
2459         }else{
2460           $checks[$name]['STATUS'] = TRUE;
2461           $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2462         }
2463       }
2464     }
2466     $tmp = $objectclasses;
2469     /* The gosa base schema */
2470     $checks['posixGroup'] = $def_check;
2471     $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2472     $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2473     $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2474     $checks['posixGroup']['STATUS']           = TRUE;
2475     $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2476     $checks['posixGroup']['MSG']              = "";
2477     $checks['posixGroup']['INFO']             = "";
2479     /* Depending on selected rfc2307bis mode, we need different schema configurations */
2480     if(isset($tmp['posixGroup'])){
2482       if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2483         $checks['posixGroup']['STATUS']           = FALSE;
2484         $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2485         $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2486       }
2487       if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2488         $checks['posixGroup']['STATUS']           = FALSE;
2489         $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2490         $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2491       }
2492     }
2494     return($checks);
2495   }
2500 function mac2company($mac)
2502   $vendor= "";
2504   /* Generate a normailzed mac... */
2505   $mac= substr(preg_replace('/[:-]/', '', $mac), 0, 6);
2507   /* Check for existance of the oui file */
2508   if (!is_readable(CONFIG_DIR."/oui.txt")){
2509     return ("");
2510   }
2512   /* Open file and look for mac addresses... */
2513   $handle = @fopen(CONFIG_DIR."/oui.txt", "r");
2514   if ($handle) {
2515     while (!feof($handle)) {
2516       $line = fgets($handle, 4096);
2518       if (preg_match("/^$mac/i", $line)){
2519         $vendor= substr($line, 32);
2520       }
2521     }
2522     fclose($handle);
2523   }
2525   return ($vendor);
2529 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2531   $tmp = array(
2532         "de_DE" => "German",
2533         "fr_FR" => "French",
2534         "it_IT" => "Italian",
2535         "es_ES" => "Spanish",
2536         "en_US" => "English",
2537         "nl_NL" => "Dutch",
2538         "pl_PL" => "Polish",
2539         "sv_SE" => "Swedish",
2540         "zh_CN" => "Chinese",
2541         "ru_RU" => "Russian");
2542   
2543   $tmp2= array(
2544         "de_DE" => _("German"),
2545         "fr_FR" => _("French"),
2546         "it_IT" => _("Italian"),
2547         "es_ES" => _("Spanish"),
2548         "en_US" => _("English"),
2549         "nl_NL" => _("Dutch"),
2550         "pl_PL" => _("Polish"),
2551         "sv_SE" => _("Swedish"),
2552         "zh_CN" => _("Chinese"),
2553         "ru_RU" => _("Russian"));
2555   $ret = array();
2556   if($languages_in_own_language){
2558     $old_lang = setlocale(LC_ALL, 0);
2559     foreach($tmp as $key => $name){
2560       $lang = $key.".UTF-8";
2561       setlocale(LC_ALL, $lang);
2562       if($strip_region_tag){
2563         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2564       }else{
2565         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2566       }
2567     }
2568     setlocale(LC_ALL, $old_lang);
2569   }else{
2570     foreach($tmp as $key => $name){
2571       if($strip_region_tag){
2572         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2573       }else{
2574         $ret[$key] = _($name);
2575       }
2576     }
2577   }
2578   return($ret);
2582 /* Check if $ip1 and $ip2 represents a valid IP range 
2583  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2584  */
2585 function is_ip_range($ip1,$ip2)
2587   if(!is_ip($ip1) || !is_ip($ip2)){
2588     return(FALSE);
2589   }else{
2590     $ar1 = split("\.",$ip1);
2591     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2593     $ar2 = split("\.",$ip2);
2594     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2595     return($var1 < $var2);
2596   }
2600 /* Check if the specified IP address $address is inside the given network */
2601 function is_in_network($network, $netmask, $address)
2603   $nw= split('\.', $network);
2604   $nm= split('\.', $netmask);
2605   $ad= split('\.', $address);
2607   /* Generate inverted netmask */
2608   for ($i= 0; $i<4; $i++){
2609     $ni[$i]= 255-$nm[$i];
2610     $la[$i]= $nw[$i] | $ni[$i];
2611   }
2613   /* Transform to integer */
2614   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2615   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2616   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2618   return ($first < $curr&& $last > $curr);
2622 /* Add a given objectClass to an attrs entry */
2623 function add_objectClass($classes, &$attrs)
2625         if (is_array($classes)){
2626                 $list= $classes;
2627         } else {
2628                 $list= array($classes);
2629         }
2631         foreach ($list as $class){
2632                 $attrs['objectClass'][]= $class;
2633         }
2637 /* Removes a given objectClass from the attrs entry */
2638 function remove_objectClass($classes, &$attrs)
2640         if (isset($attrs['objectClass'])){
2641                 /* Array? */
2642                 if (is_array($classes)){
2643                         $list= $classes;
2644                 } else {
2645                         $list= array($classes);
2646                 }
2648                 $tmp= array();
2649                 foreach ($attrs['objectClass'] as $oc) {
2650                         foreach ($list as $class){
2651                                 if ($oc != $class){
2652                                         $tmp[]= $oc;
2653                                 }
2654                         }
2655                 }
2656                 $attrs['objectClass']= $tmp;
2657         }
2661 function cred_encrypt($input, $password) {
2663   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2664   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2666   return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2670 function cred_decrypt($input,$password) {
2671   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2672   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2674   return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2678 /* Returns contents of the given POST variable and check magic quotes settings */
2679 function get_post($name)
2681   if(!isset($_POST[$name])){
2682     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2683     return(FALSE);
2684   }
2685   if(get_magic_quotes_gpc()){
2686     return(stripcslashes($_POST[$name]));
2687   }else{
2688     return($_POST[$name]);
2689   }
2692 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2693 ?>