Code

Added support for f*cking colons in the dn
[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 globals for revision comparing */
27 $svn_path = '$HeadURL$';
28 $svn_revision = '$Revision$';
30 /* Include required files */
31 require_once ("class_ldap.inc");
32 require_once ("class_config.inc");
33 require_once ("class_userinfo.inc");
34 require_once ("class_plugin.inc");
35 require_once ("class_pluglist.inc");
36 require_once ("class_tabs.inc");
37 require_once ("class_mail-methods.inc");
38 require_once("class_password-methods.inc");
39 require_once ("functions_debug.inc");
41 /* Define constants for debugging */
42 define ("DEBUG_TRACE",   1);
43 define ("DEBUG_LDAP",    2);
44 define ("DEBUG_MYSQL",   4);
45 define ("DEBUG_SHELL",   8);
46 define ("DEBUG_POST",   16);
47 define ("DEBUG_SESSION",32);
48 define ("DEBUG_CONFIG", 64);
50 /* Rewrite german 'umlauts' and spanish 'accents'
51    to get better results */
52 $REWRITE= array( "ä" => "ae",
53     "ö" => "oe",
54     "ü" => "ue",
55     "Ä" => "Ae",
56     "Ö" => "Oe",
57     "Ü" => "Ue",
58     "ß" => "ss",
59     "á" => "a",
60     "é" => "e",
61     "í" => "i",
62     "ó" => "o",
63     "ú" => "u",
64     "Á" => "A",
65     "É" => "E",
66     "Í" => "I",
67     "Ó" => "O",
68     "Ú" => "U",
69     "ñ" => "ny",
70     "Ñ" => "Ny" );
73 /* Function to include all class_ files starting at a
74    given directory base */
75 function get_dir_list($folder= ".")
76 {
77   $currdir=getcwd();
78   if ($folder){
79     chdir("$folder");
80   }
82   $dh = opendir(".");
83   while(false !== ($file = readdir($dh))){
84     
85     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
86     // Skip all files and dirs in  "./.svn/" we don't need any information from them
87     // Skip all Template, so they won't be checked twice in the following preg_matches   
88     // Skip . / ..
90     // Result  : from 1023 ms to 490 ms   i think thats great...
91     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
92       continue;
93     
95     /* Recurse through all "common" directories */
96     if(is_dir($file) &&$file!="CVS"){
97       get_dir_list($file);
98       continue;
99     }
101     /* Include existing class_ files */
102     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
103       require_once($file);
104     }
105   }
107   closedir($dh);
108   chdir($currdir);
112 /* Create seed with microseconds */
113 function make_seed() {
114   list($usec, $sec) = explode(' ', microtime());
115   return (float) $sec + ((float) $usec * 100000);
119 /* Debug level action */
120 function DEBUG($level, $line, $function, $file, $data, $info="")
122   if ($_SESSION['DEBUGLEVEL'] & $level){
123     $output= "DEBUG[$level] ";
124     if ($function != ""){
125       $output.= "($file:$function():$line) - $info: ";
126     } else {
127       $output.= "($file:$line) - $info: ";
128     }
129     echo $output;
130     if (is_array($data)){
131       print_a($data);
132     } else {
133       echo "'$data'";
134     }
135     echo "<br>";
136   }
140 /* Simple function to get browser language and convert it to
141    xx_XY needed by locales. Ignores sublanguages and weights. */
142 function get_browser_language()
144   global $BASE_DIR;
146   /* Try to use users primary language */
147   $ui= get_userinfo();
148   if ($ui != NULL){
149     if ($ui->language != ""){
150       return ($ui->language);
151     }
152   }
154   /* Get list of languages */
155   if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
156     $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
157     $languages= split (',', $lang);
158     $languages[]= "C";
159   } else {
160     $languages= array("C");
161   }
163   /* Walk through languages and get first supported */
164   foreach ($languages as $val){
166     /* Strip off weight */
167     $lang= preg_replace("/;q=.*$/i", "", $val);
169     /* Simplify sub language handling */
170     $lang= preg_replace("/-.*$/", "", $lang);
172     /* Cancel loop if available in GOsa, or the last
173        entry has been reached */
174     if (is_dir("$BASE_DIR/locale/$lang")){
175       break;
176     }
177   }
179   return (strtolower($lang)."_".strtoupper($lang));
183 /* Rewrite ui object to another dn */
184 function change_ui_dn($dn, $newdn)
186   $ui= $_SESSION['ui'];
187   if ($ui->dn == $dn){
188     $ui->dn= $newdn;
189     $_SESSION['ui']= $ui;
190   }
194 /* Return theme path for specified file */
195 function get_template_path($filename= '', $plugin= FALSE, $path= "")
197   global $config, $BASE_DIR;
199   if (!@isset($config->data['MAIN']['THEME'])){
200     $theme= 'default';
201   } else {
202     $theme= $config->data['MAIN']['THEME'];
203   }
205   /* Return path for empty filename */
206   if ($filename == ''){
207     return ("themes/$theme/");
208   }
210   /* Return plugin dir or root directory? */
211   if ($plugin){
212     if ($path == ""){
213       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
214     } else {
215       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
216     }
217     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
218       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
219     }
220     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
221       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
222     }
223     if ($path == ""){
224       return ($_SESSION['plugin_dir']."/$filename");
225     } else {
226       return ($path."/$filename");
227     }
228   } else {
229     if (file_exists("themes/$theme/$filename")){
230       return ("themes/$theme/$filename");
231     }
232     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
233       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
234     }
235     if (file_exists("themes/default/$filename")){
236       return ("themes/default/$filename");
237     }
238     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
239       return ("$BASE_DIR/ihtml/themes/default/$filename");
240     }
241     return ($filename);
242   }
246 function array_remove_entries($needles, $haystack)
248   $tmp= array();
250   /* Loop through entries to be removed */
251   foreach ($haystack as $entry){
252     if (!in_array($entry, $needles)){
253       $tmp[]= $entry;
254     }
255   }
257   return ($tmp);
261 function gosa_log ($message)
263   global $ui;
265   /* Preset to something reasonable */
266   $username= " unauthenticated";
268   /* Replace username if object is present */
269   if (isset($ui)){
270     if ($ui->username != ""){
271       $username= "[$ui->username]";
272     } else {
273       $username= "unknown";
274     }
275   }
277   syslog(LOG_INFO,"GOsa$username: $message");
281 function ldap_init ($server, $base, $binddn='', $pass='')
283   global $config;
285   $ldap = new LDAP ($binddn, $pass, $server, isset($config->current['RECURSIVE'])                                                && $config->current['RECURSIVE'] == "true",
286       isset($config->current['TLS']) && $config->current['TLS'] == "true");
288   /* Sadly we've no proper return values here. Use the error message instead. */
289   if (!preg_match("/Success/i", $ldap->error)){
290     print_red(sprintf(_("Error when connecting the LDAP. Server said '%s'."),
291           $ldap->get_error()));
292     echo $_SESSION['errors'];
294     /* Hard error. We'd like to use the LDAP, anyway... */
295     exit;
296   }
298   /* Preset connection base to $base and return to caller */
299   $ldap->cd ($base);
300   return $ldap;
304 function ldap_login_user ($username, $password)
306   global $config;
308   /* look through the entire ldap */
309   $ldap = $config->get_ldap_link();
310   if (!preg_match("/Success/i", $ldap->error)){
311     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
312     echo $_SESSION['errors'];
313     exit;
314   }
315   $ldap->cd($config->current['BASE']);
316   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
318   /* get results, only a count of 1 is valid */
319   switch ($ldap->count()){
321     /* user not found */
322     case 0:     return (NULL);
324             /* valid uniq user */
325     case 1: 
326             break;
328             /* found more than one matching id */
329     default:
330             print_red(_("Username / UID is not unique. Please check your LDAP database."));
331             return (NULL);
332   }
334   /* LDAP schema is not case sensitive. Perform additional check. */
335   $attrs= $ldap->fetch();
336   if ($attrs['uid'][0] != $username){
337     return(NULL);
338   }
340   /* got user dn, fill acl's */
341   $ui= new userinfo($config, $ldap->getDN());
342   $ui->username= $username;
344   /* password check, bind as user with supplied password  */
345   $ldap->disconnect();
346   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
347       isset($config->current['RECURSIVE']) &&
348       $config->current['RECURSIVE'] == "true",
349       isset($config->current['TLS'])
350       && $config->current['TLS'] == "true");
351   if (!preg_match("/Success/i", $ldap->error)){
352     return (NULL);
353   }
355   /* Username is set, load subtreeACL's now */
356   $ui->loadACL();
358   return ($ui);
362 function add_lock ($object, $user)
364   global $config;
366   /* Just a sanity check... */
367   if ($object == "" || $user == ""){
368     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
369     return;
370   }
372   /* Check for existing entries in lock area */
373   $ldap= $config->get_ldap_link();
374   $ldap->cd ($config->current['CONFIG']);
375   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
376       array("gosaUser"));
377   if (!preg_match("/Success/i", $ldap->error)){
378     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()));
379     return;
380   }
382   /* Add lock if none present */
383   if ($ldap->count() == 0){
384     $attrs= array();
385     $name= md5($object);
386     $ldap->cd("cn=$name,".$config->current['CONFIG']);
387     $attrs["objectClass"] = "gosaLockEntry";
388     $attrs["gosaUser"] = $user;
389     $attrs["gosaObject"] = base64_encode($object);
390     $attrs["cn"] = "$name";
391     $ldap->add($attrs);
392     if (!preg_match("/Success/i", $ldap->error)){
393       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
394             $ldap->get_error()));
395       return;
396     }
397   }
401 function del_lock ($object)
403   global $config;
405   /* Sanity check */
406   if ($object == ""){
407     return;
408   }
410   /* Check for existance and remove the entry */
411   $ldap= $config->get_ldap_link();
412   $ldap->cd ($config->current['CONFIG']);
413   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
414   $attrs= $ldap->fetch();
415   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
416     $ldap->rmdir ($ldap->getDN());
418     if (!preg_match("/Success/i", $ldap->error)){
419       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
420             $ldap->get_error()));
421       return;
422     }
423   }
427 function del_user_locks($userdn)
429   global $config;
431   /* Get LDAP ressources */ 
432   $ldap= $config->get_ldap_link();
433   $ldap->cd ($config->current['CONFIG']);
435   /* Remove all objects of this user, drop errors silently in this case. */
436   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
437   while ($attrs= $ldap->fetch()){
438     $ldap->rmdir($attrs['dn']);
439   }
443 function get_lock ($object)
445   global $config;
447   /* Sanity check */
448   if ($object == ""){
449     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
450     return("");
451   }
453   /* Get LDAP link, check for presence of the lock entry */
454   $user= "";
455   $ldap= $config->get_ldap_link();
456   $ldap->cd ($config->current['CONFIG']);
457   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
458   if (!preg_match("/Success/i", $ldap->error)){
459     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
460     return("");
461   }
463   /* Check for broken locking information in LDAP */
464   if ($ldap->count() > 1){
466     /* Hmm. We're removing broken LDAP information here and issue a warning. */
467     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
469     /* Clean up these references now... */
470     while ($attrs= $ldap->fetch()){
471       $ldap->rmdir($attrs['dn']);
472     }
474     return("");
476   } elseif ($ldap->count() == 1){
477     $attrs = $ldap->fetch();
478     $user= $attrs['gosaUser'][0];
479   }
481   return ($user);
485 function get_list2($subtreeACL, $filter, $subsearch= TRUE, $base="", $attrs= array(), $flag= FALSE)
487  global $config;
489   /* Base the search on default base if not set */
490   $ldap= $config->get_ldap_link($flag);
491   if ($base == ""){
492     $ldap->cd ($config->current['BASE']);
493   } else {
494     $ldap->cd ($base);
495   }
497   /* Perform ONE or SUB scope searches? */
498   $ldap->ls ($filter);
500   /* Check for size limit exceeded messages for GUI feedback */
501   if (preg_match("/size limit/i", $ldap->error)){
502     $_SESSION['limit_exceeded']= TRUE;
503   } else {
504     $_SESSION['limit_exceeded']= FALSE;
505   }
506   $result= array();
509   /* Crawl through reslut entries and perform the migration to the
510      result array */
511   while($attrs = $ldap->fetch()) {
512     $dn= $ldap->getDN();
513     foreach ($subtreeACL as $key => $value){
514       if (preg_match("/$key/", $dn)){
515         $attrs["dn"]= convert_department_dn($dn);
516         $result[]= $attrs;
517         break;
518       }
519     }
520   }
523   return ($result);
527 function get_list($subtreeACL, $filter, $subsearch= TRUE, $base="", $attrs= array(), $flag= FALSE)
529   global $config;
531   /* Base the search on default base if not set */
532   $ldap= $config->get_ldap_link($flag);
533   if ($base == ""){
534     $ldap->cd ($config->current['BASE']);
535   } else {
536     $ldap->cd ($base);
537   }
539   /* Perform ONE or SUB scope searches? */
540   if ($subsearch) {
541     $ldap->search ($filter, $attrs);
542   } else {
543     $ldap->ls ($filter);
544   }
546   /* Check for size limit exceeded messages for GUI feedback */
547   if (preg_match("/size limit/i", $ldap->error)){
548     $_SESSION['limit_exceeded']= TRUE;
549   } else {
550     $_SESSION['limit_exceeded']= FALSE;
551   }
553   /* Crawl through reslut entries and perform the migration to the
554      result array */
555   $result= array();
556   while($attrs = $ldap->fetch()) {
557     $dn= $ldap->getDN();
558     foreach ($subtreeACL as $key => $value){
559       if (preg_match("/$key/", $dn)){
560         $attrs["dn"]= $dn;
561         $result[]= $attrs;
562         break;
563       }
564     }
565   }
567   return ($result);
571 function check_sizelimit()
573   /* Ignore dialog? */
574   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
575     return ("");
576   }
578   /* Eventually show dialog */
579   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
580     $smarty= get_smarty();
581     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
582           $_SESSION['size_limit']));
583     $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).'">'));
584     return($smarty->fetch(get_template_path('sizelimit.tpl')));
585   }
587   return ("");
591 function print_sizelimit_warning()
593   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
594       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
595     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
596   } else {
597     $config= "";
598   }
599   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
600     return ("("._("incomplete").") $config");
601   }
602   return ("");
606 function eval_sizelimit()
608   if (isset($_POST['set_size_action'])){
610     /* User wants new size limit? */
611     if (is_id($_POST['new_limit']) &&
612         isset($_POST['action']) && $_POST['action']=="newlimit"){
614       $_SESSION['size_limit']= validate($_POST['new_limit']);
615       $_SESSION['size_ignore']= FALSE;
616     }
618     /* User wants no limits? */
619     if (isset($_POST['action']) && $_POST['action']=="ignore"){
620       $_SESSION['size_limit']= 0;
621       $_SESSION['size_ignore']= TRUE;
622     }
624     /* User wants incomplete results */
625     if (isset($_POST['action']) && $_POST['action']=="limited"){
626       $_SESSION['size_ignore']= TRUE;
627     }
628   }
630   /* Allow fallback to dialog */
631   if (isset($_POST['edit_sizelimit'])){
632     $_SESSION['size_ignore']= FALSE;
633   }
637 function get_permissions ($dn, $subtreeACL)
639   global $config;
641   $base= $config->current['BASE'];
642   $tmp= "d,".$dn;
643   $sacl= array();
645   /* Sort subacl's for lenght to simplify matching
646      for subtrees */
647   foreach ($subtreeACL as $key => $value){
648     $sacl[$key]= strlen($key);
649   }
650   arsort ($sacl);
651   reset ($sacl);
653   /* Successively remove leading parts of the dn's until
654      it doesn't contain commas anymore */
655   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
656   while (preg_match('/,/', $tmp_dn)){
657     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
658     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
660     /* Check for acl that may apply */
661     foreach ($sacl as $key => $value){
662       if (preg_match("/$key$/", $tmp)){
663         return ($subtreeACL[$key]);
664       }
665     }
666   }
668   return array("");
672 function get_module_permission($acl_array, $module, $dn)
674   global $ui;
676   $final= "";
677   foreach($acl_array as $acl){
679     /* Check for selfflag (!) in ACL to determine if
680        the user is allowed to change parts of his/her
681        own account */
682     if (preg_match("/^!/", $acl)){
683       if ($dn != "" && $dn != $ui->dn){
685         /* No match for own DN, give up on this ACL */
686         continue;
688       } else {
690         /* Matches own DN, remove the selfflag */
691         $acl= preg_replace("/^!/", "", $acl);
693       }
694     }
696     /* Remove leading garbage */
697     $acl= preg_replace("/^:/", "", $acl);
699     /* Discover if we've access to the submodule by comparing
700        all allowed submodules specified in the ACL */
701     $tmp= split(",", $acl);
702     foreach ($tmp as $mod){
703       if (preg_match("/^$module#/", $mod)){
704         $final= strstr($mod, "#")."#";
705         continue;
706       }
707       if (preg_match("/[^#]$module$/", $mod)){
708         return ("#all#");
709       }
710       if (preg_match("/^all$/", $mod)){
711         return ("#all#");
712       }
713     }
714   }
716   /* Return assembled ACL, or none */
717   if ($final != ""){
718     return (preg_replace('/##/', '#', $final));
719   }
721   /* Nothing matches - disable access for this object */
722   return ("#none#");
726 function get_userinfo()
728   global $ui;
730   return $ui;
734 function get_smarty()
736   global $smarty;
738   return $smarty;
742 function convert_department_dn($dn)
744   $dep= "";
746   /* Build a sub-directory style list of the tree level
747      specified in $dn */
748   foreach (split (',', $dn) as $val){
750     /* We're only interested in organizational units... */
751     if (preg_match ("/ou=/", $val)){
752       $dep= substr($val,3)."/$dep";
753     }
755     /* ... and location objects */
756     if (preg_match ("/l=/", $val)){
757       $dep= substr($val,2)."/$dep";
758     }
759   }
761   /* Fix name, if it contains a replace tag */
762   $dep= preg_replace('/###GOSAREPLACED###/', ',', $dep);
764   /* Return and remove accidently trailing slashes */
765   return rtrim($dep, "/");
768 function convert_department_dn2($dn)
770   $dep= "";
772   /* Build a sub-directory style list of the tree level
773      specified in $dn */
774   $deps = array_flip($_SESSION['config']->idepartments);
776   if(isset($deps[$dn])){
777     $dn= $deps[$dn];
778     $dep = preg_replace("/^.*=/","",$dn);
779   }else{
780     $dep= preg_replace("%^.*/([^/]+)$%", "\\1", $dn);
781   }
783   /* Return and remove accidently trailing slashes */
784   $tmp = rtrim($dep, "/");
785   return $tmp;
789 function get_ou($name)
791   global $config;
793   $ou= $config->current[$name];
794   if ($ou != ""){
795     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
796       return "ou=$ou,";
797     } else {
798       return "$ou,";
799     }
800   } else {
801     return "";
802   }
806 function get_people_ou()
808   return (get_ou("PEOPLE"));
812 function get_groups_ou()
814   return (get_ou("GROUPS"));
818 function get_winstations_ou()
820   return (get_ou("WINSTATIONS"));
824 function get_base_from_people($dn)
826   global $config;
828   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
829   $base= preg_replace($pattern, '', $dn);
831   /* Set to base, if we're not on a correct subtree */
832   if (!isset($config->idepartments[$base])){
833     $base= $config->current['BASE'];
834   }
836   return ($base);
840 function get_departments($ignore_dn= "")
842   global $config;
844   /* Initialize result hash */
845   $result= array();
846   $result['/']= $config->current['BASE'];
848   /* Get list of department objects */
849   $ldap= $config->get_ldap_link();
850   $ldap->cd ($config->current['BASE']);
851   $ldap->search ("(objectClass=gosaDepartment)", array("ou"));
852   while ($attrs= $ldap->fetch()){
853     $dn= $ldap->getDN();
854     if ($dn == $ignore_dn){
855       continue;
856     }
857     $result[convert_department_dn($dn)]= $dn;
858   }
860   return ($result);
864 function chkacl($acl, $name)
866   /* Look for attribute in ACL */
867   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
868     return ("");
869   }
871   /* Optically disable html object for no match */
872   return (" disabled ");
876 function is_phone_nr($nr)
878   if ($nr == ""){
879     return (TRUE);
880   }
882   return preg_match ("/^[0-9 ()+*-]+$/", $nr);
886 function is_url($url)
888   if ($url == ""){
889     return (TRUE);
890   }
892   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
896 function is_dn($dn)
898   if ($dn == ""){
899     return (TRUE);
900   }
902   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
906 function is_uid($uid)
908   global $config;
910   if ($uid == ""){
911     return (TRUE);
912   }
914   /* STRICT adds spaces and case insenstivity to the uid check.
915      This is dangerous and should not be used. */
916   if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
917     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
918   } else {
919     return preg_match ("/^[a-z0-9_-]+$/", $uid);
920   }
924 function is_id($id)
926   if ($id == ""){
927     return (FALSE);
928   }
930   return preg_match ("/^[0-9]+$/", $id);
934 function is_path($path)
936   if ($path == ""){
937     return (TRUE);
938   }
939   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
940     return (FALSE);
941   }
943   return preg_match ("/\/.+$/", $path);
947 function is_email($address, $template= FALSE)
949   if ($address == ""){
950     return (TRUE);
951   }
952   if ($template){
953     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
954         $address);
955   } else {
956     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
957         $address);
958   }
962 function print_red()
964   /* Check number of arguments */
965   if (func_num_args() < 1){
966     return;
967   }
969   /* Get arguments, save string */
970   $array = func_get_args();
971   $string= $array[0];
973   /* Step through arguments */
974   for ($i= 1; $i<count($array); $i++){
975     $string= preg_replace ("/%s/", $array[$i], $string, 1);
976   }
978   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
979      the other case... */
980   if (isset($_SESSION['DEBUGLEVEL'])){
981     $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
982       "border-style:solid;border-color:red; background-color:black;".
983       "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
984       get_template_path('images/warning.png')."\"></td>".
985       "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
986       "<b style='font-size:16px;'>$string</b></font></td><td>".
987       "<img alt=\"\"src=\"".get_template_path('images/warning.png').
988       "\"></td></tr></table></div>\n";
989   } else {
990     echo "Error: $string\n";
991   }
995 function gen_locked_message($user, $dn)
997   global $plug, $config;
999   $_SESSION['dn']= $dn;
1000   $ldap= $config->get_ldap_link();
1001   $ldap->cat ($user);
1002   $attrs= $ldap->fetch();
1003   $uid= $attrs["uid"][0];
1005   /* Prepare and show template */
1006   $smarty= get_smarty();
1007   $smarty->assign ("dn", $dn);
1008   $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."), $dn, "<a href=\"main.php?plug=0&amp;viewid=$uid\">$uid</a>"));
1010   return ($smarty->fetch (get_template_path('islocked.tpl')));
1014 function to_string ($value)
1016   /* If this is an array, generate a text blob */
1017   if (is_array($value)){
1018     $ret= "";
1019     foreach ($value as $line){
1020       $ret.= $line."<br>\n";
1021     }
1022     return ($ret);
1023   } else {
1024     return ($value);
1025   }
1029 function get_printer_list($cups_server)
1031   global $config;
1033   $res= array();
1035   /* Use CUPS, if we've access to it */
1036   if (function_exists('cups_get_dest_list')){
1037     $dest_list= cups_get_dest_list ($cups_server);
1039     foreach ($dest_list as $prt){
1040       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1042       foreach ($attr as $prt_info){
1043         if ($prt_info->name == "printer-info"){
1044           $info= $prt_info->value;
1045           break;
1046         }
1047       }
1048       $res[$prt->name]= "$info [$prt->name]";
1049     }
1051     /* CUPS is not available, try lpstat as a replacement */
1052   } else {
1053     $ar = false;
1054     exec("lpstat -p", $ar);
1055     foreach($ar as $val){
1056       list($dummy, $printer, $rest)= split(' ', $val, 3);
1057       if (preg_match('/^[^@]+$/', $printer)){
1058         $res[$printer]= "$printer";
1059       }
1060     }
1061   }
1063   /* Merge in printers from LDAP */
1064   $ldap= $config->get_ldap_link();
1065   $ldap->cd ($config->current['BASE']);
1066   $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1067   while ($attrs= $ldap->fetch()){
1068     $res[$attrs["cn"][0]]= $attrs["cn"][0];
1069   }
1071   return $res;
1075 function sess_del ($var)
1077   /* New style */
1078   unset ($_SESSION[$var]);
1080   /* ... work around, since the first one
1081      doesn't seem to work all the time */
1082   session_unregister ($var);
1086 function show_errors($message)
1088   $complete= "";
1090   /* Assemble the message array to a plain string */
1091   foreach ($message as $error){
1092     if ($complete == ""){
1093       $complete= $error;
1094     } else {
1095       $complete= "$error<br>$complete";
1096     }
1097   }
1099   /* Fill ERROR variable with nice error dialog */
1100   print_red($complete);
1104 function show_ldap_error($message)
1106   if (!preg_match("/Success/i", $message)){
1107     print_red (_("LDAP error:")." $message");
1108     return TRUE;
1109   } else {
1110     return FALSE;
1111   }
1115 function rewrite($s)
1117   global $REWRITE;
1119   foreach ($REWRITE as $key => $val){
1120     $s= preg_replace("/$key/", "$val", $s);
1121   }
1123   return ($s);
1127 function dn2base($dn)
1129   global $config;
1131   if (get_people_ou() != ""){
1132     $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1133   }
1134   if (get_groups_ou() != ""){
1135     $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1136   }
1137   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1139   return ($base);
1144 function check_command($cmdline)
1146   $cmd= preg_replace("/ .*$/", "", $cmdline);
1148   /* Check if command exists in filesystem */
1149   if (!file_exists($cmd)){
1150     return (FALSE);
1151   }
1153   /* Check if command is executable */
1154   if (!is_executable($cmd)){
1155     return (FALSE);
1156   }
1158   return (TRUE);
1162 function print_header($image, $headline, $info= "")
1164   $display= "<div class=\"plugtop\">\n";
1165   $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";
1166   $display.= "</div>\n";
1168   if ($info != ""){
1169     $display.= "<div class=\"pluginfo\">\n";
1170     $display.= "$info";
1171     $display.= "</div>\n";
1172   } else {
1173     $display.= "<div style=\"height:5px;\">\n";
1174     $display.= "&nbsp;";
1175     $display.= "</div>\n";
1176   }
1178   return ($display);
1182 function register_global($name, $object)
1184   $_SESSION[$name]= $object;
1188 function is_global($name)
1190   return isset($_SESSION[$name]);
1194 function get_global($name)
1196   return $_SESSION[$name];
1200 function range_selector($dcnt,$start,$range=25,$post_var=false)
1203   /* Entries shown left and right from the selected entry */
1204   $max_entries= 10;
1206   /* Initialize and take care that max_entries is even */
1207   $output="";
1208   if ($max_entries & 1){
1209     $max_entries++;
1210   }
1211   
1212   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1213     $range= $_POST[$post_var];
1214   }
1216   /* Prevent output to start or end out of range */
1217   if ($start < 0 ){
1218     $start= 0 ;
1219   }
1220   if ($start >= $dcnt){
1221     $start= $range * (int)(($dcnt / $range) + 0.5);
1222   }
1224   $numpages= (($dcnt / $range));
1225   if(((int)($numpages))!=($numpages)){
1226     $numpages = (int)$numpages + 1;
1227   }
1228   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1229     return ("");
1230   }
1231   $ppage= (int)(($start / $range) + 0.5);
1234   /* Align selected page to +/- max_entries/2 */
1235   $begin= $ppage - $max_entries/2;
1236   $end= $ppage + $max_entries/2;
1238   /* Adjust begin/end, so that the selected value is somewhere in
1239      the middle and the size is max_entries if possible */
1240   if ($begin < 0){
1241     $end-= $begin + 1;
1242     $begin= 0;
1243   }
1244   if ($end > $numpages) {
1245     $end= $numpages;
1246   }
1247   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1248     $begin= $end - $max_entries;
1249   }
1251   if($post_var){
1252     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1253               <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1254   }else{
1255     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1256   }
1258   /* Draw decrement */
1259   if ($start > 0 ) {
1260     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1261       (($start-$range))."\">".
1262       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1263   }
1265   /* Draw pages */
1266   for ($i= $begin; $i < $end; $i++) {
1267     if ($ppage == $i){
1268       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1269         validate($_GET['plug'])."&amp;start=".
1270         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1271     } else {
1272       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1273         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1274     }
1275   }
1277   /* Draw increment */
1278   if($start < ($dcnt-$range)) {
1279     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1280       (($start+($range)))."\">".
1281       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1282   }
1284   if(($post_var)&&($numpages)){
1285     $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()'>";
1286     foreach(array(20,50,100,200,"all") as $num){
1287       if($num == "all"){
1288         $var = 10000;
1289       }else{
1290         $var = $num;
1291       }
1292       if($var == $range){
1293         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1294       }else{  
1295         $output.="\n<option value='".$var."'>".$num."</option>";
1296       }
1297     }
1298     $output.=  "</select></td></tr></table></div>";
1299   }else{
1300     $output.= "</div>";
1301   }
1303   return($output);
1307 function apply_filter()
1309   $apply= "";
1311   $apply= ''.
1312     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1313     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1315   return ($apply);
1319 function back_to_main()
1321   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1322     _("Back").'"></p><input type="hidden" name="ignore">';
1324   return ($string);
1328 function normalize_netmask($netmask)
1330   /* Check for notation of netmask */
1331   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1332     $num= (int)($netmask);
1333     $netmask= "";
1335     for ($byte= 0; $byte<4; $byte++){
1336       $result=0;
1338       for ($i= 7; $i>=0; $i--){
1339         if ($num-- > 0){
1340           $result+= pow(2,$i);
1341         }
1342       }
1344       $netmask.= $result.".";
1345     }
1347     return (preg_replace('/\.$/', '', $netmask));
1348   }
1350   return ($netmask);
1354 function netmask_to_bits($netmask)
1356   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1357   $res= 0;
1359   for ($n= 0; $n<4; $n++){
1360     $start= 255;
1361     $name= "nm$n";
1363     for ($i= 0; $i<8; $i++){
1364       if ($start == (int)($$name)){
1365         $res+= 8 - $i;
1366         break;
1367       }
1368       $start-= pow(2,$i);
1369     }
1370   }
1372   return ($res);
1376 function recurse($rule, $variables)
1378   $result= array();
1380   if (!count($variables)){
1381     return array($rule);
1382   }
1384   reset($variables);
1385   $key= key($variables);
1386   $val= current($variables);
1387   unset ($variables[$key]);
1389   foreach($val as $possibility){
1390     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1391     $result= array_merge($result, recurse($nrule, $variables));
1392   }
1394   return ($result);
1398 function expand_id($rule, $attributes)
1400   /* Check for id rule */
1401   if(preg_match('/^id(:|#)\d+$/',$rule)){
1402     return (array("\{$rule}"));
1403   }
1405   /* Check for clean attribute */
1406   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1407     $rule= preg_replace('/^%/', '', $rule);
1408     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1409     return (array($val));
1410   }
1412   /* Check for attribute with parameters */
1413   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1414     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1415     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1416     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1417     $start= preg_replace ('/-.*$/', '', $param);
1418     $stop = preg_replace ('/^[^-]+-/', '', $param);
1420     /* Assemble results */
1421     $result= array();
1422     for ($i= $start; $i<= $stop; $i++){
1423       $result[]= substr($val, 0, $i);
1424     }
1425     return ($result);
1426   }
1428   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1429   return (array($rule));
1433 function gen_uids($rule, $attributes)
1435   global $config;
1437   /* Search for keys and fill the variables array with all 
1438      possible values for that key. */
1439   $part= "";
1440   $trigger= false;
1441   $stripped= "";
1442   $variables= array();
1444   for ($pos= 0; $pos < strlen($rule); $pos++){
1446     if ($rule[$pos] == "{" ){
1447       $trigger= true;
1448       $part= "";
1449       continue;
1450     }
1452     if ($rule[$pos] == "}" ){
1453       $variables[$pos]= expand_id($part, $attributes);
1454       $stripped.= "\{$pos}";
1455       $trigger= false;
1456       continue;
1457     }
1459     if ($trigger){
1460       $part.= $rule[$pos];
1461     } else {
1462       $stripped.= $rule[$pos];
1463     }
1464   }
1466   /* Recurse through all possible combinations */
1467   $proposed= recurse($stripped, $variables);
1469   /* Get list of used ID's */
1470   $used= array();
1471   $ldap= $config->get_ldap_link();
1472   $ldap->cd($config->current['BASE']);
1473   $ldap->search('(uid=*)');
1475   while($attrs= $ldap->fetch()){
1476     $used[]= $attrs['uid'][0];
1477   }
1479   /* Remove used uids and watch out for id tags */
1480   $ret= array();
1481   foreach($proposed as $uid){
1483     /* Check for id tag and modify uid if needed */
1484     if(preg_match('/\{id:\d+}/',$uid)){
1485       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1487       for ($i= 0; $i < pow(10,$size); $i++){
1488         $number= sprintf("%0".$size."d", $i);
1489         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1490         if (!in_array($res, $used)){
1491           $uid= $res;
1492           break;
1493         }
1494       }
1495     }
1497     if(preg_match('/\{id#\d+}/',$uid)){
1498       $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1500       while (true){
1501         mt_srand((double) microtime()*1000000);
1502         $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1503         $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1504         if (!in_array($res, $used)){
1505           $uid= $res;
1506           break;
1507         }
1508       }
1509     }
1511     /* Don't assign used ones */
1512     if (!in_array($uid, $used)){
1513       $ret[]= $uid;
1514     }
1515   }
1517   return(array_unique($ret));
1521 function array_search_r($needle, $key, $haystack){
1523   foreach($haystack as $index => $value){
1524     $match= 0;
1526     if (is_array($value)){
1527       $match= array_search_r($needle, $key, $value);
1528     }
1530     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1531       $match=1;
1532     }
1534     if ($match){
1535       return 1;
1536     }
1537   }
1539   return 0;
1540
1543 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1544    Need to convert... */
1545 function to_byte($value) {
1546   $value= strtolower(trim($value));
1548   if(!is_numeric(substr($value, -1))) {
1550     switch(substr($value, -1)) {
1551       case 'g':
1552         $mult= 1073741824;
1553         break;
1554       case 'm':
1555         $mult= 1048576;
1556         break;
1557       case 'k':
1558         $mult= 1024;
1559         break;
1560     }
1562     return ($mult * (int)substr($value, 0, -1));
1563   } else {
1564     return $value;
1565   }
1569 function in_array_ics($value, $items)
1571   if (!is_array($items)){
1572     return (FALSE);
1573   }
1574   
1575   foreach ($items as $item){
1576     if (strtolower($item) == strtolower($value)) {
1577       return (TRUE);
1578     }
1579   }
1581   return (FALSE);
1582
1585 function generate_alphabet($count= 10)
1587   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1588   $alphabet= "";
1589   $c= 0;
1591   /* Fill cells with charaters */
1592   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1593     if ($c == 0){
1594       $alphabet.= "<tr>";
1595     }
1597     $ch = mb_substr($characters, $i, 1, "UTF8");
1598     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1599       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1601     if ($c++ == $count){
1602       $alphabet.= "</tr>";
1603       $c= 0;
1604     }
1605   }
1607   /* Fill remaining cells */
1608   while ($c++ <= $count){
1609     $alphabet.= "<td>&nbsp;</td>";
1610   }
1612   return ($alphabet);
1616 function validate($string)
1618   return (strip_tags(preg_replace('/\0/', '', $string)));
1621 function get_gosa_version()
1623   global $svn_revision, $svn_path;
1625   /* Extract informations */
1626   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1628   /* Release or development? */
1629   if (preg_match('%/gosa/trunk/%', $svn_path)){
1630     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1631   } else {
1632     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1633     return (sprintf(_("GOsa $release"), $revision));
1634   }
1638 function rmdirRecursive($path, $followLinks=false) {
1639   $dir= opendir($path);
1640   while($entry= readdir($dir)) {
1641     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1642       unlink($path."/".$entry);
1643     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1644       rmdirRecursive($path."/".$entry);
1645     }
1646   }
1647   closedir($dir);
1648   return rmdir($path);
1651 function scan_directory($path,$sort_desc=false)
1653 $ret = false;
1655 /* is this a dir ? */
1656 if(is_dir($path)) {
1657   
1658   /* is this path a readable one */
1659   if(is_readable($path)){
1660     
1661     /* Get contents and write it into an array */   
1662     $ret = array();    
1663   
1664     $dir = opendir($path);
1665     
1666     /* Is this a correct result ?*/
1667     if($dir){
1668       while($fp = readdir($dir))
1669         $ret[]= $fp;
1670       }
1671     }
1672   }
1673   /* Sort array ascending , like scandir */
1674   sort($ret);
1676   /* Sort descending if parameter is sort_desc is set */
1677   if($sort_desc) {
1678     $ret = array_reverse($ret);
1679     }
1681   return($ret);
1684 function clean_smarty_compile_dir($directory)
1686   global $svn_revision;
1688   if(is_dir($directory) && is_readable($directory)) {
1689     // Set revision filename to REVISION
1690     $revision_file= $directory."/REVISION";
1692     /* Is there a stamp containing the current revision? */
1693     if(!file_exists($revision_file)) {
1694       // create revision file
1695       create_revision($revision_file, $svn_revision);
1696     } else {
1697       # check for "$config->...['CONFIG']/revision" and the
1698       # contents should match the revision number
1699       if(!compare_revision($revision_file, $svn_revision)){
1700         // If revision differs, clean compile directory
1701         foreach(scan_directory($directory) as $file) {
1702           if(($file==".")||($file=="..")) continue;
1703           if( is_file($directory."/".$file) &&
1704               is_writable($directory."/".$file)) {
1705               // delete file
1706               if(!unlink($directory."/".$file)) {
1707                 print_red("File ".$directory."/".$file." could not be deleted.");
1708                 // This should never be reached
1709               }
1710           } elseif(is_dir($directory."/".$file) &&
1711                     is_writable($directory."/".$file)) {
1712                     // Just recursively delete it
1713              rmdirRecursive($directory."/".$file);
1714           }
1715         }
1716         // We should now create a fresh revision file
1717         clean_smarty_compile_dir($directory);
1718       } else {
1719         // Revision matches, nothing to do
1720       }
1721     }
1722   } else {
1723     // Smarty compile dir is not accessible
1724     // (Smarty will warn about this)
1725   }
1728 function create_revision($revision_file, $revision)
1730   $result= false;
1731   
1732   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1733     if($fh= fopen($revision_file, "w")) {
1734       if(fwrite($fh, $revision)) {
1735         $result= true;
1736       }
1737     }
1738     fclose($fh);
1739   } else {
1740     print_red("Can not write to revision file");
1741   }
1743   return $result;
1746 function compare_revision($revision_file, $revision)
1748   // false means revision differs
1749   $result= false;
1750   
1751   if(file_exists($revision_file) && is_readable($revision_file)) {
1752     // Open file
1753     if($fh= fopen($revision_file, "r")) {
1754       // Compare File contents with current revision
1755       if($revision == fread($fh, filesize($revision_file))) {
1756         $result= true;
1757       }
1758     } else {
1759       print_red("Can not open revision file");
1760     }
1761     // Close file
1762     fclose($fh);
1763   }
1765   return $result;
1768 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1770   $str = ""; // Our return value will be saved in this var
1772   $color  = dechex($percentage+150);
1773   $color2 = dechex(150 - $percentage);
1774   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1776   $progress = (int)(($percentage /100)*$width);
1778   /* Abort printing out percentage, if divs are to small */
1781   /* If theres a better solution for this, use it... */
1782   $str = "
1783     <div style=\" width:".($width)."px; 
1784     height:".($height)."px;
1785   background-color:#000000;
1786 padding:1px;\">
1788           <div style=\" width:".($width)."px;
1789         background-color:#$bgcolor;
1790 height:".($height)."px;\">
1792          <div style=\" width:".$progress."px;
1793 height:".$height."px;
1794        background-color:#".$color2.$color2.$color."; \">";
1797        if(($height >10)&&($showvalue)){
1798          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1799            <b>".$percentage."%</b>
1800            </font>";
1801        }
1803        $str.= "</div></div></div>";
1805        return($str);
1809 function search_config($arr, $name, $return)
1811   if (is_array($arr)){
1812     foreach ($arr as $a){
1813       if (isset($a['CLASS']) &&
1814           strtolower($a['CLASS']) == strtolower($name)){
1816         if (isset($a[$return])){
1817           return ($a[$return]);
1818         } else {
1819           return ("");
1820         }
1821       } else {
1822         $res= search_config ($a, $name, $return);
1823         if ($res != ""){
1824           return $res;
1825         }
1826       }
1827     }
1828   }
1829   return ("");
1832 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1833 ?>