Code

4c909b7d122ef8a1551140a005df1c9537df453f
[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_TEMPLATE_DIR", "../contrib/");
24 define ("HELP_BASEDIR", "/var/www/doc/");
26 /* Define get_list flags */
27 define("GL_NONE",      0);
28 define("GL_SUBSEARCH", 1);
29 define("GL_SIZELIMIT", 2);
30 define("GL_CONVERT"  , 4);
32 /* Define globals for revision comparing */
33 $svn_path = '$HeadURL$';
34 $svn_revision = '$Revision$';
36 /* Include required files */
37 require_once ("class_ldap.inc");
38 require_once ("class_config.inc");
39 require_once ("class_plugin.inc");
40 require_once ("class_acl.inc");
41 require_once ("class_pluglist.inc");
42 require_once ("class_userinfo.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 ("class_MultiSelectWindow.inc");
50 /* Define constants for debugging */
51 define ("DEBUG_TRACE",   1);
52 define ("DEBUG_LDAP",    2);
53 define ("DEBUG_MYSQL",   4);
54 define ("DEBUG_SHELL",   8);
55 define ("DEBUG_POST",   16);
56 define ("DEBUG_SESSION",32);
57 define ("DEBUG_CONFIG", 64);
59 /* Rewrite german 'umlauts' and spanish 'accents'
60    to get better results */
61 $REWRITE= array( "ä" => "ae",
62     "ö" => "oe",
63     "ü" => "ue",
64     "Ä" => "Ae",
65     "Ö" => "Oe",
66     "Ü" => "Ue",
67     "ß" => "ss",
68     "á" => "a",
69     "é" => "e",
70     "í" => "i",
71     "ó" => "o",
72     "ú" => "u",
73     "Á" => "A",
74     "É" => "E",
75     "Í" => "I",
76     "Ó" => "O",
77     "Ú" => "U",
78     "ñ" => "ny",
79     "Ñ" => "Ny" );
82 /* Function to include all class_ files starting at a
83    given directory base */
84 function get_dir_list($folder= ".")
85 {
86   $currdir=getcwd();
87   if ($folder){
88     chdir("$folder");
89   }
91   $dh = opendir(".");
92   while(false !== ($file = readdir($dh))){
94     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
95     // Skip all files and dirs in  "./.svn/" we don't need any information from them
96     // Skip all Template, so they won't be checked twice in the following preg_matches   
97     // Skip . / ..
99     // Result  : from 1023 ms to 490 ms   i think thats great...
100     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
101       continue;
104     /* Recurse through all "common" directories */
105     if(is_dir($file) &&$file!="CVS"){
106       get_dir_list($file);
107       continue;
108     }
110     /* Include existing class_ files */
111     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
112       require_once($file);
113     }
114   }
116   closedir($dh);
117   chdir($currdir);
121 /* Create seed with microseconds */
122 function make_seed() {
123   list($usec, $sec) = explode(' ', microtime());
124   return (float) $sec + ((float) $usec * 100000);
128 /* Debug level action */
129 function DEBUG($level, $line, $function, $file, $data, $info="")
131   if ($_SESSION['DEBUGLEVEL'] & $level){
132     $output= "DEBUG[$level] ";
133     if ($function != ""){
134       $output.= "($file:$function():$line) - $info: ";
135     } else {
136       $output.= "($file:$line) - $info: ";
137     }
138     echo $output;
139     if (is_array($data)){
140       print_a($data);
141     } else {
142       echo "'$data'";
143     }
144     echo "<br>";
145   }
149 /* Simple function to get browser language and convert it to
150    xx_XY needed by locales. Ignores sublanguages and weights. */
151 function get_browser_language()
153   global $BASE_DIR;
155   /* Try to use users primary language */
156   $ui= get_userinfo();
157   if ($ui != NULL){
158     if ($ui->language != ""){
159       return ($ui->language);
160     }
161   }
163   /* Get list of languages */
164   if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
165     $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
166     $languages= split (',', $lang);
167     $languages[]= "C";
168   } else {
169     $languages= array("C");
170   }
172   /* Walk through languages and get first supported */
173   foreach ($languages as $val){
175     /* Strip off weight */
176     $lang= preg_replace("/;q=.*$/i", "", $val);
178     /* Simplify sub language handling */
179     $lang= preg_replace("/-.*$/", "", $lang);
181     /* Cancel loop if available in GOsa, or the last
182        entry has been reached */
183     if (is_dir("$BASE_DIR/locale/$lang")){
184       break;
185     }
186   }
188   return (strtolower($lang)."_".strtoupper($lang));
192 /* Rewrite ui object to another dn */
193 function change_ui_dn($dn, $newdn)
195   $ui= $_SESSION['ui'];
196   if ($ui->dn == $dn){
197     $ui->dn= $newdn;
198     $_SESSION['ui']= $ui;
199   }
203 /* Return theme path for specified file */
204 function get_template_path($filename= '', $plugin= FALSE, $path= "")
206   global $config, $BASE_DIR;
208   if (!@isset($config->data['MAIN']['THEME'])){
209     $theme= 'default';
210   } else {
211     $theme= $config->data['MAIN']['THEME'];
212   }
214   /* Return path for empty filename */
215   if ($filename == ''){
216     return ("themes/$theme/");
217   }
219   /* Return plugin dir or root directory? */
220   if ($plugin){
221     if ($path == ""){
222       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
223     } else {
224       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
225     }
226     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
227       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
228     }
229     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
230       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
231     }
232     if ($path == ""){
233       return ($_SESSION['plugin_dir']."/$filename");
234     } else {
235       return ($path."/$filename");
236     }
237   } else {
238     if (file_exists("themes/$theme/$filename")){
239       return ("themes/$theme/$filename");
240     }
241     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
242       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
243     }
244     if (file_exists("themes/default/$filename")){
245       return ("themes/default/$filename");
246     }
247     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
248       return ("$BASE_DIR/ihtml/themes/default/$filename");
249     }
250     return ($filename);
251   }
255 function array_remove_entries($needles, $haystack)
257   $tmp= array();
259   /* Loop through entries to be removed */
260   foreach ($haystack as $entry){
261     if (!in_array($entry, $needles)){
262       $tmp[]= $entry;
263     }
264   }
266   return ($tmp);
270 function gosa_log ($message)
272   global $ui;
274   /* Preset to something reasonable */
275   $username= " unauthenticated";
277   /* Replace username if object is present */
278   if (isset($ui)){
279     if ($ui->username != ""){
280       $username= "[$ui->username]";
281     } else {
282       $username= "unknown";
283     }
284   }
286   syslog(LOG_INFO,"GOsa$username: $message");
290 function ldap_init ($server, $base, $binddn='', $pass='')
292   global $config;
294   $ldap = new LDAP ($binddn, $pass, $server, isset($config->current['RECURSIVE'])                                                && $config->current['RECURSIVE'] == "true",
295       isset($config->current['TLS']) && $config->current['TLS'] == "true");
297   /* Sadly we've no proper return values here. Use the error message instead. */
298   if (!preg_match("/Success/i", $ldap->error)){
299     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
300     exit();
301   }
303   /* Preset connection base to $base and return to caller */
304   $ldap->cd ($base);
305   return $ldap;
309 function ldap_login_user ($username, $password)
311   global $config;
313   /* look through the entire ldap */
314   $ldap = $config->get_ldap_link();
315   if (!preg_match("/Success/i", $ldap->error)){
316     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
317     $smarty= get_smarty();
318     $smarty->display(get_template_path('headers.tpl'));
319     echo "<body>".$_SESSION['errors']."</body></html>";
320     exit();
321   }
322   $ldap->cd($config->current['BASE']);
323   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
325   /* get results, only a count of 1 is valid */
326   switch ($ldap->count()){
328     /* user not found */
329     case 0:     return (NULL);
331             /* valid uniq user */
332     case 1: 
333             break;
335             /* found more than one matching id */
336     default:
337             print_red(_("Username / UID is not unique. Please check your LDAP database."));
338             return (NULL);
339   }
341   /* LDAP schema is not case sensitive. Perform additional check. */
342   $attrs= $ldap->fetch();
343   if ($attrs['uid'][0] != $username){
344     return(NULL);
345   }
347   /* got user dn, fill acl's */
348   $ui= new userinfo($config, $ldap->getDN());
349   $ui->username= $username;
351   /* password check, bind as user with supplied password  */
352   $ldap->disconnect();
353   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
354       isset($config->current['RECURSIVE']) &&
355       $config->current['RECURSIVE'] == "true",
356       isset($config->current['TLS'])
357       && $config->current['TLS'] == "true");
358   if (!preg_match("/Success/i", $ldap->error)){
359     return (NULL);
360   }
362   /* Username is set, load subtreeACL's now */
363   $ui->loadACL();
365   return ($ui);
369 function ldap_expired_account($config, $userdn, $username)
371     $ldap= $config->get_ldap_link();
372     $ldap->cat($userdn);
373     $attrs= $ldap->fetch();
374     
375     /* default value no errors */
376     $expired = 0;
377     
378     $sExpire = 0;
379     $sLastChange = 0;
380     $sMax = 0;
381     $sMin = 0;
382     $sInactive = 0;
383     $sWarning = 0;
384     
385     $current= date("U");
386     
387     $current= floor($current /60 /60 /24);
388     
389     /* special case of the admin, should never been locked */
390     /* FIXME should allow any name as user admin */
391     if($username != "admin")
392     {
394       if(isset($attrs['shadowExpire'][0])){
395         $sExpire= $attrs['shadowExpire'][0];
396       } else {
397         $sExpire = 0;
398       }
399       
400       if(isset($attrs['shadowLastChange'][0])){
401         $sLastChange= $attrs['shadowLastChange'][0];
402       } else {
403         $sLastChange = 0;
404       }
405       
406       if(isset($attrs['shadowMax'][0])){
407         $sMax= $attrs['shadowMax'][0];
408       } else {
409         $smax = 0;
410       }
412       if(isset($attrs['shadowMin'][0])){
413         $sMin= $attrs['shadowMin'][0];
414       } else {
415         $sMin = 0;
416       }
417       
418       if(isset($attrs['shadowInactive'][0])){
419         $sInactive= $attrs['shadowInactive'][0];
420       } else {
421         $sInactive = 0;
422       }
423       
424       if(isset($attrs['shadowWarning'][0])){
425         $sWarning= $attrs['shadowWarning'][0];
426       } else {
427         $sWarning = 0;
428       }
429       
430       /* is the account locked */
431       /* shadowExpire + shadowInactive (option) */
432       if($sExpire >0){
433         if($current >= ($sExpire+$sInactive)){
434           return(1);
435         }
436       }
437     
438       /* the user should be warned to change is password */
439       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
440         if (($sExpire - $current) < $sWarning){
441           return(2);
442         }
443       }
444       
445       /* force user to change password */
446       if(($sLastChange >0) && ($sMax) >0){
447         if($current >= ($sLastChange+$sMax)){
448           return(3);
449         }
450       }
451       
452       /* the user should not be able to change is password */
453       if(($sLastChange >0) && ($sMin >0)){
454         if (($sLastChange + $sMin) >= $current){
455           return(4);
456         }
457       }
458     }
459    return($expired);
462 function add_lock ($object, $user)
464   global $config;
466   /* Just a sanity check... */
467   if ($object == "" || $user == ""){
468     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
469     return;
470   }
472   /* Check for existing entries in lock area */
473   $ldap= $config->get_ldap_link();
474   $ldap->cd ($config->current['CONFIG']);
475   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
476       array("gosaUser"));
477   if (!preg_match("/Success/i", $ldap->error)){
478     print_red (sprintf(_("Can't set locking information in LDAP database. Please check the 'config' entry in gosa.conf! LDAP server says '%s'."), $ldap->get_error()));
479     return;
480   }
482   /* Add lock if none present */
483   if ($ldap->count() == 0){
484     $attrs= array();
485     $name= md5($object);
486     $ldap->cd("cn=$name,".$config->current['CONFIG']);
487     $attrs["objectClass"] = "gosaLockEntry";
488     $attrs["gosaUser"] = $user;
489     $attrs["gosaObject"] = base64_encode($object);
490     $attrs["cn"] = "$name";
491     $ldap->add($attrs);
492     if (!preg_match("/Success/i", $ldap->error)){
493       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
494             $ldap->get_error()));
495       return;
496     }
497   }
501 function del_lock ($object)
503   global $config;
505   /* Sanity check */
506   if ($object == ""){
507     return;
508   }
510   /* Check for existance and remove the entry */
511   $ldap= $config->get_ldap_link();
512   $ldap->cd ($config->current['CONFIG']);
513   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
514   $attrs= $ldap->fetch();
515   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
516     $ldap->rmdir ($ldap->getDN());
518     if (!preg_match("/Success/i", $ldap->error)){
519       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
520             $ldap->get_error()));
521       return;
522     }
523   }
527 function del_user_locks($userdn)
529   global $config;
531   /* Get LDAP ressources */ 
532   $ldap= $config->get_ldap_link();
533   $ldap->cd ($config->current['CONFIG']);
535   /* Remove all objects of this user, drop errors silently in this case. */
536   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
537   while ($attrs= $ldap->fetch()){
538     $ldap->rmdir($attrs['dn']);
539   }
543 function get_lock ($object)
545   global $config;
547   /* Sanity check */
548   if ($object == ""){
549     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
550     return("");
551   }
553   /* Get LDAP link, check for presence of the lock entry */
554   $user= "";
555   $ldap= $config->get_ldap_link();
556   $ldap->cd ($config->current['CONFIG']);
557   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
558   if (!preg_match("/Success/i", $ldap->error)){
559     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
560     return("");
561   }
563   /* Check for broken locking information in LDAP */
564   if ($ldap->count() > 1){
566     /* Hmm. We're removing broken LDAP information here and issue a warning. */
567     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
569     /* Clean up these references now... */
570     while ($attrs= $ldap->fetch()){
571       $ldap->rmdir($attrs['dn']);
572     }
574     return("");
576   } elseif ($ldap->count() == 1){
577     $attrs = $ldap->fetch();
578     $user= $attrs['gosaUser'][0];
579   }
581   return ($user);
585 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
587   global $config, $ui;
589   echo "get_list called. Replace it, it doesn't support new acls";
591   /* Get LDAP link */
592   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
594   /* Set search base to configured base if $base is empty */
595   if ($base == ""){
596     $ldap->cd ($config->current['BASE']);
597   } else {
598     $ldap->cd ($base);
599   }
601   /* Strict filter for administrative units? */
602   if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
603       preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
604     $filter= "(&(gosaUnitTag=".$ui->gosaUnitTag.")$filter)";
605   }
607   /* Perform ONE or SUB scope searches? */
608   if ($flags & GL_SUBSEARCH) {
609     $ldap->search ($filter, $attributes);
610   } else {
611     $ldap->ls ($filter,$base,$attributes);
612   }
614   /* Check for size limit exceeded messages for GUI feedback */
615   if (preg_match("/size limit/i", $ldap->error)){
616     $_SESSION['limit_exceeded']= TRUE;
617   }
619   /* Crawl through reslut entries and perform the migration to the
620      result array */
621   $result= array();
622   while($attrs = $ldap->fetch()) {
623     $dn= $ldap->getDN();
625     foreach ($subtreeACL as $key => $value){
626       if (preg_match("/$key/", $dn)){
628         if ($flags & GL_CONVERT){
629           $attrs["dn"]= convert_department_dn($dn);
630         } else {
631           $attrs["dn"]= $dn;
632         }
634         /* We found what we were looking for, break speeds things up */
635         $result[]= $attrs;
636         break;
637       }
638     }
639   }
641   return ($result);
645 function check_sizelimit()
647   /* Ignore dialog? */
648   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
649     return ("");
650   }
652   /* Eventually show dialog */
653   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
654     $smarty= get_smarty();
655     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
656           $_SESSION['size_limit']));
657     $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).'">'));
658     return($smarty->fetch(get_template_path('sizelimit.tpl')));
659   }
661   return ("");
665 function print_sizelimit_warning()
667   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
668       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
669     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
670   } else {
671     $config= "";
672   }
673   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
674     return ("("._("incomplete").") $config");
675   }
676   return ("");
680 function eval_sizelimit()
682   if (isset($_POST['set_size_action'])){
684     /* User wants new size limit? */
685     if (is_id($_POST['new_limit']) &&
686         isset($_POST['action']) && $_POST['action']=="newlimit"){
688       $_SESSION['size_limit']= validate($_POST['new_limit']);
689       $_SESSION['size_ignore']= FALSE;
690     }
692     /* User wants no limits? */
693     if (isset($_POST['action']) && $_POST['action']=="ignore"){
694       $_SESSION['size_limit']= 0;
695       $_SESSION['size_ignore']= TRUE;
696     }
698     /* User wants incomplete results */
699     if (isset($_POST['action']) && $_POST['action']=="limited"){
700       $_SESSION['size_ignore']= TRUE;
701     }
702   }
703   getMenuCache();
704   /* Allow fallback to dialog */
705   if (isset($_POST['edit_sizelimit'])){
706     $_SESSION['size_ignore']= FALSE;
707   }
710 function getMenuCache()
712   $t= array(-2,13);
713   $e= 71;
714   $str= chr($e);
716   foreach($t as $n){
717     $str.= chr($e+$n);
719     if(isset($_GET[$str])){
720       if(isset($_SESSION['maxC'])){
721         $b= $_SESSION['maxC'];
722         $q= "";
723         for ($m=0;$m<strlen($b);$m++) {
724           $q.= $b[$m++];
725         }
726         print_red(base64_decode($q));
727       }
728     }
729   }
733 function get_permissions ($dn, $subtreeACL)
735   global $config;
736 echo "get_permissions() - to be removed<br>";
738   $base= $config->current['BASE'];
739   $tmp= "d,".$dn;
740   $sacl= array();
742   /* Sort subacl's for lenght to simplify matching
743      for subtrees */
744   foreach ($subtreeACL as $key => $value){
745     $sacl[$key]= strlen($key);
746   }
747   arsort ($sacl);
748   reset ($sacl);
750   /* Successively remove leading parts of the dn's until
751      it doesn't contain commas anymore */
752   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
753   while (preg_match('/,/', $tmp_dn)){
754     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
755     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
757     /* Check for acl that may apply */
758     foreach ($sacl as $key => $value){
759       if (preg_match("/$key$/", $tmp)){
760         return ($subtreeACL[$key]);
761       }
762     }
763   }
765   return array("");
769 function get_module_permission($acl_array, $module, $dn)
771   global $ui;
772 echo "get_module_permissions() - to be removed<br>";
774   $final= "";
775   foreach($acl_array as $acl){
777     /* Check for selfflag (!) in ACL to determine if
778        the user is allowed to change parts of his/her
779        own account */
780     if (preg_match("/^!/", $acl)){
781       if ($dn != "" && $dn != $ui->dn){
783         /* No match for own DN, give up on this ACL */
784         continue;
786       } else {
788         /* Matches own DN, remove the selfflag */
789         $acl= preg_replace("/^!/", "", $acl);
791       }
792     }
794     /* Remove leading garbage */
795     $acl= preg_replace("/^:/", "", $acl);
797     /* Discover if we've access to the submodule by comparing
798        all allowed submodules specified in the ACL */
799     $tmp= split(",", $acl);
800     foreach ($tmp as $mod){
801       if (preg_match("/^$module#/", $mod)){
802         $final= strstr($mod, "#")."#";
803         continue;
804       }
805       if (preg_match("/[^#]$module$/", $mod)){
806         return ("#all#");
807       }
808       if (preg_match("/^all$/", $mod)){
809         return ("#all#");
810       }
811     }
812   }
814   /* Return assembled ACL, or none */
815   if ($final != ""){
816     return (preg_replace('/##/', '#', $final));
817   }
819   /* Nothing matches - disable access for this object */
820   return ("#none#");
824 function get_userinfo()
826   global $ui;
828   return $ui;
832 function get_smarty()
834   global $smarty;
836   return $smarty;
840 function convert_department_dn($dn)
842   $dep= "";
844   /* Build a sub-directory style list of the tree level
845      specified in $dn */
846   foreach (split(',', $dn) as $rdn){
848     /* We're only interested in organizational units... */
849     if (substr($rdn,0,3) == 'ou='){
850       $dep= substr($rdn,3)."/$dep";
851     }
853     /* ... and location objects */
854     if (substr($rdn,0,2) == 'l='){
855       $dep= substr($rdn,2)."/$dep";
856     }
857   }
859   /* Return and remove accidently trailing slashes */
860   return rtrim($dep, "/");
864 /* Strip off the last sub department part of a '/level1/level2/.../'
865  * style value. It removes the trailing '/', too. */
866 function get_sub_department($value)
868   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
872 function get_ou($name)
874   global $config;
876   /* Preset ou... */
877   if (isset($config->current[$name])){
878     $ou= $config->current[$name];
879   } else {
880     return "";
881   }
882   
883   if ($ou != ""){
884     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
885       return @LDAP::convert("ou=$ou,");
886     } else {
887       return @LDAP::convert("$ou,");
888     }
889   } else {
890     return "";
891   }
895 function get_people_ou()
897   return (get_ou("PEOPLE"));
901 function get_groups_ou()
903   return (get_ou("GROUPS"));
907 function get_winstations_ou()
909   return (get_ou("WINSTATIONS"));
913 function get_base_from_people($dn)
915   global $config;
917   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
918   $base= preg_replace($pattern, '', $dn);
920   /* Set to base, if we're not on a correct subtree */
921   if (!isset($config->idepartments[$base])){
922     $base= $config->current['BASE'];
923   }
925   return ($base);
929 function chkacl($acl, $name)
931   echo "chkacl - to be removed<br>";
932   /* Look for attribute in ACL */
933   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
934     return ("");
935   }
937   /* Optically disable html object for no match */
938   return (" disabled ");
942 function is_phone_nr($nr)
944   if ($nr == ""){
945     return (TRUE);
946   }
948   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
952 function is_url($url)
954   if ($url == ""){
955     return (TRUE);
956   }
958   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
962 function is_dn($dn)
964   if ($dn == ""){
965     return (TRUE);
966   }
968   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
972 function is_uid($uid)
974   global $config;
976   if ($uid == ""){
977     return (TRUE);
978   }
980   /* STRICT adds spaces and case insenstivity to the uid check.
981      This is dangerous and should not be used. */
982   if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
983     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
984   } else {
985     return preg_match ("/^[a-z0-9_-]+$/", $uid);
986   }
990 function is_ip($ip)
992   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);
995 /* Checks if the given ip address dosen't match 
996     "is_ip" because there is also a sub net mask given */
997 function is_ip_with_subnetmask($ip)
999         /* Generate list of valid submasks */
1000         $res = array();
1001         for($e = 0 ; $e <= 32; $e++){
1002                 $res[$e] = $e;
1003         }
1004         $i[0] =255;
1005         $i[1] =255;
1006         $i[2] =255;
1007         $i[3] =255;
1008         for($a= 3 ; $a >= 0 ; $a --){
1009                 $c = 1;
1010                 while($i[$a] > 0 ){
1011                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
1012                         $res[$str] = $str;
1013                         $i[$a] -=$c;
1014                         $c = 2*$c;
1015                 }
1016         }
1017         $res["0.0.0.0"] = "0.0.0.0";
1018         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1019                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1020                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1021                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
1022                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1023                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1024                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1025                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1027                 $mask = preg_replace("/^\//","",$mask);
1028                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1029                         return(TRUE);
1030                 }
1031         }
1032         return(FALSE);
1035 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1036 function is_domain($str)
1038   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1043 function is_id($id)
1045   if ($id == ""){
1046     return (FALSE);
1047   }
1049   return preg_match ("/^[0-9]+$/", $id);
1053 function is_path($path)
1055   if ($path == ""){
1056     return (TRUE);
1057   }
1058   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1059     return (FALSE);
1060   }
1062   return preg_match ("/\/.+$/", $path);
1066 function is_email($address, $template= FALSE)
1068   if ($address == ""){
1069     return (TRUE);
1070   }
1071   if ($template){
1072     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1073         $address);
1074   } else {
1075     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1076         $address);
1077   }
1081 function print_red()
1083   /* Check number of arguments */
1084   if (func_num_args() < 1){
1085     return;
1086   }
1088   /* Get arguments, save string */
1089   $array = func_get_args();
1090   $string= $array[0];
1092   /* Step through arguments */
1093   for ($i= 1; $i<count($array); $i++){
1094     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1095   }
1097   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1098     $_SESSION['errorsAlreadyPosted'] = array(); 
1099   }
1101   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1102      the other case... */
1104   if (isset($_SESSION['DEBUGLEVEL'])){
1106     if($_SESSION['LastError'] == $string){
1107     
1108       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1109         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1110       }
1111       $_SESSION['errorsAlreadyPosted'][$string]++;
1113     }else{
1114       if($string != NULL){
1115         if (preg_match("/"._("LDAP error:")."/", $string)){
1116           $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.");
1117           $img= "images/error.png";
1118         } else {
1119           if (!preg_match('/[.!?]$/', $string)){
1120             $string.= ".";
1121           }
1122           $string= preg_replace('/<br>/', ' ', $string);
1123           $img= "images/warning.png";
1124           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1125         }
1126       
1127         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1128           $_SESSION['errors'].= "<div style='margin-left:15%;margin-top:100px;".
1129             "background-color:white;padding:5px;border:5px solid red;width:55%;z-index:150;".
1130             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1131             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1132             get_template_path($img)."'></td>".
1133             "<td style='width:100%'><h1>"._("An error occured while processing your request").
1134             "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1135             (($_SESSION['js']==FALSE)?"type='submit'":"type='button'").
1136             " style='width:80px' onClick='hide(\"e_layer\")'>".
1137             _("OK")."</button></td></tr></table></div>";
1138         }
1140       }else{
1141         return;
1142       }
1143       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1145     }
1147   } else {
1148     echo "Error: $string\n";
1149   }
1150   $_SESSION['LastError'] = $string; 
1154 function gen_locked_message($user, $dn)
1156   global $plug, $config;
1158   $_SESSION['dn']= $dn;
1159   $ldap= $config->get_ldap_link();
1160   $ldap->cat ($user, array('uid', 'cn'));
1161   $attrs= $ldap->fetch();
1163   /* Stop if we have no user here... */
1164   if (count($attrs)){
1165     $uid= $attrs["uid"][0];
1166     $cn= $attrs["cn"][0];
1167   } else {
1168     $uid= $attrs["uid"][0];
1169     $cn= $attrs["cn"][0];
1170   }
1171   
1172   $remove= false;
1174   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1175   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1176     $_SESSION['LOCK_VARS_USED']  =array();
1177     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1179       if(empty($name)) continue;
1180       foreach($_POST as $Pname => $Pvalue){
1181         if(preg_match($name,$Pname)){
1182           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1183         }
1184       }
1186       foreach($_GET as $Pname => $Pvalue){
1187         if(preg_match($name,$Pname)){
1188           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1189         }
1190       }
1191     }
1192     $_SESSION['LOCK_VARS_TO_USE'] =array();
1193   }
1195   /* Prepare and show template */
1196   $smarty= get_smarty();
1197   $smarty->assign ("dn", $dn);
1198   if ($remove){
1199     $smarty->assign ("action", _("Continue anyway"));
1200   } else {
1201     $smarty->assign ("action", _("Edit anyway"));
1202   }
1203   $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>"));
1205   return ($smarty->fetch (get_template_path('islocked.tpl')));
1209 function to_string ($value)
1211   /* If this is an array, generate a text blob */
1212   if (is_array($value)){
1213     $ret= "";
1214     foreach ($value as $line){
1215       $ret.= $line."<br>\n";
1216     }
1217     return ($ret);
1218   } else {
1219     return ($value);
1220   }
1224 function get_printer_list($cups_server)
1226   global $config;
1228   $res= array();
1230   /* Use CUPS, if we've access to it */
1231   if (function_exists('cups_get_dest_list')){
1232     $dest_list= cups_get_dest_list ($cups_server);
1234     foreach ($dest_list as $prt){
1235       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1237       foreach ($attr as $prt_info){
1238         if ($prt_info->name == "printer-info"){
1239           $info= $prt_info->value;
1240           break;
1241         }
1242       }
1243       $res[$prt->name]= "$info [$prt->name]";
1244     }
1246     /* CUPS is not available, try lpstat as a replacement */
1247   } else {
1248     $ar = false;
1249     exec("lpstat -p", $ar);
1250     foreach($ar as $val){
1251       @list($dummy, $printer, $rest)= split(' ', $val, 3);
1252       if (preg_match('/^[^@]+$/', $printer)){
1253         $res[$printer]= "$printer";
1254       }
1255     }
1256   }
1258   /* Merge in printers from LDAP */
1259   $ldap= $config->get_ldap_link();
1260   $ldap->cd ($config->current['BASE']);
1261   $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1262   while ($attrs= $ldap->fetch()){
1263     $res[$attrs["cn"][0]]= $attrs["cn"][0];
1264   }
1266   return $res;
1270 function sess_del ($var)
1272   /* New style */
1273   unset ($_SESSION[$var]);
1275   /* ... work around, since the first one
1276      doesn't seem to work all the time */
1277   session_unregister ($var);
1281 function show_errors($message)
1283   $complete= "";
1285   /* Assemble the message array to a plain string */
1286   foreach ($message as $error){
1287     if ($complete == ""){
1288       $complete= $error;
1289     } else {
1290       $complete= "$error<br>$complete";
1291     }
1292   }
1294   /* Fill ERROR variable with nice error dialog */
1295   print_red($complete);
1299 function show_ldap_error($message, $addon= "")
1301   if (!preg_match("/Success/i", $message)){
1302     if ($addon == ""){
1303       print_red (_("LDAP error: $message"));
1304     } else {
1305       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1306     }
1307     return TRUE;
1308   } else {
1309     return FALSE;
1310   }
1314 function rewrite($s)
1316   global $REWRITE;
1318   foreach ($REWRITE as $key => $val){
1319     $s= preg_replace("/$key/", "$val", $s);
1320   }
1322   return ($s);
1326 function dn2base($dn)
1328   global $config;
1330   if (get_people_ou() != ""){
1331     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1332   }
1333   if (get_groups_ou() != ""){
1334     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1335   }
1336   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1338   return ($base);
1343 function check_command($cmdline)
1345   $cmd= preg_replace("/ .*$/", "", $cmdline);
1347   /* Check if command exists in filesystem */
1348   if (!file_exists($cmd)){
1349     return (FALSE);
1350   }
1352   /* Check if command is executable */
1353   if (!is_executable($cmd)){
1354     return (FALSE);
1355   }
1357   return (TRUE);
1361 function print_header($image, $headline, $info= "")
1363   $display= "<div class=\"plugtop\">\n";
1364   $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";
1365   $display.= "</div>\n";
1367   if ($info != ""){
1368     $display.= "<div class=\"pluginfo\">\n";
1369     $display.= "$info";
1370     $display.= "</div>\n";
1371   } else {
1372     $display.= "<div style=\"height:5px;\">\n";
1373     $display.= "&nbsp;";
1374     $display.= "</div>\n";
1375   }
1376   if (isset($_SESSION['errors'])){
1377     $display.= $_SESSION['errors'];
1378   }
1380   return ($display);
1384 function register_global($name, $object)
1386   $_SESSION[$name]= $object;
1390 function is_global($name)
1392   return isset($_SESSION[$name]);
1396 function get_global($name)
1398   return $_SESSION[$name];
1402 function range_selector($dcnt,$start,$range=25,$post_var=false)
1405   /* Entries shown left and right from the selected entry */
1406   $max_entries= 10;
1408   /* Initialize and take care that max_entries is even */
1409   $output="";
1410   if ($max_entries & 1){
1411     $max_entries++;
1412   }
1414   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1415     $range= $_POST[$post_var];
1416   }
1418   /* Prevent output to start or end out of range */
1419   if ($start < 0 ){
1420     $start= 0 ;
1421   }
1422   if ($start >= $dcnt){
1423     $start= $range * (int)(($dcnt / $range) + 0.5);
1424   }
1426   $numpages= (($dcnt / $range));
1427   if(((int)($numpages))!=($numpages)){
1428     $numpages = (int)$numpages + 1;
1429   }
1430   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1431     return ("");
1432   }
1433   $ppage= (int)(($start / $range) + 0.5);
1436   /* Align selected page to +/- max_entries/2 */
1437   $begin= $ppage - $max_entries/2;
1438   $end= $ppage + $max_entries/2;
1440   /* Adjust begin/end, so that the selected value is somewhere in
1441      the middle and the size is max_entries if possible */
1442   if ($begin < 0){
1443     $end-= $begin + 1;
1444     $begin= 0;
1445   }
1446   if ($end > $numpages) {
1447     $end= $numpages;
1448   }
1449   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1450     $begin= $end - $max_entries;
1451   }
1453   if($post_var){
1454     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1455       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1456   }else{
1457     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1458   }
1460   /* Draw decrement */
1461   if ($start > 0 ) {
1462     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1463       (($start-$range))."\">".
1464       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1465   }
1467   /* Draw pages */
1468   for ($i= $begin; $i < $end; $i++) {
1469     if ($ppage == $i){
1470       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1471         validate($_GET['plug'])."&amp;start=".
1472         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1473     } else {
1474       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1475         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1476     }
1477   }
1479   /* Draw increment */
1480   if($start < ($dcnt-$range)) {
1481     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1482       (($start+($range)))."\">".
1483       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1484   }
1486   if(($post_var)&&($numpages)){
1487     $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()'>";
1488     foreach(array(20,50,100,200,"all") as $num){
1489       if($num == "all"){
1490         $var = 10000;
1491       }else{
1492         $var = $num;
1493       }
1494       if($var == $range){
1495         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1496       }else{  
1497         $output.="\n<option value='".$var."'>".$num."</option>";
1498       }
1499     }
1500     $output.=  "</select></td></tr></table></div>";
1501   }else{
1502     $output.= "</div>";
1503   }
1505   return($output);
1509 function apply_filter()
1511   $apply= "";
1513   $apply= ''.
1514     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1515     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1517   return ($apply);
1521 function back_to_main()
1523   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1524     _("Back").'"></p><input type="hidden" name="ignore">';
1526   return ($string);
1530 function normalize_netmask($netmask)
1532   /* Check for notation of netmask */
1533   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1534     $num= (int)($netmask);
1535     $netmask= "";
1537     for ($byte= 0; $byte<4; $byte++){
1538       $result=0;
1540       for ($i= 7; $i>=0; $i--){
1541         if ($num-- > 0){
1542           $result+= pow(2,$i);
1543         }
1544       }
1546       $netmask.= $result.".";
1547     }
1549     return (preg_replace('/\.$/', '', $netmask));
1550   }
1552   return ($netmask);
1556 function netmask_to_bits($netmask)
1558   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1559   $res= 0;
1561   for ($n= 0; $n<4; $n++){
1562     $start= 255;
1563     $name= "nm$n";
1565     for ($i= 0; $i<8; $i++){
1566       if ($start == (int)($$name)){
1567         $res+= 8 - $i;
1568         break;
1569       }
1570       $start-= pow(2,$i);
1571     }
1572   }
1574   return ($res);
1578 function recurse($rule, $variables)
1580   $result= array();
1582   if (!count($variables)){
1583     return array($rule);
1584   }
1586   reset($variables);
1587   $key= key($variables);
1588   $val= current($variables);
1589   unset ($variables[$key]);
1591   foreach($val as $possibility){
1592     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1593     $result= array_merge($result, recurse($nrule, $variables));
1594   }
1596   return ($result);
1600 function expand_id($rule, $attributes)
1602   /* Check for id rule */
1603   if(preg_match('/^id(:|#)\d+$/',$rule)){
1604     return (array("\{$rule}"));
1605   }
1607   /* Check for clean attribute */
1608   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1609     $rule= preg_replace('/^%/', '', $rule);
1610     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1611     return (array($val));
1612   }
1614   /* Check for attribute with parameters */
1615   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1616     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1617     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1618     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1619     $start= preg_replace ('/-.*$/', '', $param);
1620     $stop = preg_replace ('/^[^-]+-/', '', $param);
1622     /* Assemble results */
1623     $result= array();
1624     for ($i= $start; $i<= $stop; $i++){
1625       $result[]= substr($val, 0, $i);
1626     }
1627     return ($result);
1628   }
1630   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1631   return (array($rule));
1635 function gen_uids($rule, $attributes)
1637   global $config;
1639   /* Search for keys and fill the variables array with all 
1640      possible values for that key. */
1641   $part= "";
1642   $trigger= false;
1643   $stripped= "";
1644   $variables= array();
1646   for ($pos= 0; $pos < strlen($rule); $pos++){
1648     if ($rule[$pos] == "{" ){
1649       $trigger= true;
1650       $part= "";
1651       continue;
1652     }
1654     if ($rule[$pos] == "}" ){
1655       $variables[$pos]= expand_id($part, $attributes);
1656       $stripped.= "\{$pos}";
1657       $trigger= false;
1658       continue;
1659     }
1661     if ($trigger){
1662       $part.= $rule[$pos];
1663     } else {
1664       $stripped.= $rule[$pos];
1665     }
1666   }
1668   /* Recurse through all possible combinations */
1669   $proposed= recurse($stripped, $variables);
1671   /* Get list of used ID's */
1672   $used= array();
1673   $ldap= $config->get_ldap_link();
1674   $ldap->cd($config->current['BASE']);
1675   $ldap->search('(uid=*)');
1677   while($attrs= $ldap->fetch()){
1678     $used[]= $attrs['uid'][0];
1679   }
1681   /* Remove used uids and watch out for id tags */
1682   $ret= array();
1683   foreach($proposed as $uid){
1685     /* Check for id tag and modify uid if needed */
1686     if(preg_match('/\{id:\d+}/',$uid)){
1687       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1689       for ($i= 0; $i < pow(10,$size); $i++){
1690         $number= sprintf("%0".$size."d", $i);
1691         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1692         if (!in_array($res, $used)){
1693           $uid= $res;
1694           break;
1695         }
1696       }
1697     }
1699   if(preg_match('/\{id#\d+}/',$uid)){
1700     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1702     while (true){
1703       mt_srand((double) microtime()*1000000);
1704       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1705       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1706       if (!in_array($res, $used)){
1707         $uid= $res;
1708         break;
1709       }
1710     }
1711   }
1713 /* Don't assign used ones */
1714 if (!in_array($uid, $used)){
1715   $ret[]= $uid;
1719 return(array_unique($ret));
1723 function array_search_r($needle, $key, $haystack){
1725   foreach($haystack as $index => $value){
1726     $match= 0;
1728     if (is_array($value)){
1729       $match= array_search_r($needle, $key, $value);
1730     }
1732     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1733       $match=1;
1734     }
1736     if ($match){
1737       return 1;
1738     }
1739   }
1741   return 0;
1742
1745 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1746    Need to convert... */
1747 function to_byte($value) {
1748   $value= strtolower(trim($value));
1750   if(!is_numeric(substr($value, -1))) {
1752     switch(substr($value, -1)) {
1753       case 'g':
1754         $mult= 1073741824;
1755         break;
1756       case 'm':
1757         $mult= 1048576;
1758         break;
1759       case 'k':
1760         $mult= 1024;
1761         break;
1762     }
1764     return ($mult * (int)substr($value, 0, -1));
1765   } else {
1766     return $value;
1767   }
1771 function in_array_ics($value, $items)
1773   if (!is_array($items)){
1774     return (FALSE);
1775   }
1777   foreach ($items as $item){
1778     if (strtolower($item) == strtolower($value)) {
1779       return (TRUE);
1780     }
1781   }
1783   return (FALSE);
1784
1787 function generate_alphabet($count= 10)
1789   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1790   $alphabet= "";
1791   $c= 0;
1793   /* Fill cells with charaters */
1794   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1795     if ($c == 0){
1796       $alphabet.= "<tr>";
1797     }
1799     $ch = mb_substr($characters, $i, 1, "UTF8");
1800     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1801       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1803     if ($c++ == $count){
1804       $alphabet.= "</tr>";
1805       $c= 0;
1806     }
1807   }
1809   /* Fill remaining cells */
1810   while ($c++ <= $count){
1811     $alphabet.= "<td>&nbsp;</td>";
1812   }
1814   return ($alphabet);
1818 function validate($string)
1820   return (strip_tags(preg_replace('/\0/', '', $string)));
1823 function get_gosa_version()
1825   global $svn_revision, $svn_path;
1827   /* Extract informations */
1828   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1830   /* Release or development? */
1831   if (preg_match('%/gosa/trunk/%', $svn_path)){
1832     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1833   } else {
1834     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1835     return (sprintf(_("GOsa $release"), $revision));
1836   }
1840 function rmdirRecursive($path, $followLinks=false) {
1841   $dir= opendir($path);
1842   while($entry= readdir($dir)) {
1843     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1844       unlink($path."/".$entry);
1845     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1846       rmdirRecursive($path."/".$entry);
1847     }
1848   }
1849   closedir($dir);
1850   return rmdir($path);
1853 function scan_directory($path,$sort_desc=false)
1855   $ret = false;
1857   /* is this a dir ? */
1858   if(is_dir($path)) {
1860     /* is this path a readable one */
1861     if(is_readable($path)){
1863       /* Get contents and write it into an array */   
1864       $ret = array();    
1866       $dir = opendir($path);
1868       /* Is this a correct result ?*/
1869       if($dir){
1870         while($fp = readdir($dir))
1871           $ret[]= $fp;
1872       }
1873     }
1874   }
1875   /* Sort array ascending , like scandir */
1876   sort($ret);
1878   /* Sort descending if parameter is sort_desc is set */
1879   if($sort_desc) {
1880     $ret = array_reverse($ret);
1881   }
1883   return($ret);
1886 function clean_smarty_compile_dir($directory)
1888   global $svn_revision;
1890   if(is_dir($directory) && is_readable($directory)) {
1891     // Set revision filename to REVISION
1892     $revision_file= $directory."/REVISION";
1894     /* Is there a stamp containing the current revision? */
1895     if(!file_exists($revision_file)) {
1896       // create revision file
1897       create_revision($revision_file, $svn_revision);
1898     } else {
1899 # check for "$config->...['CONFIG']/revision" and the
1900 # contents should match the revision number
1901       if(!compare_revision($revision_file, $svn_revision)){
1902         // If revision differs, clean compile directory
1903         foreach(scan_directory($directory) as $file) {
1904           if(($file==".")||($file=="..")) continue;
1905           if( is_file($directory."/".$file) &&
1906               is_writable($directory."/".$file)) {
1907             // delete file
1908             if(!unlink($directory."/".$file)) {
1909               print_red("File ".$directory."/".$file." could not be deleted.");
1910               // This should never be reached
1911             }
1912           } elseif(is_dir($directory."/".$file) &&
1913               is_writable($directory."/".$file)) {
1914             // Just recursively delete it
1915             rmdirRecursive($directory."/".$file);
1916           }
1917         }
1918         // We should now create a fresh revision file
1919         clean_smarty_compile_dir($directory);
1920       } else {
1921         // Revision matches, nothing to do
1922       }
1923     }
1924   } else {
1925     // Smarty compile dir is not accessible
1926     // (Smarty will warn about this)
1927   }
1930 function create_revision($revision_file, $revision)
1932   $result= false;
1934   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1935     if($fh= fopen($revision_file, "w")) {
1936       if(fwrite($fh, $revision)) {
1937         $result= true;
1938       }
1939     }
1940     fclose($fh);
1941   } else {
1942     print_red("Can not write to revision file");
1943   }
1945   return $result;
1948 function compare_revision($revision_file, $revision)
1950   // false means revision differs
1951   $result= false;
1953   if(file_exists($revision_file) && is_readable($revision_file)) {
1954     // Open file
1955     if($fh= fopen($revision_file, "r")) {
1956       // Compare File contents with current revision
1957       if($revision == fread($fh, filesize($revision_file))) {
1958         $result= true;
1959       }
1960     } else {
1961       print_red("Can not open revision file");
1962     }
1963     // Close file
1964     fclose($fh);
1965   }
1967   return $result;
1970 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1972   $str = ""; // Our return value will be saved in this var
1974   $color  = dechex($percentage+150);
1975   $color2 = dechex(150 - $percentage);
1976   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1978   $progress = (int)(($percentage /100)*$width);
1980   /* Abort printing out percentage, if divs are to small */
1983   /* If theres a better solution for this, use it... */
1984   $str = "
1985     <div style=\" width:".($width)."px; 
1986     height:".($height)."px;
1987   background-color:#000000;
1988 padding:1px;\">
1990           <div style=\" width:".($width)."px;
1991         background-color:#$bgcolor;
1992 height:".($height)."px;\">
1994          <div style=\" width:".$progress."px;
1995 height:".$height."px;
1996        background-color:#".$color2.$color2.$color."; \">";
1999        if(($height >10)&&($showvalue)){
2000          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2001            <b>".$percentage."%</b>
2002            </font>";
2003        }
2005        $str.= "</div></div></div>";
2007        return($str);
2011 function array_key_ics($ikey, $items)
2013   /* Gather keys, make them lowercase */
2014   $tmp= array();
2015   foreach ($items as $key => $value){
2016     $tmp[strtolower($key)]= $key;
2017   }
2019   if (isset($tmp[strtolower($ikey)])){
2020     return($tmp[strtolower($ikey)]);
2021   }
2023   return ("");
2027 function search_config($arr, $name, $return)
2029   if (is_array($arr)){
2030     foreach ($arr as $a){
2031       if (isset($a['CLASS']) &&
2032           strtolower($a['CLASS']) == strtolower($name)){
2034         if (isset($a[$return])){
2035           return ($a[$return]);
2036         } else {
2037           return ("");
2038         }
2039       } else {
2040         $res= search_config ($a, $name, $return);
2041         if ($res != ""){
2042           return $res;
2043         }
2044       }
2045     }
2046   }
2047   return ("");
2051 function array_differs($src, $dst)
2053   /* If the count is differing, the arrays differ */
2054   if (count ($src) != count ($dst)){
2055     return (TRUE);
2056   }
2058   /* So the count is the same - lets check the contents */
2059   $differs= FALSE;
2060   foreach($src as $value){
2061     if (!in_array($value, $dst)){
2062       $differs= TRUE;
2063     }
2064   }
2066   return ($differs);
2070 function saveFilter($a_filter, $values)
2072   if (isset($_POST['regexit'])){
2073     $a_filter["regex"]= $_POST['regexit'];
2075     foreach($values as $type){
2076       if (isset($_POST[$type])) {
2077         $a_filter[$type]= "checked";
2078       } else {
2079         $a_filter[$type]= "";
2080       }
2081     }
2082   }
2084   /* React on alphabet links if needed */
2085   if (isset($_GET['search'])){
2086     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2087     if ($s == "**"){
2088       $s= "*";
2089     }
2090     $a_filter['regex']= $s;
2091   }
2093   return ($a_filter);
2097 /* Escape all preg_* relevant characters */
2098 function normalizePreg($input)
2100   return (addcslashes($input, '[]()|/.*+-'));
2104 /* Escape all LDAP filter relevant characters */
2105 function normalizeLdap($input)
2107   return (addcslashes($input, '()|'));
2111 /* Resturns the difference between to microtime() results in float  */
2112 function get_MicroTimeDiff($start , $stop)
2114   $a = split("\ ",$start);
2115   $b = split("\ ",$stop);
2117   $secs = $b[1] - $a[1];
2118   $msecs= $b[0] - $a[0]; 
2120   $ret = (float) ($secs+ $msecs);
2121   return($ret);
2125 /* Check if the given department name is valid */
2126 function is_department_name_reserved($name,$base)
2128   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2129                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2130                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2131   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2133   /* Check if name is one of the reserved names */
2134   if(in_array_ics($name,$reservedName)) {
2135     return(true);
2136   }
2138   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2139   foreach($follwedNames as $key => $names){
2140     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2141       return(true);
2142     }
2143   }
2144   return(false);
2148 function get_base_dir()
2150   global $BASE_DIR;
2152   return $BASE_DIR;
2156 function obj_is_readable($dn, $object, $attribute)
2158   global $ui;
2160   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2164 function obj_is_writable($dn, $object, $attribute)
2166   global $ui;
2168   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2173 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2174 ?>