Code

Added ns record to zones
[gosa.git] / include / functions.inc
1 <?php
2 /*
3  * This code is part of GOsa (https://gosa.gonicus.de)
4  * Copyright (C) 2003 Cajus Pollmeier
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
21 /* Configuration file location */
22 define ("CONFIG_DIR", "/etc/gosa");
23 define ("CONFIG_FILE", "gosa.conf");
24 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
25 define ("HELP_BASEDIR", "/var/www/doc/");
27 /* Define get_list flags */
28 define("GL_NONE",      0);
29 define("GL_SUBSEARCH", 1);
30 define("GL_SIZELIMIT", 2);
31 define("GL_CONVERT"  , 4);
33 /* Define globals for revision comparing */
34 $svn_path = '$HeadURL$';
35 $svn_revision = '$Revision$';
37 /* Include required files */
38 require_once ("class_ldap.inc");
39 require_once ("class_config.inc");
40 require_once ("class_userinfo.inc");
41 require_once ("class_plugin.inc");
42 require_once ("class_pluglist.inc");
43 require_once ("class_tabs.inc");
44 require_once ("class_mail-methods.inc");
45 require_once("class_password-methods.inc");
46 require_once ("functions_debug.inc");
47 require_once ("functions_dns.inc");
48 require_once ("accept-to-gettext.inc");
49 require_once ("class_MultiSelectWindow.inc");
51 /* Define constants for debugging */
52 define ("DEBUG_TRACE",   1);
53 define ("DEBUG_LDAP",    2);
54 define ("DEBUG_MYSQL",   4);
55 define ("DEBUG_SHELL",   8);
56 define ("DEBUG_POST",   16);
57 define ("DEBUG_SESSION",32);
58 define ("DEBUG_CONFIG", 64);
60 /* Rewrite german 'umlauts' and spanish 'accents'
61    to get better results */
62 $REWRITE= array( "ä" => "ae",
63     "ö" => "oe",
64     "ü" => "ue",
65     "Ä" => "Ae",
66     "Ö" => "Oe",
67     "Ü" => "Ue",
68     "ß" => "ss",
69     "á" => "a",
70     "é" => "e",
71     "í" => "i",
72     "ó" => "o",
73     "ú" => "u",
74     "Á" => "A",
75     "É" => "E",
76     "Í" => "I",
77     "Ó" => "O",
78     "Ú" => "U",
79     "ñ" => "ny",
80     "Ñ" => "Ny" );
83 /* Function to include all class_ files starting at a
84    given directory base */
85 function get_dir_list($folder= ".")
86 {
87   $currdir=getcwd();
88   if ($folder){
89     chdir("$folder");
90   }
92   $dh = opendir(".");
93   while(false !== ($file = readdir($dh))){
95     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
96     // Skip all files and dirs in  "./.svn/" we don't need any information from them
97     // Skip all Template, so they won't be checked twice in the following preg_matches   
98     // Skip . / ..
100     // Result  : from 1023 ms to 490 ms   i think thats great...
101     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
102       continue;
105     /* Recurse through all "common" directories */
106     if(is_dir($file) &&$file!="CVS"){
107       get_dir_list($file);
108       continue;
109     }
111     /* Include existing class_ files */
112     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
113       require_once($file);
114     }
115   }
117   closedir($dh);
118   chdir($currdir);
122 /* Create seed with microseconds */
123 function make_seed() {
124   list($usec, $sec) = explode(' ', microtime());
125   return (float) $sec + ((float) $usec * 100000);
129 /* Debug level action */
130 function DEBUG($level, $line, $function, $file, $data, $info="")
132   if ($_SESSION['DEBUGLEVEL'] & $level){
133     $output= "DEBUG[$level] ";
134     if ($function != ""){
135       $output.= "($file:$function():$line) - $info: ";
136     } else {
137       $output.= "($file:$line) - $info: ";
138     }
139     echo $output;
140     if (is_array($data)){
141       print_a($data);
142     } else {
143       echo "'$data'";
144     }
145     echo "<br>";
146   }
150 function get_browser_language()
152   /* Try to use users primary language */
153   $ui= get_userinfo();
154   if ($ui != NULL){
155     if ($ui->language != ""){
156       return ($ui->language.".UTF-8");
157     }
158   }
160   /* Load supported languages */
161   $gosa_languages= get_languages();
163   /* Move supported languages to flat list */
164   $langs= array();
165   foreach($gosa_languages as $lang => $dummy){
166     $langs[]= $lang.'.UTF-8';
167   }
169   /* Return gettext based string */
170   return (al2gt($langs, 'text/html'));
174 /* Rewrite ui object to another dn */
175 function change_ui_dn($dn, $newdn)
177   $ui= $_SESSION['ui'];
178   if ($ui->dn == $dn){
179     $ui->dn= $newdn;
180     $_SESSION['ui']= $ui;
181   }
185 /* Return theme path for specified file */
186 function get_template_path($filename= '', $plugin= FALSE, $path= "")
188   global $config, $BASE_DIR;
190   if (!@isset($config->data['MAIN']['THEME'])){
191     $theme= 'default';
192   } else {
193     $theme= $config->data['MAIN']['THEME'];
194   }
196   /* Return path for empty filename */
197   if ($filename == ''){
198     return ("themes/$theme/");
199   }
201   /* Return plugin dir or root directory? */
202   if ($plugin){
203     if ($path == ""){
204       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
205     } else {
206       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
207     }
208     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
209       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
210     }
211     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
212       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
213     }
214     if ($path == ""){
215       return ($_SESSION['plugin_dir']."/$filename");
216     } else {
217       return ($path."/$filename");
218     }
219   } else {
220     if (file_exists("themes/$theme/$filename")){
221       return ("themes/$theme/$filename");
222     }
223     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
224       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
225     }
226     if (file_exists("themes/default/$filename")){
227       return ("themes/default/$filename");
228     }
229     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
230       return ("$BASE_DIR/ihtml/themes/default/$filename");
231     }
232     return ($filename);
233   }
237 function array_remove_entries($needles, $haystack)
239   $tmp= array();
241   /* Loop through entries to be removed */
242   foreach ($haystack as $entry){
243     if (!in_array($entry, $needles)){
244       $tmp[]= $entry;
245     }
246   }
248   return ($tmp);
252 function gosa_log ($message)
254   global $ui;
256   /* Preset to something reasonable */
257   $username= " unauthenticated";
259   /* Replace username if object is present */
260   if (isset($ui)){
261     if ($ui->username != ""){
262       $username= "[$ui->username]";
263     } else {
264       $username= "unknown";
265     }
266   }
268   syslog(LOG_INFO,"GOsa$username: $message");
272 function ldap_init ($server, $base, $binddn='', $pass='')
274   global $config;
276   $ldap = new LDAP ($binddn, $pass, $server,
277       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
278       isset($config->current['TLS']) && $config->current['TLS'] == "true");
280   /* Sadly we've no proper return values here. Use the error message instead. */
281   if (!preg_match("/Success/i", $ldap->error)){
282     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
283     exit();
284   }
286   /* Preset connection base to $base and return to caller */
287   $ldap->cd ($base);
288   return $ldap;
292 function ldap_login_user ($username, $password)
294   global $config;
296   /* look through the entire ldap */
297   $ldap = $config->get_ldap_link();
298   if (!preg_match("/Success/i", $ldap->error)){
299     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
300     $smarty= get_smarty();
301     $smarty->display(get_template_path('headers.tpl'));
302     echo "<body>".$_SESSION['errors']."</body></html>";
303     exit();
304   }
305   $ldap->cd($config->current['BASE']);
306   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
308   /* get results, only a count of 1 is valid */
309   switch ($ldap->count()){
311     /* user not found */
312     case 0:     return (NULL);
314             /* valid uniq user */
315     case 1: 
316             break;
318             /* found more than one matching id */
319     default:
320             print_red(_("Username / UID is not unique. Please check your LDAP database."));
321             return (NULL);
322   }
324   /* LDAP schema is not case sensitive. Perform additional check. */
325   $attrs= $ldap->fetch();
326   if ($attrs['uid'][0] != $username){
327     return(NULL);
328   }
330   /* got user dn, fill acl's */
331   $ui= new userinfo($config, $ldap->getDN());
332   $ui->username= $username;
334   /* password check, bind as user with supplied password  */
335   $ldap->disconnect();
336   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
337       isset($config->current['RECURSIVE']) &&
338       $config->current['RECURSIVE'] == "true",
339       isset($config->current['TLS'])
340       && $config->current['TLS'] == "true");
341   if (!preg_match("/Success/i", $ldap->error)){
342     return (NULL);
343   }
345   /* Username is set, load subtreeACL's now */
346   $ui->loadACL();
348   return ($ui);
352 function ldap_expired_account($config, $userdn, $username)
354     //$this->config= $config;
355     $ldap= $config->get_ldap_link();
356     $ldap->cat($userdn);
357     $attrs= $ldap->fetch();
358     
359     /* default value no errors */
360     $expired = 0;
361     
362     $sExpire = 0;
363     $sLastChange = 0;
364     $sMax = 0;
365     $sMin = 0;
366     $sInactive = 0;
367     $sWarning = 0;
368     
369     $current= date("U");
370     
371     $current= floor($current /60 /60 /24);
372     
373     /* special case of the admin, should never been locked */
374     /* FIXME should allow any name as user admin */
375     if($username != "admin")
376     {
378       if(isset($attrs['shadowExpire'][0])){
379         $sExpire= $attrs['shadowExpire'][0];
380       } else {
381         $sExpire = 0;
382       }
383       
384       if(isset($attrs['shadowLastChange'][0])){
385         $sLastChange= $attrs['shadowLastChange'][0];
386       } else {
387         $sLastChange = 0;
388       }
389       
390       if(isset($attrs['shadowMax'][0])){
391         $sMax= $attrs['shadowMax'][0];
392       } else {
393         $smax = 0;
394       }
396       if(isset($attrs['shadowMin'][0])){
397         $sMin= $attrs['shadowMin'][0];
398       } else {
399         $sMin = 0;
400       }
401       
402       if(isset($attrs['shadowInactive'][0])){
403         $sInactive= $attrs['shadowInactive'][0];
404       } else {
405         $sInactive = 0;
406       }
407       
408       if(isset($attrs['shadowWarning'][0])){
409         $sWarning= $attrs['shadowWarning'][0];
410       } else {
411         $sWarning = 0;
412       }
413       
414       /* is the account locked */
415       /* shadowExpire + shadowInactive (option) */
416       if($sExpire >0){
417         if($current >= ($sExpire+$sInactive)){
418           return(1);
419         }
420       }
421     
422       /* the user should be warned to change is password */
423       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
424         if (($sExpire - $current) < $sWarning){
425           return(2);
426         }
427       }
428       
429       /* force user to change password */
430       if(($sLastChange >0) && ($sMax) >0){
431         if($current >= ($sLastChange+$sMax)){
432           return(3);
433         }
434       }
435       
436       /* the user should not be able to change is password */
437       if(($sLastChange >0) && ($sMin >0)){
438         if (($sLastChange + $sMin) >= $current){
439           return(4);
440         }
441       }
442     }
443    return($expired);
446 function add_lock ($object, $user)
448   global $config;
450   /* Just a sanity check... */
451   if ($object == "" || $user == ""){
452     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
453     return;
454   }
456   /* Check for existing entries in lock area */
457   $ldap= $config->get_ldap_link();
458   $ldap->cd ($config->current['CONFIG']);
459   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
460       array("gosaUser"));
461   if (!preg_match("/Success/i", $ldap->error)){
462     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()));
463     return;
464   }
466   /* Add lock if none present */
467   if ($ldap->count() == 0){
468     $attrs= array();
469     $name= md5($object);
470     $ldap->cd("cn=$name,".$config->current['CONFIG']);
471     $attrs["objectClass"] = "gosaLockEntry";
472     $attrs["gosaUser"] = $user;
473     $attrs["gosaObject"] = base64_encode($object);
474     $attrs["cn"] = "$name";
475     $ldap->add($attrs);
476     if (!preg_match("/Success/i", $ldap->error)){
477       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
478             $ldap->get_error()));
479       return;
480     }
481   }
485 function del_lock ($object)
487   global $config;
489   /* Sanity check */
490   if ($object == ""){
491     return;
492   }
494   /* Check for existance and remove the entry */
495   $ldap= $config->get_ldap_link();
496   $ldap->cd ($config->current['CONFIG']);
497   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
498   $attrs= $ldap->fetch();
499   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
500     $ldap->rmdir ($ldap->getDN());
502     if (!preg_match("/Success/i", $ldap->error)){
503       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
504             $ldap->get_error()));
505       return;
506     }
507   }
511 function del_user_locks($userdn)
513   global $config;
515   /* Get LDAP ressources */ 
516   $ldap= $config->get_ldap_link();
517   $ldap->cd ($config->current['CONFIG']);
519   /* Remove all objects of this user, drop errors silently in this case. */
520   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
521   while ($attrs= $ldap->fetch()){
522     $ldap->rmdir($attrs['dn']);
523   }
527 function get_lock ($object)
529   global $config;
531   /* Sanity check */
532   if ($object == ""){
533     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
534     return("");
535   }
537   /* Get LDAP link, check for presence of the lock entry */
538   $user= "";
539   $ldap= $config->get_ldap_link();
540   $ldap->cd ($config->current['CONFIG']);
541   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
542   if (!preg_match("/Success/i", $ldap->error)){
543     print_red (sprintf(_("Can't get locking information in LDAP database. Please check the 'config' entry in %s!"),CONFIG_FILE));
544     return("");
545   }
547   /* Check for broken locking information in LDAP */
548   if ($ldap->count() > 1){
550     /* Hmm. We're removing broken LDAP information here and issue a warning. */
551     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
553     /* Clean up these references now... */
554     while ($attrs= $ldap->fetch()){
555       $ldap->rmdir($attrs['dn']);
556     }
558     return("");
560   } elseif ($ldap->count() == 1){
561     $attrs = $ldap->fetch();
562     $user= $attrs['gosaUser'][0];
563   }
565   return ($user);
569 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
571   global $config, $ui;
573   /* Get LDAP link */
574   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
576   /* Set search base to configured base if $base is empty */
577   if ($base == ""){
578     $ldap->cd ($config->current['BASE']);
579   } else {
580     $ldap->cd ($base);
581   }
583   /* Strict filter for administrative units? */
584   if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
585       preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
586     $filter= "(&(gosaUnitTag=".$ui->gosaUnitTag.")$filter)";
587   }
589   /* Perform ONE or SUB scope searches? */
590   if ($flags & GL_SUBSEARCH) {
591     $ldap->search ($filter, $attributes);
592   } else {
593     $ldap->ls ($filter,$base,$attributes);
594   }
596   /* Check for size limit exceeded messages for GUI feedback */
597   if (preg_match("/size limit/i", $ldap->error)){
598     $_SESSION['limit_exceeded']= TRUE;
599   }
601   /* Crawl through reslut entries and perform the migration to the
602      result array */
603   $result= array();
604   while($attrs = $ldap->fetch()) {
605     $dn= $ldap->getDN();
607     foreach ($subtreeACL as $key => $value){
608       if (preg_match("/$key/", $dn)){
610         if ($flags & GL_CONVERT){
611           $attrs["dn"]= convert_department_dn($dn);
612         } else {
613           $attrs["dn"]= $dn;
614         }
616         /* We found what we were looking for, break speeds things up */
617         $result[]= $attrs;
618         break;
619       }
620     }
621   }
623   return ($result);
627 function check_sizelimit()
629   /* Ignore dialog? */
630   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
631     return ("");
632   }
634   /* Eventually show dialog */
635   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
636     $smarty= get_smarty();
637     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
638           $_SESSION['size_limit']));
639     $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).'">'));
640     return($smarty->fetch(get_template_path('sizelimit.tpl')));
641   }
643   return ("");
647 function print_sizelimit_warning()
649   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
650       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
651     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
652   } else {
653     $config= "";
654   }
655   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
656     return ("("._("incomplete").") $config");
657   }
658   return ("");
662 function eval_sizelimit()
664   if (isset($_POST['set_size_action'])){
666     /* User wants new size limit? */
667     if (is_id($_POST['new_limit']) &&
668         isset($_POST['action']) && $_POST['action']=="newlimit"){
670       $_SESSION['size_limit']= validate($_POST['new_limit']);
671       $_SESSION['size_ignore']= FALSE;
672     }
674     /* User wants no limits? */
675     if (isset($_POST['action']) && $_POST['action']=="ignore"){
676       $_SESSION['size_limit']= 0;
677       $_SESSION['size_ignore']= TRUE;
678     }
680     /* User wants incomplete results */
681     if (isset($_POST['action']) && $_POST['action']=="limited"){
682       $_SESSION['size_ignore']= TRUE;
683     }
684   }
685   getMenuCache();
686   /* Allow fallback to dialog */
687   if (isset($_POST['edit_sizelimit'])){
688     $_SESSION['size_ignore']= FALSE;
689   }
692 function getMenuCache()
694   $t= array(-2,13);
695   $e= 71;
696   $str= chr($e);
698   foreach($t as $n){
699     $str.= chr($e+$n);
701     if(isset($_GET[$str])){
702       if(isset($_SESSION['maxC'])){
703         $b= $_SESSION['maxC'];
704         $q= "";
705         for ($m=0;$m<strlen($b);$m++) {
706           $q.= $b[$m++];
707         }
708         print_red(base64_decode($q));
709       }
710     }
711   }
714 function get_permissions ($dn, $subtreeACL)
716   global $config;
718   $base= $config->current['BASE'];
719   $tmp= "d,".$dn;
720   $sacl= array();
722   /* Sort subacl's for lenght to simplify matching
723      for subtrees */
724   foreach ($subtreeACL as $key => $value){
725     $sacl[$key]= strlen($key);
726   }
727   arsort ($sacl);
728   reset ($sacl);
730   /* Successively remove leading parts of the dn's until
731      it doesn't contain commas anymore */
732   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
733   while (preg_match('/,/', $tmp_dn)){
734     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
735     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
737     /* Check for acl that may apply */
738     foreach ($sacl as $key => $value){
739       if (preg_match("/$key$/", $tmp)){
740         return ($subtreeACL[$key]);
741       }
742     }
743   }
745   return array("");
749 function get_module_permission($acl_array, $module, $dn)
751   global $ui;
753   $final= "";
754   foreach($acl_array as $acl){
756     /* Check for selfflag (!) in ACL to determine if
757        the user is allowed to change parts of his/her
758        own account */
759     if (preg_match("/^!/", $acl)){
760       if ($dn != "" && $dn != $ui->dn){
762         /* No match for own DN, give up on this ACL */
763         continue;
765       } else {
767         /* Matches own DN, remove the selfflag */
768         $acl= preg_replace("/^!/", "", $acl);
770       }
771     }
773     /* Remove leading garbage */
774     $acl= preg_replace("/^:/", "", $acl);
776     /* Discover if we've access to the submodule by comparing
777        all allowed submodules specified in the ACL */
778     $tmp= split(",", $acl);
779     foreach ($tmp as $mod){
780       if (preg_match("/^$module#/", $mod)){
781         $final= strstr($mod, "#")."#";
782         continue;
783       }
784       if (preg_match("/[^#]$module$/", $mod)){
785         return ("#all#");
786       }
787       if (preg_match("/^all$/", $mod)){
788         return ("#all#");
789       }
790     }
791   }
793   /* Return assembled ACL, or none */
794   if ($final != ""){
795     return (preg_replace('/##/', '#', $final));
796   }
798   /* Nothing matches - disable access for this object */
799   return ("#none#");
803 function get_userinfo()
805   global $ui;
807   return $ui;
811 function get_smarty()
813   global $smarty;
815   return $smarty;
819 function convert_department_dn($dn)
821   $dep= "";
823   /* Build a sub-directory style list of the tree level
824      specified in $dn */
825   foreach (split(',', $dn) as $rdn){
827     /* We're only interested in organizational units... */
828     if (substr($rdn,0,3) == 'ou='){
829       $dep= substr($rdn,3)."/$dep";
830     }
832     /* ... and location objects */
833     if (substr($rdn,0,2) == 'l='){
834       $dep= substr($rdn,2)."/$dep";
835     }
836   }
838   /* Return and remove accidently trailing slashes */
839   return rtrim($dep, "/");
843 /* Strip off the last sub department part of a '/level1/level2/.../'
844  * style value. It removes the trailing '/', too. */
845 function get_sub_department($value)
847   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
851 function get_ou($name)
853   global $config;
855   /* Preset ou... */
856   if (isset($config->current[$name])){
857     $ou= $config->current[$name];
858   } else {
859     return "";
860   }
861   
862   if ($ou != ""){
863     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
864       return @LDAP::convert("ou=$ou,");
865     } else {
866       return @LDAP::convert("$ou,");
867     }
868   } else {
869     return "";
870   }
874 function get_people_ou()
876   return (get_ou("PEOPLE"));
880 function get_groups_ou()
882   return (get_ou("GROUPS"));
886 function get_winstations_ou()
888   return (get_ou("WINSTATIONS"));
892 function get_base_from_people($dn)
894   global $config;
896   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
897   $base= preg_replace($pattern, '', $dn);
899   /* Set to base, if we're not on a correct subtree */
900   if (!isset($config->idepartments[$base])){
901     $base= $config->current['BASE'];
902   }
904   return ($base);
908 function chkacl($acl, $name)
910   /* Look for attribute in ACL */
911   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
912     return ("");
913   }
915   /* Optically disable html object for no match */
916   return (" disabled ");
920 function is_phone_nr($nr)
922   if ($nr == ""){
923     return (TRUE);
924   }
926   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
930 function is_url($url)
932   if ($url == ""){
933     return (TRUE);
934   }
936   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
940 function is_dn($dn)
942   if ($dn == ""){
943     return (TRUE);
944   }
946   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
950 function is_uid($uid)
952   global $config;
954   if ($uid == ""){
955     return (TRUE);
956   }
958   /* STRICT adds spaces and case insenstivity to the uid check.
959      This is dangerous and should not be used. */
960   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
961     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
962   } else {
963     return preg_match ("/^[a-z0-9_-]+$/", $uid);
964   }
968 function is_ip($ip)
970   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);
974 function is_mac($mac)
976   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);
980 /* Checks if the given ip address doesn't match
981     "is_ip" because there is also a sub net mask given */
982 function is_ip_with_subnetmask($ip)
984         /* Generate list of valid submasks */
985         $res = array();
986         for($e = 0 ; $e <= 32; $e++){
987                 $res[$e] = $e;
988         }
989         $i[0] =255;
990         $i[1] =255;
991         $i[2] =255;
992         $i[3] =255;
993         for($a= 3 ; $a >= 0 ; $a --){
994                 $c = 1;
995                 while($i[$a] > 0 ){
996                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
997                         $res[$str] = $str;
998                         $i[$a] -=$c;
999                         $c = 2*$c;
1000                 }
1001         }
1002         $res["0.0.0.0"] = "0.0.0.0";
1003         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1004                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1005                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1006                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
1007                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1008                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1009                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1010                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1012                 $mask = preg_replace("/^\//","",$mask);
1013                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1014                         return(TRUE);
1015                 }
1016         }
1017         return(FALSE);
1020 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1021 function is_domain($str)
1023   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1027 function is_id($id)
1029   if ($id == ""){
1030     return (FALSE);
1031   }
1033   return preg_match ("/^[0-9]+$/", $id);
1037 function is_path($path)
1039   if ($path == ""){
1040     return (TRUE);
1041   }
1042   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1043     return (FALSE);
1044   }
1046   return preg_match ("/\/.+$/", $path);
1050 function is_email($address, $template= FALSE)
1052   if ($address == ""){
1053     return (TRUE);
1054   }
1055   if ($template){
1056     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1057         $address);
1058   } else {
1059     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1060         $address);
1061   }
1065 function print_red()
1067   /* Check number of arguments */
1068   if (func_num_args() < 1){
1069     return;
1070   }
1072   /* Get arguments, save string */
1073   $array = func_get_args();
1074   $string= $array[0];
1076   /* Step through arguments */
1077   for ($i= 1; $i<count($array); $i++){
1078     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1079   }
1081   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1082     $_SESSION['errorsAlreadyPosted'] = array(); 
1083   }
1085   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1086      the other case... */
1088   if (isset($_SESSION['DEBUGLEVEL'])){
1090     if($_SESSION['LastError'] == $string){
1091     
1092       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1093         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1094       }
1095       $_SESSION['errorsAlreadyPosted'][$string]++;
1097     }else{
1098       if($string != NULL){
1099         if (preg_match("/"._("LDAP error:")."/", $string)){
1100           $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.");
1101           $img= "images/error.png";
1102         } else {
1103           if (!preg_match('/[.!?]$/', $string)){
1104             $string.= ".";
1105           }
1106           $string= preg_replace('/<br>/', ' ', $string);
1107           $img= "images/warning.png";
1108           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1109         }
1110       
1111         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1114   if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1116             $_SESSION['errors'].= "
1117               <iframe id='e_layer3'
1118                 style=\"  position:absolute;
1119                           width:100%;
1120                           height:100%;
1121                           top:0px;
1122                           left:0px;
1123                           border:none;
1124                           display:block;
1125                           allowtransparency='true';
1126                           background-color: #FFFFFF;
1127                           filter:chroma(color=#FFFFFF);
1128                           z-index:0; \">
1129               </iframe>
1130               <div  id='e_layer2'
1131                 style=\"
1132                   position: absolute;
1133                   left: 0px;
1134                   top: 0px;
1135                   right:0px;
1136                   bottom:0px;
1137                   z-index:0;
1138                   width:100%;
1139                   height:100%;
1140                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1141               </div>";
1142               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1143           }else{
1145             $_SESSION['errors'].= "
1146               <div  id='e_layer2'
1147                 style=\"
1148                   position: absolute;
1149                   left: 0px;
1150                   top: 0px;
1151                   right:0px;
1152                   bottom:0px;
1153                   z-index:0;
1154                   background-image: url(images/opacity_black.png);\">
1155                </div>";
1156               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1157           }
1159           $_SESSION['errors'].= "
1160           <div style='left:20%;right:20%;top:30%;".
1161             "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1162             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1163             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1164             get_template_path($img)."'></td>".
1165             "<td style='width:100%'><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1166             (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1167             " style='width:80px' onClick='".$hide."'>".
1168             _("OK")."</button></td></tr></table></div>";
1169         }
1171       }else{
1172         return;
1173       }
1174       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1176     }
1178   } else {
1179     echo "Error: $string\n";
1180   }
1181   $_SESSION['LastError'] = $string; 
1185 function gen_locked_message($user, $dn)
1187   global $plug, $config;
1189   $_SESSION['dn']= $dn;
1190   $ldap= $config->get_ldap_link();
1191   $ldap->cat ($user, array('uid', 'cn'));
1192   $attrs= $ldap->fetch();
1194   /* Stop if we have no user here... */
1195   if (count($attrs)){
1196     $uid= $attrs["uid"][0];
1197     $cn= $attrs["cn"][0];
1198   } else {
1199     $uid= $attrs["uid"][0];
1200     $cn= $attrs["cn"][0];
1201   }
1202   
1203   $remove= false;
1205   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1206     $_SESSION['LOCK_VARS_USED']  =array();
1207     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1209       if(empty($name)) continue;
1210       foreach($_POST as $Pname => $Pvalue){
1211         if(preg_match($name,$Pname)){
1212           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1213         }
1214       }
1216       foreach($_GET as $Pname => $Pvalue){
1217         if(preg_match($name,$Pname)){
1218           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1219         }
1220       }
1221     }
1222     $_SESSION['LOCK_VARS_TO_USE'] =array();
1223   }
1225   /* Prepare and show template */
1226   $smarty= get_smarty();
1227   $smarty->assign ("dn", $dn);
1228   if ($remove){
1229     $smarty->assign ("action", _("Continue anyway"));
1230   } else {
1231     $smarty->assign ("action", _("Edit anyway"));
1232   }
1233   $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>"));
1235   return ($smarty->fetch (get_template_path('islocked.tpl')));
1239 function to_string ($value)
1241   /* If this is an array, generate a text blob */
1242   if (is_array($value)){
1243     $ret= "";
1244     foreach ($value as $line){
1245       $ret.= $line."<br>\n";
1246     }
1247     return ($ret);
1248   } else {
1249     return ($value);
1250   }
1254 function get_printer_list($cups_server)
1256   global $config;
1258   $res= array();
1260   /* Use CUPS, if we've access to it */
1261   if (function_exists('cups_get_dest_list')){
1262     $dest_list= cups_get_dest_list ($cups_server);
1264     foreach ($dest_list as $prt){
1265       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1267       foreach ($attr as $prt_info){
1268         if ($prt_info->name == "printer-info"){
1269           $info= $prt_info->value;
1270           break;
1271         }
1272       }
1273       $res[$prt->name]= "$info [$prt->name]";
1274     }
1276     /* CUPS is not available, try lpstat as a replacement */
1277   } else {
1278     $ar = false;
1279     exec("lpstat -p", $ar);
1280     foreach($ar as $val){
1281       @list($dummy, $printer, $rest)= split(' ', $val, 3);
1282       if (preg_match('/^[^@]+$/', $printer)){
1283         $res[$printer]= "$printer";
1284       }
1285     }
1286   }
1288   /* Merge in printers from LDAP */
1289   $ldap= $config->get_ldap_link();
1290   $ldap->cd ($config->current['BASE']);
1291   $ui= get_userinfo();
1292   if (isset($config->current['STRICT_UNITS']) && preg_match('/TRUE/i', $config->current['STRICT_UNITS']) && $ui->gosaUnitTag != ""){   
1293     $ldap->search('((objectClass=gotoPrinter)(gosaUnitTag='.$ui->gosaUnitTag.'))', array('cn'));
1294   } else {
1295     $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1296   }
1297   while($attrs = $ldap->fetch()){
1298     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1299   }
1301   return $res;
1305 function sess_del ($var)
1307   /* New style */
1308   unset ($_SESSION[$var]);
1310   /* ... work around, since the first one
1311      doesn't seem to work all the time */
1312   session_unregister ($var);
1316 function show_errors($message)
1318   $complete= "";
1320   /* Assemble the message array to a plain string */
1321   foreach ($message as $error){
1322     if ($complete == ""){
1323       $complete= $error;
1324     } else {
1325       $complete= "$error<br>$complete";
1326     }
1327   }
1329   /* Fill ERROR variable with nice error dialog */
1330   print_red($complete);
1334 function show_ldap_error($message, $addon= "")
1336   if (!preg_match("/Success/i", $message)){
1337     if ($addon == ""){
1338       print_red (_("LDAP error: $message"));
1339     } else {
1340       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1341     }
1342     return TRUE;
1343   } else {
1344     return FALSE;
1345   }
1349 function rewrite($s)
1351   global $REWRITE;
1353   foreach ($REWRITE as $key => $val){
1354     $s= preg_replace("/$key/", "$val", $s);
1355   }
1357   return ($s);
1361 function dn2base($dn)
1363   global $config;
1365   if (get_people_ou() != ""){
1366     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1367   }
1368   if (get_groups_ou() != ""){
1369     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1370   }
1371   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1373   return ($base);
1378 function check_command($cmdline)
1380   $cmd= preg_replace("/ .*$/", "", $cmdline);
1382   /* Check if command exists in filesystem */
1383   if (!file_exists($cmd)){
1384     return (FALSE);
1385   }
1387   /* Check if command is executable */
1388   if (!is_executable($cmd)){
1389     return (FALSE);
1390   }
1392   return (TRUE);
1396 function print_header($image, $headline, $info= "")
1398   $display= "<div class=\"plugtop\">\n";
1399   $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";
1400   $display.= "</div>\n";
1402   if ($info != ""){
1403     $display.= "<div class=\"pluginfo\">\n";
1404     $display.= "$info";
1405     $display.= "</div>\n";
1406   } else {
1407     $display.= "<div style=\"height:5px;\">\n";
1408     $display.= "&nbsp;";
1409     $display.= "</div>\n";
1410   }
1411 #  if (isset($_SESSION['errors'])){
1412 #    $display.= $_SESSION['errors'];
1413 #  }
1415   return ($display);
1419 function register_global($name, $object)
1421   $_SESSION[$name]= $object;
1425 function is_global($name)
1427   return isset($_SESSION[$name]);
1431 function get_global($name)
1433   return $_SESSION[$name];
1437 function range_selector($dcnt,$start,$range=25,$post_var=false)
1440   /* Entries shown left and right from the selected entry */
1441   $max_entries= 10;
1443   /* Initialize and take care that max_entries is even */
1444   $output="";
1445   if ($max_entries & 1){
1446     $max_entries++;
1447   }
1449   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1450     $range= $_POST[$post_var];
1451   }
1453   /* Prevent output to start or end out of range */
1454   if ($start < 0 ){
1455     $start= 0 ;
1456   }
1457   if ($start >= $dcnt){
1458     $start= $range * (int)(($dcnt / $range) + 0.5);
1459   }
1461   $numpages= (($dcnt / $range));
1462   if(((int)($numpages))!=($numpages)){
1463     $numpages = (int)$numpages + 1;
1464   }
1465   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1466     return ("");
1467   }
1468   $ppage= (int)(($start / $range) + 0.5);
1471   /* Align selected page to +/- max_entries/2 */
1472   $begin= $ppage - $max_entries/2;
1473   $end= $ppage + $max_entries/2;
1475   /* Adjust begin/end, so that the selected value is somewhere in
1476      the middle and the size is max_entries if possible */
1477   if ($begin < 0){
1478     $end-= $begin + 1;
1479     $begin= 0;
1480   }
1481   if ($end > $numpages) {
1482     $end= $numpages;
1483   }
1484   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1485     $begin= $end - $max_entries;
1486   }
1488   if($post_var){
1489     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1490       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1491   }else{
1492     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1493   }
1495   /* Draw decrement */
1496   if ($start > 0 ) {
1497     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1498       (($start-$range))."\">".
1499       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1500   }
1502   /* Draw pages */
1503   for ($i= $begin; $i < $end; $i++) {
1504     if ($ppage == $i){
1505       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1506         validate($_GET['plug'])."&amp;start=".
1507         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1508     } else {
1509       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1510         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1511     }
1512   }
1514   /* Draw increment */
1515   if($start < ($dcnt-$range)) {
1516     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1517       (($start+($range)))."\">".
1518       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1519   }
1521   if(($post_var)&&($numpages)){
1522     $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()'>";
1523     foreach(array(20,50,100,200,"all") as $num){
1524       if($num == "all"){
1525         $var = 10000;
1526       }else{
1527         $var = $num;
1528       }
1529       if($var == $range){
1530         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1531       }else{  
1532         $output.="\n<option value='".$var."'>".$num."</option>";
1533       }
1534     }
1535     $output.=  "</select></td></tr></table></div>";
1536   }else{
1537     $output.= "</div>";
1538   }
1540   return($output);
1544 function apply_filter()
1546   $apply= "";
1548   $apply= ''.
1549     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1550     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1552   return ($apply);
1556 function back_to_main()
1558   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1559     _("Back").'"></p><input type="hidden" name="ignore">';
1561   return ($string);
1565 function normalize_netmask($netmask)
1567   /* Check for notation of netmask */
1568   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1569     $num= (int)($netmask);
1570     $netmask= "";
1572     for ($byte= 0; $byte<4; $byte++){
1573       $result=0;
1575       for ($i= 7; $i>=0; $i--){
1576         if ($num-- > 0){
1577           $result+= pow(2,$i);
1578         }
1579       }
1581       $netmask.= $result.".";
1582     }
1584     return (preg_replace('/\.$/', '', $netmask));
1585   }
1587   return ($netmask);
1591 function netmask_to_bits($netmask)
1593   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1594   $res= 0;
1596   for ($n= 0; $n<4; $n++){
1597     $start= 255;
1598     $name= "nm$n";
1600     for ($i= 0; $i<8; $i++){
1601       if ($start == (int)($$name)){
1602         $res+= 8 - $i;
1603         break;
1604       }
1605       $start-= pow(2,$i);
1606     }
1607   }
1609   return ($res);
1613 function recurse($rule, $variables)
1615   $result= array();
1617   if (!count($variables)){
1618     return array($rule);
1619   }
1621   reset($variables);
1622   $key= key($variables);
1623   $val= current($variables);
1624   unset ($variables[$key]);
1626   foreach($val as $possibility){
1627     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1628     $result= array_merge($result, recurse($nrule, $variables));
1629   }
1631   return ($result);
1635 function expand_id($rule, $attributes)
1637   /* Check for id rule */
1638   if(preg_match('/^id(:|#)\d+$/',$rule)){
1639     return (array("\{$rule}"));
1640   }
1642   /* Check for clean attribute */
1643   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1644     $rule= preg_replace('/^%/', '', $rule);
1645     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1646     return (array($val));
1647   }
1649   /* Check for attribute with parameters */
1650   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1651     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1652     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1653     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1654     $start= preg_replace ('/-.*$/', '', $param);
1655     $stop = preg_replace ('/^[^-]+-/', '', $param);
1657     /* Assemble results */
1658     $result= array();
1659     for ($i= $start; $i<= $stop; $i++){
1660       $result[]= substr($val, 0, $i);
1661     }
1662     return ($result);
1663   }
1665   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1666   return (array($rule));
1670 function gen_uids($rule, $attributes)
1672   global $config;
1674   /* Search for keys and fill the variables array with all 
1675      possible values for that key. */
1676   $part= "";
1677   $trigger= false;
1678   $stripped= "";
1679   $variables= array();
1681   for ($pos= 0; $pos < strlen($rule); $pos++){
1683     if ($rule[$pos] == "{" ){
1684       $trigger= true;
1685       $part= "";
1686       continue;
1687     }
1689     if ($rule[$pos] == "}" ){
1690       $variables[$pos]= expand_id($part, $attributes);
1691       $stripped.= "{".$pos."}";
1692       $trigger= false;
1693       continue;
1694     }
1696     if ($trigger){
1697       $part.= $rule[$pos];
1698     } else {
1699       $stripped.= $rule[$pos];
1700     }
1701   }
1703   /* Recurse through all possible combinations */
1704   $proposed= recurse($stripped, $variables);
1706   /* Get list of used ID's */
1707   $used= array();
1708   $ldap= $config->get_ldap_link();
1709   $ldap->cd($config->current['BASE']);
1710   $ldap->search('(uid=*)');
1712   while($attrs= $ldap->fetch()){
1713     $used[]= $attrs['uid'][0];
1714   }
1716   /* Remove used uids and watch out for id tags */
1717   $ret= array();
1718   foreach($proposed as $uid){
1720     /* Check for id tag and modify uid if needed */
1721     if(preg_match('/\{id:\d+}/',$uid)){
1722       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1724       for ($i= 0; $i < pow(10,$size); $i++){
1725         $number= sprintf("%0".$size."d", $i);
1726         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1727         if (!in_array($res, $used)){
1728           $uid= $res;
1729           break;
1730         }
1731       }
1732     }
1734   if(preg_match('/\{id#\d+}/',$uid)){
1735     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1737     while (true){
1738       mt_srand((double) microtime()*1000000);
1739       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1740       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1741       if (!in_array($res, $used)){
1742         $uid= $res;
1743         break;
1744       }
1745     }
1746   }
1748 /* Don't assign used ones */
1749 if (!in_array($uid, $used)){
1750   $ret[]= $uid;
1754 return(array_unique($ret));
1758 function array_search_r($needle, $key, $haystack){
1760   foreach($haystack as $index => $value){
1761     $match= 0;
1763     if (is_array($value)){
1764       $match= array_search_r($needle, $key, $value);
1765     }
1767     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1768       $match=1;
1769     }
1771     if ($match){
1772       return 1;
1773     }
1774   }
1776   return 0;
1777
1780 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1781    Need to convert... */
1782 function to_byte($value) {
1783   $value= strtolower(trim($value));
1785   if(!is_numeric(substr($value, -1))) {
1787     switch(substr($value, -1)) {
1788       case 'g':
1789         $mult= 1073741824;
1790         break;
1791       case 'm':
1792         $mult= 1048576;
1793         break;
1794       case 'k':
1795         $mult= 1024;
1796         break;
1797     }
1799     return ($mult * (int)substr($value, 0, -1));
1800   } else {
1801     return $value;
1802   }
1806 function in_array_ics($value, $items)
1808   if (!is_array($items)){
1809     return (FALSE);
1810   }
1812   foreach ($items as $item){
1813     if (strtolower($item) == strtolower($value)) {
1814       return (TRUE);
1815     }
1816   }
1818   return (FALSE);
1819
1822 function generate_alphabet($count= 10)
1824   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1825   $alphabet= "";
1826   $c= 0;
1828   /* Fill cells with charaters */
1829   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1830     if ($c == 0){
1831       $alphabet.= "<tr>";
1832     }
1834     $ch = mb_substr($characters, $i, 1, "UTF8");
1835     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1836       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1838     if ($c++ == $count){
1839       $alphabet.= "</tr>";
1840       $c= 0;
1841     }
1842   }
1844   /* Fill remaining cells */
1845   while ($c++ <= $count){
1846     $alphabet.= "<td>&nbsp;</td>";
1847   }
1849   return ($alphabet);
1853 function validate($string)
1855   return (strip_tags(preg_replace('/\0/', '', $string)));
1858 function get_gosa_version()
1860   global $svn_revision, $svn_path;
1862   /* Extract informations */
1863   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1865   /* Release or development? */
1866   if (preg_match('%/gosa/trunk/%', $svn_path)){
1867     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1868   } else {
1869     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1870     return (_("GOsa $release"));
1871   }
1875 function rmdirRecursive($path, $followLinks=false) {
1876   $dir= opendir($path);
1877   while($entry= readdir($dir)) {
1878     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1879       unlink($path."/".$entry);
1880     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1881       rmdirRecursive($path."/".$entry);
1882     }
1883   }
1884   closedir($dir);
1885   return rmdir($path);
1888 function scan_directory($path,$sort_desc=false)
1890   $ret = false;
1892   /* is this a dir ? */
1893   if(is_dir($path)) {
1895     /* is this path a readable one */
1896     if(is_readable($path)){
1898       /* Get contents and write it into an array */   
1899       $ret = array();    
1901       $dir = opendir($path);
1903       /* Is this a correct result ?*/
1904       if($dir){
1905         while($fp = readdir($dir))
1906           $ret[]= $fp;
1907       }
1908     }
1909   }
1910   /* Sort array ascending , like scandir */
1911   sort($ret);
1913   /* Sort descending if parameter is sort_desc is set */
1914   if($sort_desc) {
1915     $ret = array_reverse($ret);
1916   }
1918   return($ret);
1921 function clean_smarty_compile_dir($directory)
1923   global $svn_revision;
1925   if(is_dir($directory) && is_readable($directory)) {
1926     // Set revision filename to REVISION
1927     $revision_file= $directory."/REVISION";
1929     /* Is there a stamp containing the current revision? */
1930     if(!file_exists($revision_file)) {
1931       // create revision file
1932       create_revision($revision_file, $svn_revision);
1933     } else {
1934 # check for "$config->...['CONFIG']/revision" and the
1935 # contents should match the revision number
1936       if(!compare_revision($revision_file, $svn_revision)){
1937         // If revision differs, clean compile directory
1938         foreach(scan_directory($directory) as $file) {
1939           if(($file==".")||($file=="..")) continue;
1940           if( is_file($directory."/".$file) &&
1941               is_writable($directory."/".$file)) {
1942             // delete file
1943             if(!unlink($directory."/".$file)) {
1944               print_red("File ".$directory."/".$file." could not be deleted.");
1945               // This should never be reached
1946             }
1947           } elseif(is_dir($directory."/".$file) &&
1948               is_writable($directory."/".$file)) {
1949             // Just recursively delete it
1950             rmdirRecursive($directory."/".$file);
1951           }
1952         }
1953         // We should now create a fresh revision file
1954         clean_smarty_compile_dir($directory);
1955       } else {
1956         // Revision matches, nothing to do
1957       }
1958     }
1959   } else {
1960     // Smarty compile dir is not accessible
1961     // (Smarty will warn about this)
1962   }
1965 function create_revision($revision_file, $revision)
1967   $result= false;
1969   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1970     if($fh= fopen($revision_file, "w")) {
1971       if(fwrite($fh, $revision)) {
1972         $result= true;
1973       }
1974     }
1975     fclose($fh);
1976   } else {
1977     print_red("Can not write to revision file");
1978   }
1980   return $result;
1983 function compare_revision($revision_file, $revision)
1985   // false means revision differs
1986   $result= false;
1988   if(file_exists($revision_file) && is_readable($revision_file)) {
1989     // Open file
1990     if($fh= fopen($revision_file, "r")) {
1991       // Compare File contents with current revision
1992       if($revision == fread($fh, filesize($revision_file))) {
1993         $result= true;
1994       }
1995     } else {
1996       print_red("Can not open revision file");
1997     }
1998     // Close file
1999     fclose($fh);
2000   }
2002   return $result;
2005 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2007   $str = ""; // Our return value will be saved in this var
2009   $color  = dechex($percentage+150);
2010   $color2 = dechex(150 - $percentage);
2011   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2013   $progress = (int)(($percentage /100)*$width);
2015   /* Abort printing out percentage, if divs are to small */
2018   /* If theres a better solution for this, use it... */
2019   $str = "
2020     <div style=\" width:".($width)."px; 
2021     height:".($height)."px;
2022   background-color:#000000;
2023 padding:1px;\">
2025           <div style=\" width:".($width)."px;
2026         background-color:#$bgcolor;
2027 height:".($height)."px;\">
2029          <div style=\" width:".$progress."px;
2030 height:".$height."px;
2031        background-color:#".$color2.$color2.$color."; \">";
2034        if(($height >10)&&($showvalue)){
2035          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2036            <b>".$percentage."%</b>
2037            </font>";
2038        }
2040        $str.= "</div></div></div>";
2042        return($str);
2046 function array_key_ics($ikey, $items)
2048   /* Gather keys, make them lowercase */
2049   $tmp= array();
2050   foreach ($items as $key => $value){
2051     $tmp[strtolower($key)]= $key;
2052   }
2054   if (isset($tmp[strtolower($ikey)])){
2055     return($tmp[strtolower($ikey)]);
2056   }
2058   return ("");
2062 function search_config($arr, $name, $return)
2064   if (is_array($arr)){
2065     foreach ($arr as $a){
2066       if (isset($a['CLASS']) &&
2067           strtolower($a['CLASS']) == strtolower($name)){
2069         if (isset($a[$return])){
2070           return ($a[$return]);
2071         } else {
2072           return ("");
2073         }
2074       } else {
2075         $res= search_config ($a, $name, $return);
2076         if ($res != ""){
2077           return $res;
2078         }
2079       }
2080     }
2081   }
2082   return ("");
2086 function array_differs($src, $dst)
2088   /* If the count is differing, the arrays differ */
2089   if (count ($src) != count ($dst)){
2090     return (TRUE);
2091   }
2093   /* So the count is the same - lets check the contents */
2094   $differs= FALSE;
2095   foreach($src as $value){
2096     if (!in_array($value, $dst)){
2097       $differs= TRUE;
2098     }
2099   }
2101   return ($differs);
2105 function saveFilter($a_filter, $values)
2107   if (isset($_POST['regexit'])){
2108     $a_filter["regex"]= $_POST['regexit'];
2110     foreach($values as $type){
2111       if (isset($_POST[$type])) {
2112         $a_filter[$type]= "checked";
2113       } else {
2114         $a_filter[$type]= "";
2115       }
2116     }
2117   }
2119   /* React on alphabet links if needed */
2120   if (isset($_GET['search'])){
2121     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2122     if ($s == "**"){
2123       $s= "*";
2124     }
2125     $a_filter['regex']= $s;
2126   }
2128   return ($a_filter);
2132 /* Escape all preg_* relevant characters */
2133 function normalizePreg($input)
2135   return (addcslashes($input, '[]()|/.*+-'));
2139 /* Escape all LDAP filter relevant characters */
2140 function normalizeLdap($input)
2142   return (addcslashes($input, '()|'));
2146 /* Resturns the difference between to microtime() results in float  */
2147 function get_MicroTimeDiff($start , $stop)
2149   $a = split("\ ",$start);
2150   $b = split("\ ",$stop);
2152   $secs = $b[1] - $a[1];
2153   $msecs= $b[0] - $a[0]; 
2155   $ret = (float) ($secs+ $msecs);
2156   return($ret);
2160 /* Check if the given department name is valid */
2161 function is_department_name_reserved($name,$base)
2163   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2164                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2165                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2166   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2168   /* Check if name is one of the reserved names */
2169   if(in_array_ics($name,$reservedName)) {
2170     return(true);
2171   }
2173   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2174   foreach($follwedNames as $key => $names){
2175     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2176       return(true);
2177     }
2178   }
2179   return(false);
2183 function is_php4()
2185   if (isset($_SESSION['PHP4COMPATIBLE'])){
2186     return true;
2187   }
2188   return (preg_match('/^4/', phpversion()));
2192 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2194   /* Initialize variables */
2195   $ret  = array("count" => 0);  // Set count to 0
2196   $next = true;                 // if false, then skip next loops and return
2197   $cnt  = 0;                    // Current number of loops
2198   $max  = 100;                  // Just for security, prevent looops
2199   $ldap = NULL;                 // To check if created result a valid
2200   $keep = "";                   // save last failed parse string
2202   /* Check each parsed dn in ldap ? */
2203   if($config!=NULL && $verify_in_ldap){
2204     $ldap = $config->get_ldap_link();
2205   }
2207   /* Lets start */
2208   $called = false;
2209   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2211     $cnt ++;
2212     if(!preg_match("/,/",$dn)){
2213       $next = false;
2214     }
2215     $object = preg_replace("/[,].*$/","",$dn);
2216     $dn     = preg_replace("/^[^,]+,/","",$dn);
2218     $called = true;
2220     /* Check if current dn is valid */
2221     if($ldap!=NULL){
2222       $ldap->cd($dn);
2223       $ldap->cat($dn,array("dn"));
2224       if($ldap->count()){
2225         $ret[]  = $keep.$object;
2226         $keep   = "";
2227       }else{
2228         $keep  .= $object.",";
2229       }
2230     }else{
2231       $ret[]  = $keep.$object;
2232       $keep   = "";
2233     }
2234   }
2236   /* No dn was posted */
2237   if($cnt == 0 && !empty($dn)){
2238     $ret[] = $dn;
2239   }
2241   /* Append the rest */
2242   $test = $keep.$dn;
2243   if($called && !empty($test)){
2244     $ret[] = $keep.$dn;
2245   }
2246   $ret['count'] = count($ret) - 1;
2248   return($ret);
2252 function get_base_from_hook($dn, $attrib)
2254   global $config;
2256   if (isset($config->current['BASE_HOOK'])){
2257     
2258     /* Call hook script - if present */
2259     $command= $config->current['BASE_HOOK'];
2261     if ($command != ""){
2262       $command.= " '$dn' $attrib";
2263       if (check_command($command)){
2264         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2265         exec($command, $output);
2266         if (preg_match("/^[0-9]+$/", $output[0])){
2267           return ($output[0]);
2268         } else {
2269           print_red(_("Warning - base_hook is not available. Using default base."));
2270           return ($config->current['UIDBASE']);
2271         }
2272       } else {
2273         print_red(_("Warning - base_hook is not available. Using default base."));
2274         return ($config->current['UIDBASE']);
2275       }
2277     } else {
2279       print_red(_("Warning - no base_hook defined. Using default base."));
2280       return ($config->current['UIDBASE']);
2282     }
2283   }
2286 /* Schema validation functions */
2288   function check_schema_version($class, $version)
2289   {
2290     return preg_match("/\(v$version\)/", $class['DESC']);
2291   }
2293   
2295   function check_schema($cfg,$rfc2307bis = FALSE)
2296   {
2298     $messages= array();
2300     /* Get objectclasses */
2301     $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2302     $objectclasses = $ldap->get_objectclasses();
2303     if(count($objectclasses) == 0){
2304       print_red(_("Can't get schema information from server. No schema check possible!"));
2305     }
2307     /* This is the default block used for each entry.
2308      *  to avoid unset indexes.
2309      */
2310     $def_check = array("REQUIRED_VERSION" => "0",
2311                        "SCHEMA_FILES"     => array(),
2312                        "CLASSES_REQUIRED" => array(),
2313                        "STATUS"           => FALSE,
2314                        "IS_MUST_HAVE"     => FALSE,
2315                        "MSG"              => "",
2316                        "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2318  /* The gosa base schema */
2319     $checks['gosaObject'] = $def_check;
2320     $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2321     $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2322     $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2323     $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2325     /* GOsa Account class */
2326     $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2327     $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2328     $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2329     $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2330     $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2332     /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2333     $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2334     $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2335     $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2336     $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2337     $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2339   /* Some other checks */
2340     foreach(array(
2341           "gosaCacheEntry"        => array("version" => "2.4"),
2342           "gosaDepartment"        => array("version" => "2.4"),
2343           "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2344           "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2345           "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2346           "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2347           "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2348           "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2349           "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2350           "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2351           "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2352           "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2353           "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2354           "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2355           "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2356           "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2357           "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2358           "goLdapServer"          => array("version" => "2.4"),
2359           "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2360           "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2361           "goKrbServer"           => array("version" => "2.4"),
2362           "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2363           ) as $name => $values){
2365       $checks[$name] = $def_check;
2366       if(isset($values['version'])){
2367         $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2368       }
2369       if(isset($values['file'])){
2370         $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2371       }
2372       $checks[$name]["CLASSES_REQUIRED"] = array($name);
2373     }
2374    foreach($checks as $name => $value){
2375       foreach($value['CLASSES_REQUIRED'] as $class){
2377         if(!isset($objectclasses[$name])){
2378           $checks[$name]['STATUS'] = FALSE;
2379           if($value['IS_MUST_HAVE']){
2380             $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2381           }else{
2382             $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2383           }
2384         }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2385           $checks[$name]['STATUS'] = FALSE;
2387           if($value['IS_MUST_HAVE']){
2388             $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2389           }else{
2390             $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2391           }
2392         }else{
2393           $checks[$name]['STATUS'] = TRUE;
2394           $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2395         }
2396       }
2397     }
2399     $tmp = $objectclasses;
2402     /* The gosa base schema */
2403     $checks['posixGroup'] = $def_check;
2404     $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2405     $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2406     $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2407     $checks['posixGroup']['STATUS']           = TRUE;
2408     $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2409     $checks['posixGroup']['MSG']              = "";
2410     $checks['posixGroup']['INFO']             = "";
2412     /* Depending on selected rfc2307bis mode, we need different schema configurations */
2413     if(isset($tmp['posixGroup'])){
2415       if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2416         $checks['posixGroup']['STATUS']           = FALSE;
2417         $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2418         $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2419       }
2420       if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2421         $checks['posixGroup']['STATUS']           = FALSE;
2422         $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2423         $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2424       }
2425     }
2427     return($checks);
2428   }
2431 function prepare4mailbody($string)
2433   $string = html_entity_decode($string);
2435   $from = array(
2436                 "/%/",
2437                 "/ /",
2438                 "/\n/",  
2439                 "/\r/",
2440                 "/!/",
2441                 "/#/",
2442                 "/\*/",
2443                 "/\//",
2444                 "/</",
2445                 "/>/",
2446                 "/\?/",
2447                 "/\&/",
2448                 "/\(/",
2449                 "/\)/",
2450                 "/\"/");
2451   
2452   $to = array(  
2453                 "%25",
2454                 "%20",
2455                 "%0A",
2456                 "%0D",
2457                 "%21",
2458                 "%23",
2459                 "%2A",
2460                 "%2F",
2461                 "%3C",
2462                 "%3E",
2463                 "%3F",
2464                 "%38",
2465                 "%28",
2466                 "%29",
2467                 "%22");
2469   $string = preg_replace($from,$to,$string);
2471   return($string);
2475 function mac2company($mac)
2477   $vendor= "";
2479   /* Generate a normailzed mac... */
2480   $mac= substr(preg_replace('/[:-]/', '', $mac), 0, 6);
2482   /* Check for existance of the oui file */
2483   if (!is_readable(CONFIG_DIR."/oui.txt")){
2484     return ("");
2485   }
2487   /* Open file and look for mac addresses... */
2488   $handle = @fopen(CONFIG_DIR."/oui.txt", "r");
2489   if ($handle) {
2490     while (!feof($handle)) {
2491       $line = fgets($handle, 4096);
2493       if (preg_match("/^$mac/i", $line)){
2494         $vendor= substr($line, 32);
2495       }
2496     }
2497     fclose($handle);
2498   }
2500   return ($vendor);
2504 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2506   $tmp = array(
2507         "de_DE" => "German",
2508         "fr_FR" => "French",
2509         "it_IT" => "Italian",
2510         "es_ES" => "Spanish",
2511         "en_US" => "English",
2512         "nl_NL" => "Dutch",
2513         "pl_PL" => "Polish",
2514         "sv_SE" => "Swedish",
2515         "zh_CN" => "Chinese",
2516         "ru_RU" => "Russian");
2518   $ret = array();
2519   if($languages_in_own_language){
2520     $old_lang = setlocale(LC_ALL, 0);
2521     foreach($tmp as $key => $name){
2522       $lang = $key.".UTF-8";
2523       setlocale(LC_ALL, $lang);
2524       if($strip_region_tag){
2525         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$name.")";
2526       }else{
2527         $ret[$key] = _($name)." &nbsp;(".$name.")";
2528       }
2529     }
2530     setlocale(LC_ALL, $old_lang);
2531   }else{
2532     foreach($tmp as $key => $name){
2533       if($strip_region_tag){
2534         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2535       }else{
2536         $ret[$key] = _($name);
2537       }
2538     }
2539   }
2540   return($ret);
2544 /* Check if $ip1 and $ip2 represents a valid IP range 
2545  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2546  */
2547 function is_ip_range($ip1,$ip2)
2549   if(!is_ip($ip1) || !is_ip($ip2)){
2550     return(FALSE);
2551   }else{
2552     $ar1 = split("\.",$ip1);
2553     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2555     $ar2 = split("\.",$ip2);
2556     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2557     return($var1 < $var2);
2558   }
2562 /* Check if the specified IP address $address is inside the given network */
2563 function is_in_network($network, $netmask, $address)
2565   $nw= split('\.', $network);
2566   $nm= split('\.', $netmask);
2567   $ad= split('\.', $address);
2569   /* Generate inverted netmask */
2570   for ($i= 0; $i<4; $i++){
2571     $ni[$i]= 255-$nm[$i];
2572     $la[$i]= $nw[$i] | $ni[$i];
2573   }
2575   /* Transform to integer */
2576   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2577   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2578   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2580   return ($first < $curr&& $last > $curr);
2584 /* Returns contents of the given POST variable and check magic quotes settings */
2585 function get_post($name)
2587   if(!isset($_POST[$name])){
2588     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2589     return(FALSE);
2590   }
2591   if(get_magic_quotes_gpc()){
2592     return(stripcslashes($_POST[$name]));
2593   }else{
2594     return($_POST[$name]);
2595   }
2598 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2599 ?>