Code

Added first fixes for use with existing DN's with an escaped comma inside
[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=".base64encode($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= clean_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= clean_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 (dn_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   /* Return and remove accidently trailing slashes */
762   return rtrim($dep, "/");
765 function convert_department_dn2($dn)
767   $dep= "";
769   /* Build a sub-directory style list of the tree level
770      specified in $dn */
771   $deps = array_flip($_SESSION['config']->idepartments);
773   if(isset($deps[$dn])){
774     $dn= $deps[$dn];
775     $tmp = dn_split ($dn);
776     $dep = preg_replace("/^.*=/","",$tmp[0]);
777   }else{
778     $tmp = dn_split ($dn);
779     $dep= preg_replace("%^.*/([^/]+)$%", "\\1", $tmp[0]);
780   }
782   /* Return and remove accidently trailing slashes */
783   $tmp = rtrim($dep, "/");
784   return $tmp;
788 function get_ou($name)
790   global $config;
792   $ou= $config->current[$name];
793   if ($ou != ""){
794     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
795       return "ou=$ou,";
796     } else {
797       return "$ou,";
798     }
799   } else {
800     return "";
801   }
805 function get_people_ou()
807   return (get_ou("PEOPLE"));
811 function get_groups_ou()
813   return (get_ou("GROUPS"));
817 function get_winstations_ou()
819   return (get_ou("WINSTATIONS"));
823 function get_base_from_people($dn)
825   global $config;
827   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
828   $base= preg_replace($pattern, '', $dn);
830   /* Set to base, if we're not on a correct subtree */
831   if (!isset($config->idepartments[$base])){
832     $base= $config->current['BASE'];
833   }
835   return ($base);
839 function get_departments($ignore_dn= "")
841   global $config;
843   /* Initialize result hash */
844   $result= array();
845   $result['/']= $config->current['BASE'];
847   /* Get list of department objects */
848   $ldap= $config->get_ldap_link();
849   $ldap->cd ($config->current['BASE']);
850   $ldap->search ("(objectClass=gosaDepartment)", array("ou"));
851   while ($attrs= $ldap->fetch()){
852     $dn= $ldap->getDN();
853     if ($dn == $ignore_dn){
854       continue;
855     }
856     $result[convert_department_dn($dn)]= $dn;
857   }
859   return ($result);
863 function chkacl($acl, $name)
865   /* Look for attribute in ACL */
866   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
867     return ("");
868   }
870   /* Optically disable html object for no match */
871   return (" disabled ");
875 function is_phone_nr($nr)
877   if ($nr == ""){
878     return (TRUE);
879   }
881   return preg_match ("/^[0-9 ()+*-]+$/", $nr);
885 function is_url($url)
887   if ($url == ""){
888     return (TRUE);
889   }
891   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
895 function is_dn($dn)
897   if ($dn == ""){
898     return (TRUE);
899   }
901   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
905 function is_uid($uid)
907   global $config;
909   if ($uid == ""){
910     return (TRUE);
911   }
913   /* STRICT adds spaces and case insenstivity to the uid check.
914      This is dangerous and should not be used. */
915   if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
916     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
917   } else {
918     return preg_match ("/^[a-z0-9_-]+$/", $uid);
919   }
923 function is_id($id)
925   if ($id == ""){
926     return (FALSE);
927   }
929   return preg_match ("/^[0-9]+$/", $id);
933 function is_path($path)
935   if ($path == ""){
936     return (TRUE);
937   }
938   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
939     return (FALSE);
940   }
942   return preg_match ("/\/.+$/", $path);
946 function is_email($address, $template= FALSE)
948   if ($address == ""){
949     return (TRUE);
950   }
951   if ($template){
952     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
953         $address);
954   } else {
955     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
956         $address);
957   }
961 function print_red()
963   /* Check number of arguments */
964   if (func_num_args() < 1){
965     return;
966   }
968   /* Get arguments, save string */
969   $array = func_get_args();
970   $string= $array[0];
972   /* Step through arguments */
973   for ($i= 1; $i<count($array); $i++){
974     $string= preg_replace ("/%s/", $array[$i], $string, 1);
975   }
977   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
978      the other case... */
979   if (isset($_SESSION['DEBUGLEVEL'])){
980     $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
981       "border-style:solid;border-color:red; background-color:black;".
982       "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
983       get_template_path('images/warning.png')."\"></td>".
984       "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
985       "<b style='font-size:16px;'>$string</b></font></td><td>".
986       "<img alt=\"\"src=\"".get_template_path('images/warning.png').
987       "\"></td></tr></table></div>\n";
988   } else {
989     echo "Error: $string\n";
990   }
994 function gen_locked_message($user, $dn)
996   global $plug, $config;
998   $_SESSION['dn']= $dn;
999   $ldap= $config->get_ldap_link();
1000   $ldap->cat ($user);
1001   $attrs= $ldap->fetch();
1002   $uid= $attrs["uid"][0];
1004   /* Prepare and show template */
1005   $smarty= get_smarty();
1006   $smarty->assign ("dn", $dn);
1007   $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>"));
1009   return ($smarty->fetch (get_template_path('islocked.tpl')));
1013 function to_string ($value)
1015   /* If this is an array, generate a text blob */
1016   if (is_array($value)){
1017     $ret= "";
1018     foreach ($value as $line){
1019       $ret.= $line."<br>\n";
1020     }
1021     return ($ret);
1022   } else {
1023     return ($value);
1024   }
1028 function get_printer_list($cups_server)
1030   global $config;
1032   $res= array();
1034   /* Use CUPS, if we've access to it */
1035   if (function_exists('cups_get_dest_list')){
1036     $dest_list= cups_get_dest_list ($cups_server);
1038     foreach ($dest_list as $prt){
1039       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1041       foreach ($attr as $prt_info){
1042         if ($prt_info->name == "printer-info"){
1043           $info= $prt_info->value;
1044           break;
1045         }
1046       }
1047       $res[$prt->name]= "$info [$prt->name]";
1048     }
1050     /* CUPS is not available, try lpstat as a replacement */
1051   } else {
1052     $ar = false;
1053     exec("lpstat -p", $ar);
1054     foreach($ar as $val){
1055       list($dummy, $printer, $rest)= split(' ', $val, 3);
1056       if (preg_match('/^[^@]+$/', $printer)){
1057         $res[$printer]= "$printer";
1058       }
1059     }
1060   }
1062   /* Merge in printers from LDAP */
1063   $ldap= $config->get_ldap_link();
1064   $ldap->cd ($config->current['BASE']);
1065   $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1066   while ($attrs= $ldap->fetch()){
1067     $res[$attrs["cn"][0]]= $attrs["cn"][0];
1068   }
1070   return $res;
1074 function sess_del ($var)
1076   /* New style */
1077   unset ($_SESSION[$var]);
1079   /* ... work around, since the first one
1080      doesn't seem to work all the time */
1081   session_unregister ($var);
1085 function show_errors($message)
1087   $complete= "";
1089   /* Assemble the message array to a plain string */
1090   foreach ($message as $error){
1091     if ($complete == ""){
1092       $complete= $error;
1093     } else {
1094       $complete= "$error<br>$complete";
1095     }
1096   }
1098   /* Fill ERROR variable with nice error dialog */
1099   print_red($complete);
1103 function show_ldap_error($message)
1105   if (!preg_match("/Success/i", $message)){
1106     print_red (_("LDAP error:")." $message");
1107     return TRUE;
1108   } else {
1109     return FALSE;
1110   }
1114 function rewrite($s)
1116   global $REWRITE;
1118   foreach ($REWRITE as $key => $val){
1119     $s= preg_replace("/$key/", "$val", $s);
1120   }
1122   return ($s);
1126 function dn2base($dn)
1128   global $config;
1130   if (get_people_ou() != ""){
1131     $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1132   }
1133   if (get_groups_ou() != ""){
1134     $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1135   }
1136   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1138   return ($base);
1143 function check_command($cmdline)
1145   $cmd= preg_replace("/ .*$/", "", $cmdline);
1147   /* Check if command exists in filesystem */
1148   if (!file_exists($cmd)){
1149     return (FALSE);
1150   }
1152   /* Check if command is executable */
1153   if (!is_executable($cmd)){
1154     return (FALSE);
1155   }
1157   return (TRUE);
1161 function print_header($image, $headline, $info= "")
1163   $display= "<div class=\"plugtop\">\n";
1164   $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";
1165   $display.= "</div>\n";
1167   if ($info != ""){
1168     $display.= "<div class=\"pluginfo\">\n";
1169     $display.= "$info";
1170     $display.= "</div>\n";
1171   } else {
1172     $display.= "<div style=\"height:5px;\">\n";
1173     $display.= "&nbsp;";
1174     $display.= "</div>\n";
1175   }
1177   return ($display);
1181 function register_global($name, $object)
1183   $_SESSION[$name]= $object;
1187 function is_global($name)
1189   return isset($_SESSION[$name]);
1193 function get_global($name)
1195   return $_SESSION[$name];
1199 function range_selector($dcnt,$start,$range=25,$post_var=false)
1202   /* Entries shown left and right from the selected entry */
1203   $max_entries= 10;
1205   /* Initialize and take care that max_entries is even */
1206   $output="";
1207   if ($max_entries & 1){
1208     $max_entries++;
1209   }
1210   
1211   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1212     $range= $_POST[$post_var];
1213   }
1215   /* Prevent output to start or end out of range */
1216   if ($start < 0 ){
1217     $start= 0 ;
1218   }
1219   if ($start >= $dcnt){
1220     $start= $range * (int)(($dcnt / $range) + 0.5);
1221   }
1223   $numpages= (($dcnt / $range));
1224   if(((int)($numpages))!=($numpages)){
1225     $numpages = (int)$numpages + 1;
1226   }
1227   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1228     return ("");
1229   }
1230   $ppage= (int)(($start / $range) + 0.5);
1233   /* Align selected page to +/- max_entries/2 */
1234   $begin= $ppage - $max_entries/2;
1235   $end= $ppage + $max_entries/2;
1237   /* Adjust begin/end, so that the selected value is somewhere in
1238      the middle and the size is max_entries if possible */
1239   if ($begin < 0){
1240     $end-= $begin + 1;
1241     $begin= 0;
1242   }
1243   if ($end > $numpages) {
1244     $end= $numpages;
1245   }
1246   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1247     $begin= $end - $max_entries;
1248   }
1250   if($post_var){
1251     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1252               <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1253   }else{
1254     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1255   }
1257   /* Draw decrement */
1258   if ($start > 0 ) {
1259     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1260       (($start-$range))."\">".
1261       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1262   }
1264   /* Draw pages */
1265   for ($i= $begin; $i < $end; $i++) {
1266     if ($ppage == $i){
1267       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1268         validate($_GET['plug'])."&amp;start=".
1269         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1270     } else {
1271       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1272         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1273     }
1274   }
1276   /* Draw increment */
1277   if($start < ($dcnt-$range)) {
1278     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1279       (($start+($range)))."\">".
1280       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1281   }
1283   if(($post_var)&&($numpages)){
1284     $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()'>";
1285     foreach(array(20,50,100,200,"all") as $num){
1286       if($num == "all"){
1287         $var = 10000;
1288       }else{
1289         $var = $num;
1290       }
1291       if($var == $range){
1292         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1293       }else{  
1294         $output.="\n<option value='".$var."'>".$num."</option>";
1295       }
1296     }
1297     $output.=  "</select></td></tr></table></div>";
1298   }else{
1299     $output.= "</div>";
1300   }
1302   return($output);
1306 function apply_filter()
1308   $apply= "";
1310   $apply= ''.
1311     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1312     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1314   return ($apply);
1318 function back_to_main()
1320   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1321     _("Back").'"></p><input type="hidden" name="ignore">';
1323   return ($string);
1327 function normalize_netmask($netmask)
1329   /* Check for notation of netmask */
1330   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1331     $num= (int)($netmask);
1332     $netmask= "";
1334     for ($byte= 0; $byte<4; $byte++){
1335       $result=0;
1337       for ($i= 7; $i>=0; $i--){
1338         if ($num-- > 0){
1339           $result+= pow(2,$i);
1340         }
1341       }
1343       $netmask.= $result.".";
1344     }
1346     return (preg_replace('/\.$/', '', $netmask));
1347   }
1349   return ($netmask);
1353 function netmask_to_bits($netmask)
1355   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1356   $res= 0;
1358   for ($n= 0; $n<4; $n++){
1359     $start= 255;
1360     $name= "nm$n";
1362     for ($i= 0; $i<8; $i++){
1363       if ($start == (int)($$name)){
1364         $res+= 8 - $i;
1365         break;
1366       }
1367       $start-= pow(2,$i);
1368     }
1369   }
1371   return ($res);
1375 function recurse($rule, $variables)
1377   $result= array();
1379   if (!count($variables)){
1380     return array($rule);
1381   }
1383   reset($variables);
1384   $key= key($variables);
1385   $val= current($variables);
1386   unset ($variables[$key]);
1388   foreach($val as $possibility){
1389     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1390     $result= array_merge($result, recurse($nrule, $variables));
1391   }
1393   return ($result);
1397 function expand_id($rule, $attributes)
1399   /* Check for id rule */
1400   if(preg_match('/^id(:|#)\d+$/',$rule)){
1401     return (array("\{$rule}"));
1402   }
1404   /* Check for clean attribute */
1405   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1406     $rule= preg_replace('/^%/', '', $rule);
1407     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1408     return (array($val));
1409   }
1411   /* Check for attribute with parameters */
1412   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1413     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1414     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1415     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1416     $start= preg_replace ('/-.*$/', '', $param);
1417     $stop = preg_replace ('/^[^-]+-/', '', $param);
1419     /* Assemble results */
1420     $result= array();
1421     for ($i= $start; $i<= $stop; $i++){
1422       $result[]= substr($val, 0, $i);
1423     }
1424     return ($result);
1425   }
1427   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1428   return (array($rule));
1432 function gen_uids($rule, $attributes)
1434   global $config;
1436   /* Search for keys and fill the variables array with all 
1437      possible values for that key. */
1438   $part= "";
1439   $trigger= false;
1440   $stripped= "";
1441   $variables= array();
1443   for ($pos= 0; $pos < strlen($rule); $pos++){
1445     if ($rule[$pos] == "{" ){
1446       $trigger= true;
1447       $part= "";
1448       continue;
1449     }
1451     if ($rule[$pos] == "}" ){
1452       $variables[$pos]= expand_id($part, $attributes);
1453       $stripped.= "\{$pos}";
1454       $trigger= false;
1455       continue;
1456     }
1458     if ($trigger){
1459       $part.= $rule[$pos];
1460     } else {
1461       $stripped.= $rule[$pos];
1462     }
1463   }
1465   /* Recurse through all possible combinations */
1466   $proposed= recurse($stripped, $variables);
1468   /* Get list of used ID's */
1469   $used= array();
1470   $ldap= $config->get_ldap_link();
1471   $ldap->cd($config->current['BASE']);
1472   $ldap->search('(uid=*)');
1474   while($attrs= $ldap->fetch()){
1475     $used[]= $attrs['uid'][0];
1476   }
1478   /* Remove used uids and watch out for id tags */
1479   $ret= array();
1480   foreach($proposed as $uid){
1482     /* Check for id tag and modify uid if needed */
1483     if(preg_match('/\{id:\d+}/',$uid)){
1484       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1486       for ($i= 0; $i < pow(10,$size); $i++){
1487         $number= sprintf("%0".$size."d", $i);
1488         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1489         if (!in_array($res, $used)){
1490           $uid= $res;
1491           break;
1492         }
1493       }
1494     }
1496     if(preg_match('/\{id#\d+}/',$uid)){
1497       $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1499       while (true){
1500         mt_srand((double) microtime()*1000000);
1501         $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1502         $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1503         if (!in_array($res, $used)){
1504           $uid= $res;
1505           break;
1506         }
1507       }
1508     }
1510     /* Don't assign used ones */
1511     if (!in_array($uid, $used)){
1512       $ret[]= $uid;
1513     }
1514   }
1516   return(array_unique($ret));
1520 function array_search_r($needle, $key, $haystack){
1522   foreach($haystack as $index => $value){
1523     $match= 0;
1525     if (is_array($value)){
1526       $match= array_search_r($needle, $key, $value);
1527     }
1529     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1530       $match=1;
1531     }
1533     if ($match){
1534       return 1;
1535     }
1536   }
1538   return 0;
1539
1542 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1543    Need to convert... */
1544 function to_byte($value) {
1545   $value= strtolower(trim($value));
1547   if(!is_numeric(substr($value, -1))) {
1549     switch(substr($value, -1)) {
1550       case 'g':
1551         $mult= 1073741824;
1552         break;
1553       case 'm':
1554         $mult= 1048576;
1555         break;
1556       case 'k':
1557         $mult= 1024;
1558         break;
1559     }
1561     return ($mult * (int)substr($value, 0, -1));
1562   } else {
1563     return $value;
1564   }
1568 function in_array_ics($value, $items)
1570   if (!is_array($items)){
1571     return (FALSE);
1572   }
1573   
1574   foreach ($items as $item){
1575     if (strtolower($item) == strtolower($value)) {
1576       return (TRUE);
1577     }
1578   }
1580   return (FALSE);
1581
1584 function generate_alphabet($count= 10)
1586   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1587   $alphabet= "";
1588   $c= 0;
1590   /* Fill cells with charaters */
1591   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1592     if ($c == 0){
1593       $alphabet.= "<tr>";
1594     }
1596     $ch = mb_substr($characters, $i, 1, "UTF8");
1597     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1598       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1600     if ($c++ == $count){
1601       $alphabet.= "</tr>";
1602       $c= 0;
1603     }
1604   }
1606   /* Fill remaining cells */
1607   while ($c++ <= $count){
1608     $alphabet.= "<td>&nbsp;</td>";
1609   }
1611   return ($alphabet);
1615 function validate($string)
1617   return (strip_tags(preg_replace('/\0/', '', $string)));
1620 function get_gosa_version()
1622   global $svn_revision, $svn_path;
1624   /* Extract informations */
1625   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1627   /* Release or development? */
1628   if (preg_match('%/gosa/trunk/%', $svn_path)){
1629     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1630   } else {
1631     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1632     return (sprintf(_("GOsa $release"), $revision));
1633   }
1637 function rmdirRecursive($path, $followLinks=false) {
1638   $dir= opendir($path);
1639   while($entry= readdir($dir)) {
1640     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1641       unlink($path."/".$entry);
1642     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1643       rmdirRecursive($path."/".$entry);
1644     }
1645   }
1646   closedir($dir);
1647   return rmdir($path);
1650 function scan_directory($path,$sort_desc=false)
1652 $ret = false;
1654 /* is this a dir ? */
1655 if(is_dir($path)) {
1656   
1657   /* is this path a readable one */
1658   if(is_readable($path)){
1659     
1660     /* Get contents and write it into an array */   
1661     $ret = array();    
1662   
1663     $dir = opendir($path);
1664     
1665     /* Is this a correct result ?*/
1666     if($dir){
1667       while($fp = readdir($dir))
1668         $ret[]= $fp;
1669       }
1670     }
1671   }
1672   /* Sort array ascending , like scandir */
1673   sort($ret);
1675   /* Sort descending if parameter is sort_desc is set */
1676   if($sort_desc) {
1677     $ret = array_reverse($ret);
1678     }
1680   return($ret);
1683 function clean_smarty_compile_dir($directory)
1685   global $svn_revision;
1687   if(is_dir($directory) && is_readable($directory)) {
1688     // Set revision filename to REVISION
1689     $revision_file= $directory."/REVISION";
1691     /* Is there a stamp containing the current revision? */
1692     if(!file_exists($revision_file)) {
1693       // create revision file
1694       create_revision($revision_file, $svn_revision);
1695     } else {
1696       # check for "$config->...['CONFIG']/revision" and the
1697       # contents should match the revision number
1698       if(!compare_revision($revision_file, $svn_revision)){
1699         // If revision differs, clean compile directory
1700         foreach(scan_directory($directory) as $file) {
1701           if(($file==".")||($file=="..")) continue;
1702           if( is_file($directory."/".$file) &&
1703               is_writable($directory."/".$file)) {
1704               // delete file
1705               if(!unlink($directory."/".$file)) {
1706                 print_red("File ".$directory."/".$file." could not be deleted.");
1707                 // This should never be reached
1708               }
1709           } elseif(is_dir($directory."/".$file) &&
1710                     is_writable($directory."/".$file)) {
1711                     // Just recursively delete it
1712              rmdirRecursive($directory."/".$file);
1713           }
1714         }
1715         // We should now create a fresh revision file
1716         clean_smarty_compile_dir($directory);
1717       } else {
1718         // Revision matches, nothing to do
1719       }
1720     }
1721   } else {
1722     // Smarty compile dir is not accessible
1723     // (Smarty will warn about this)
1724   }
1727 function create_revision($revision_file, $revision)
1729   $result= false;
1730   
1731   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1732     if($fh= fopen($revision_file, "w")) {
1733       if(fwrite($fh, $revision)) {
1734         $result= true;
1735       }
1736     }
1737     fclose($fh);
1738   } else {
1739     print_red("Can not write to revision file");
1740   }
1742   return $result;
1745 function compare_revision($revision_file, $revision)
1747   // false means revision differs
1748   $result= false;
1749   
1750   if(file_exists($revision_file) && is_readable($revision_file)) {
1751     // Open file
1752     if($fh= fopen($revision_file, "r")) {
1753       // Compare File contents with current revision
1754       if($revision == fread($fh, filesize($revision_file))) {
1755         $result= true;
1756       }
1757     } else {
1758       print_red("Can not open revision file");
1759     }
1760     // Close file
1761     fclose($fh);
1762   }
1764   return $result;
1767 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1769   $str = ""; // Our return value will be saved in this var
1771   $color  = dechex($percentage+150);
1772   $color2 = dechex(150 - $percentage);
1773   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1775   $progress = (int)(($percentage /100)*$width);
1777   /* Abort printing out percentage, if divs are to small */
1780   /* If theres a better solution for this, use it... */
1781   $str = "
1782     <div style=\" width:".($width)."px; 
1783     height:".($height)."px;
1784   background-color:#000000;
1785 padding:1px;\">
1787           <div style=\" width:".($width)."px;
1788         background-color:#$bgcolor;
1789 height:".($height)."px;\">
1791          <div style=\" width:".$progress."px;
1792 height:".$height."px;
1793        background-color:#".$color2.$color2.$color."; \">";
1796        if(($height >10)&&($showvalue)){
1797          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1798            <b>".$percentage."%</b>
1799            </font>";
1800        }
1802        $str.= "</div></div></div>";
1804        return($str);
1808 function search_config($arr, $name, $return)
1810   if (is_array($arr)){
1811     foreach ($arr as $a){
1812       if (isset($a['CLASS']) &&
1813           strtolower($a['CLASS']) == strtolower($name)){
1815         if (isset($a[$return])){
1816           return ($a[$return]);
1817         } else {
1818           return ("");
1819         }
1820       } else {
1821         $res= search_config ($a, $name, $return);
1822         if ($res != ""){
1823           return $res;
1824         }
1825       }
1826     }
1827   }
1828   return ("");
1832 function dn_split($dn)
1834   $ret= array();
1835   $tmp_dn= preg_replace('/\\\\,/', '##', $dn);
1836   if (!preg_match('/,/', $tmp_dn)){
1837     $ret[]= $dn;
1838     return $ret;
1839   }
1841   while (1){
1843     # Get next position of comma, exit if there
1844     # are none left
1845     $pos= strpos($tmp_dn, ',');
1846     if ($pos === false){
1847       break;
1848     }
1850     # Assign element
1851     $ret[]= substr($dn, 0, $pos);
1852     $tmp_dn= substr($tmp_dn, $pos + 1);
1853     $dn= substr($dn, $pos + 1);
1854   }
1855   
1856   return ($ret);
1860 function clean_dn($dn)
1862   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $dn);
1863   $tmp_dn= preg_replace('/[ ]*,[ ]*/', ",", $tmp_dn);
1864   $tmp_dn= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp_dn);
1865   return ($tmp_dn);
1868 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1869 ?>