Code

Added fixes for several special characters
[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);
641   $e= 71;
642   $str= chr($e);
644   foreach($t as $n){
645     $str.= chr($e+$n);
647     if(isset($_GET[$str])){
648       if(isset($_SESSION['maxC'])){
649         $b= $_SESSION['maxC'];
650         $q= "";
651         for ($m=0;$m<strlen($b);$m++) {
652           $q.= $b[$m++];
653         }
654         print_red(base64_decode($q));
655       }
656     }
657   }
660 function get_permissions ($dn, $subtreeACL)
662   global $config;
664   $base= $config->current['BASE'];
665   $tmp= "d,".$dn;
666   $sacl= array();
668   /* Sort subacl's for lenght to simplify matching
669      for subtrees */
670   foreach ($subtreeACL as $key => $value){
671     $sacl[$key]= strlen($key);
672   }
673   arsort ($sacl);
674   reset ($sacl);
676   /* Successively remove leading parts of the dn's until
677      it doesn't contain commas anymore */
678   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
679   while (preg_match('/,/', $tmp_dn)){
680     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
681     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
683     /* Check for acl that may apply */
684     foreach ($sacl as $key => $value){
685       if (preg_match("/$key$/", $tmp)){
686         return ($subtreeACL[$key]);
687       }
688     }
689   }
691   return array("");
695 function get_module_permission($acl_array, $module, $dn)
697   global $ui;
699   $final= "";
700   foreach($acl_array as $acl){
702     /* Check for selfflag (!) in ACL to determine if
703        the user is allowed to change parts of his/her
704        own account */
705     if (preg_match("/^!/", $acl)){
706       if ($dn != "" && $dn != $ui->dn){
708         /* No match for own DN, give up on this ACL */
709         continue;
711       } else {
713         /* Matches own DN, remove the selfflag */
714         $acl= preg_replace("/^!/", "", $acl);
716       }
717     }
719     /* Remove leading garbage */
720     $acl= preg_replace("/^:/", "", $acl);
722     /* Discover if we've access to the submodule by comparing
723        all allowed submodules specified in the ACL */
724     $tmp= split(",", $acl);
725     foreach ($tmp as $mod){
726       if (preg_match("/^$module#/", $mod)){
727         $final= strstr($mod, "#")."#";
728         continue;
729       }
730       if (preg_match("/[^#]$module$/", $mod)){
731         return ("#all#");
732       }
733       if (preg_match("/^all$/", $mod)){
734         return ("#all#");
735       }
736     }
737   }
739   /* Return assembled ACL, or none */
740   if ($final != ""){
741     return (preg_replace('/##/', '#', $final));
742   }
744   /* Nothing matches - disable access for this object */
745   return ("#none#");
749 function get_userinfo()
751   global $ui;
753   return $ui;
757 function get_smarty()
759   global $smarty;
761   return $smarty;
765 function convert_department_dn($dn)
767   $dep= "";
769   /* Build a sub-directory style list of the tree level
770      specified in $dn */
771   foreach (split (',', $dn) as $val){
773     /* We're only interested in organizational units... */
774     if (preg_match ("/ou=/", $val)){
775       $dep= substr($val,3)."/$dep";
776     }
778     /* ... and location objects */
779     if (preg_match ("/l=/", $val)){
780       $dep= substr($val,2)."/$dep";
781     }
782   }
784   /* Return and remove accidently trailing slashes */
785   return rtrim($dep, "/");
788 function convert_department_dn2($dn)
790   $dep= "";
792   /* Build a sub-directory style list of the tree level
793      specified in $dn */
794   $deps = array_flip($_SESSION['config']->idepartments);
796   if(isset($deps[$dn])){
797     $dn= $deps[$dn];
798     $dep = preg_replace("/^.*=/","",$dn);
799   }else{
800     $dep= preg_replace("%^.*/([^/]+)$%", "\\1", $dn);
801   }
803   /* Return and remove accidently trailing slashes */
804   $tmp = rtrim($dep, "/");
805   return @ldap::fix($tmp);
809 function get_ou($name)
811   global $config;
813   $ou= $config->current[$name];
814   if ($ou != ""){
815     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
816       return "ou=$ou,";
817     } else {
818       return "$ou,";
819     }
820   } else {
821     return "";
822   }
826 function get_people_ou()
828   return (get_ou("PEOPLE"));
832 function get_groups_ou()
834   return (get_ou("GROUPS"));
838 function get_winstations_ou()
840   return (get_ou("WINSTATIONS"));
844 function get_base_from_people($dn)
846   global $config;
848   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
849   $base= preg_replace($pattern, '', $dn);
851   /* Set to base, if we're not on a correct subtree */
852   if (!isset($config->idepartments[$base])){
853     $base= $config->current['BASE'];
854   }
856   return ($base);
860 function get_departments($ignore_dn= "")
862   global $config;
864   /* Initialize result hash */
865   $result= array();
866   $result['/']= $config->current['BASE'];
868   /* Get list of department objects */
869   $ldap= $config->get_ldap_link();
870   $ldap->cd ($config->current['BASE']);
871   $ldap->search ("(objectClass=gosaDepartment)", array("ou"));
872   while ($attrs= $ldap->fetch()){
873     $dn= $ldap->getDN();
874     if ($dn == $ignore_dn){
875       continue;
876     }
877     $result[convert_department_dn($dn)]= $dn;
878   }
880   return ($result);
884 function chkacl($acl, $name)
886   /* Look for attribute in ACL */
887   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
888     return ("");
889   }
891   /* Optically disable html object for no match */
892   return (" disabled ");
896 function is_phone_nr($nr)
898   if ($nr == ""){
899     return (TRUE);
900   }
902   return preg_match ("/^[0-9 ()+*-]+$/", $nr);
906 function is_url($url)
908   if ($url == ""){
909     return (TRUE);
910   }
912   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
916 function is_dn($dn)
918   if ($dn == ""){
919     return (TRUE);
920   }
922   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
926 function is_uid($uid)
928   global $config;
930   if ($uid == ""){
931     return (TRUE);
932   }
934   /* STRICT adds spaces and case insenstivity to the uid check.
935      This is dangerous and should not be used. */
936   if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
937     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
938   } else {
939     return preg_match ("/^[a-z0-9_-]+$/", $uid);
940   }
944 function is_id($id)
946   if ($id == ""){
947     return (FALSE);
948   }
950   return preg_match ("/^[0-9]+$/", $id);
954 function is_path($path)
956   if ($path == ""){
957     return (TRUE);
958   }
959   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
960     return (FALSE);
961   }
963   return preg_match ("/\/.+$/", $path);
967 function is_email($address, $template= FALSE)
969   if ($address == ""){
970     return (TRUE);
971   }
972   if ($template){
973     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
974         $address);
975   } else {
976     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
977         $address);
978   }
982 function print_red()
984   /* Check number of arguments */
985   if (func_num_args() < 1){
986     return;
987   }
989   /* Get arguments, save string */
990   $array = func_get_args();
991   $string= $array[0];
993   /* Step through arguments */
994   for ($i= 1; $i<count($array); $i++){
995     $string= preg_replace ("/%s/", $array[$i], $string, 1);
996   }
998   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
999     $_SESSION['errorsAlreadyPosted'] = array(); 
1000   }
1002   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1003      the other case... */
1005   if (isset($_SESSION['DEBUGLEVEL'])){
1007     if($_SESSION['LastError'] == $string){
1009       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1010         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1011       }
1012       $_SESSION['errorsAlreadyPosted'][$string] ++;
1014     }else{
1015       if((!empty($_SESSION['LastError'])) && ($_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']]>1)){
1016         $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
1017           "border-style:solid;border-color:red; background-color:black;".
1018           "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
1019           get_template_path('images/warning.png')."\"></td>".
1020           "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
1021           "<b style='font-size:16px;'>".sprintf(_("Last message repeated %s times."),$_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']])."</b></font></td><td>".
1022           "<img alt=\"\"src=\"".get_template_path('images/warning.png').
1023           "\"></td></tr></table></div>\n";
1024       }
1026       if($string != NULL){
1027         $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
1028           "border-style:solid;border-color:red; background-color:black;".
1029           "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
1030           get_template_path('images/warning.png')."\"></td>".
1031           "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
1032           "<b style='font-size:16px;'>$string</b></font></td><td>".
1033           "<img alt=\"\"src=\"".get_template_path('images/warning.png').
1034           "\"></td></tr></table></div>\n";
1035       }else{
1036         return;
1037       }
1038       $_SESSION['errorsAlreadyPosted'] = array();
1039       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1041     }
1043   } else {
1044     echo "Error: $string\n";
1045   }
1046   $_SESSION['LastError'] = $string; 
1051 function gen_locked_message($user, $dn)
1053   global $plug, $config;
1055   $_SESSION['dn']= $dn;
1056   $ldap= $config->get_ldap_link();
1057   $ldap->cat ($user);
1058   $attrs= $ldap->fetch();
1059   $uid= $attrs["uid"][0];
1061   //  print_a($_POST);
1062   //  print_a($_GET);
1064   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1065     $_SESSION['LOCK_VARS_USED']  =array();
1066     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1068       if(empty($name)) continue;
1069       foreach($_POST as $Pname => $Pvalue){
1070         if(preg_match($name,$Pname)){
1071           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1072         }
1073       }
1075       foreach($_GET as $Pname => $Pvalue){
1076         if(preg_match($name,$Pname)){
1077           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1078         }
1079       }
1080     }
1081     $_SESSION['LOCK_VARS_TO_USE'] =array();
1082   }
1084   /* Prepare and show template */
1085   $smarty= get_smarty();
1086   $smarty->assign ("dn", $dn);
1087   $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>"));
1089   return ($smarty->fetch (get_template_path('islocked.tpl')));
1093 function to_string ($value)
1095   /* If this is an array, generate a text blob */
1096   if (is_array($value)){
1097     $ret= "";
1098     foreach ($value as $line){
1099       $ret.= $line."<br>\n";
1100     }
1101     return ($ret);
1102   } else {
1103     return ($value);
1104   }
1108 function get_printer_list($cups_server)
1110   global $config;
1112   $res= array();
1114   /* Use CUPS, if we've access to it */
1115   if (function_exists('cups_get_dest_list')){
1116     $dest_list= cups_get_dest_list ($cups_server);
1118     foreach ($dest_list as $prt){
1119       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1121       foreach ($attr as $prt_info){
1122         if ($prt_info->name == "printer-info"){
1123           $info= $prt_info->value;
1124           break;
1125         }
1126       }
1127       $res[$prt->name]= "$info [$prt->name]";
1128     }
1130     /* CUPS is not available, try lpstat as a replacement */
1131   } else {
1132     $ar = false;
1133     exec("lpstat -p", $ar);
1134     foreach($ar as $val){
1135       list($dummy, $printer, $rest)= split(' ', $val, 3);
1136       if (preg_match('/^[^@]+$/', $printer)){
1137         $res[$printer]= "$printer";
1138       }
1139     }
1140   }
1142   /* Merge in printers from LDAP */
1143   $ldap= $config->get_ldap_link();
1144   $ldap->cd ($config->current['BASE']);
1145   $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1146   while ($attrs= $ldap->fetch()){
1147     $res[$attrs["cn"][0]]= $attrs["cn"][0];
1148   }
1150   return $res;
1154 function sess_del ($var)
1156   /* New style */
1157   unset ($_SESSION[$var]);
1159   /* ... work around, since the first one
1160      doesn't seem to work all the time */
1161   session_unregister ($var);
1165 function show_errors($message)
1167   $complete= "";
1169   /* Assemble the message array to a plain string */
1170   foreach ($message as $error){
1171     if ($complete == ""){
1172       $complete= $error;
1173     } else {
1174       $complete= "$error<br>$complete";
1175     }
1176   }
1178   /* Fill ERROR variable with nice error dialog */
1179   print_red($complete);
1183 function show_ldap_error($message)
1185   if (!preg_match("/Success/i", $message)){
1186     print_red (_("LDAP error:")." $message");
1187     return TRUE;
1188   } else {
1189     return FALSE;
1190   }
1194 function rewrite($s)
1196   global $REWRITE;
1198   foreach ($REWRITE as $key => $val){
1199     $s= preg_replace("/$key/", "$val", $s);
1200   }
1202   return ($s);
1206 function dn2base($dn)
1208   global $config;
1210   if (get_people_ou() != ""){
1211     $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1212   }
1213   if (get_groups_ou() != ""){
1214     $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1215   }
1216   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1218   return ($base);
1223 function check_command($cmdline)
1225   $cmd= preg_replace("/ .*$/", "", $cmdline);
1227   /* Check if command exists in filesystem */
1228   if (!file_exists($cmd)){
1229     return (FALSE);
1230   }
1232   /* Check if command is executable */
1233   if (!is_executable($cmd)){
1234     return (FALSE);
1235   }
1237   return (TRUE);
1241 function print_header($image, $headline, $info= "")
1243   $display= "<div class=\"plugtop\">\n";
1244   $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";
1245   $display.= "</div>\n";
1247   if ($info != ""){
1248     $display.= "<div class=\"pluginfo\">\n";
1249     $display.= "$info";
1250     $display.= "</div>\n";
1251   } else {
1252     $display.= "<div style=\"height:5px;\">\n";
1253     $display.= "&nbsp;";
1254     $display.= "</div>\n";
1255   }
1257   return ($display);
1261 function register_global($name, $object)
1263   $_SESSION[$name]= $object;
1267 function is_global($name)
1269   return isset($_SESSION[$name]);
1273 function get_global($name)
1275   return $_SESSION[$name];
1279 function range_selector($dcnt,$start,$range=25,$post_var=false)
1282   /* Entries shown left and right from the selected entry */
1283   $max_entries= 10;
1285   /* Initialize and take care that max_entries is even */
1286   $output="";
1287   if ($max_entries & 1){
1288     $max_entries++;
1289   }
1291   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1292     $range= $_POST[$post_var];
1293   }
1295   /* Prevent output to start or end out of range */
1296   if ($start < 0 ){
1297     $start= 0 ;
1298   }
1299   if ($start >= $dcnt){
1300     $start= $range * (int)(($dcnt / $range) + 0.5);
1301   }
1303   $numpages= (($dcnt / $range));
1304   if(((int)($numpages))!=($numpages)){
1305     $numpages = (int)$numpages + 1;
1306   }
1307   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1308     return ("");
1309   }
1310   $ppage= (int)(($start / $range) + 0.5);
1313   /* Align selected page to +/- max_entries/2 */
1314   $begin= $ppage - $max_entries/2;
1315   $end= $ppage + $max_entries/2;
1317   /* Adjust begin/end, so that the selected value is somewhere in
1318      the middle and the size is max_entries if possible */
1319   if ($begin < 0){
1320     $end-= $begin + 1;
1321     $begin= 0;
1322   }
1323   if ($end > $numpages) {
1324     $end= $numpages;
1325   }
1326   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1327     $begin= $end - $max_entries;
1328   }
1330   if($post_var){
1331     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1332       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1333   }else{
1334     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1335   }
1337   /* Draw decrement */
1338   if ($start > 0 ) {
1339     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1340       (($start-$range))."\">".
1341       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1342   }
1344   /* Draw pages */
1345   for ($i= $begin; $i < $end; $i++) {
1346     if ($ppage == $i){
1347       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1348         validate($_GET['plug'])."&amp;start=".
1349         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1350     } else {
1351       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1352         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1353     }
1354   }
1356   /* Draw increment */
1357   if($start < ($dcnt-$range)) {
1358     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1359       (($start+($range)))."\">".
1360       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1361   }
1363   if(($post_var)&&($numpages)){
1364     $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()'>";
1365     foreach(array(20,50,100,200,"all") as $num){
1366       if($num == "all"){
1367         $var = 10000;
1368       }else{
1369         $var = $num;
1370       }
1371       if($var == $range){
1372         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1373       }else{  
1374         $output.="\n<option value='".$var."'>".$num."</option>";
1375       }
1376     }
1377     $output.=  "</select></td></tr></table></div>";
1378   }else{
1379     $output.= "</div>";
1380   }
1382   return($output);
1386 function apply_filter()
1388   $apply= "";
1390   $apply= ''.
1391     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1392     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1394   return ($apply);
1398 function back_to_main()
1400   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1401     _("Back").'"></p><input type="hidden" name="ignore">';
1403   return ($string);
1407 function normalize_netmask($netmask)
1409   /* Check for notation of netmask */
1410   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1411     $num= (int)($netmask);
1412     $netmask= "";
1414     for ($byte= 0; $byte<4; $byte++){
1415       $result=0;
1417       for ($i= 7; $i>=0; $i--){
1418         if ($num-- > 0){
1419           $result+= pow(2,$i);
1420         }
1421       }
1423       $netmask.= $result.".";
1424     }
1426     return (preg_replace('/\.$/', '', $netmask));
1427   }
1429   return ($netmask);
1433 function netmask_to_bits($netmask)
1435   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1436   $res= 0;
1438   for ($n= 0; $n<4; $n++){
1439     $start= 255;
1440     $name= "nm$n";
1442     for ($i= 0; $i<8; $i++){
1443       if ($start == (int)($$name)){
1444         $res+= 8 - $i;
1445         break;
1446       }
1447       $start-= pow(2,$i);
1448     }
1449   }
1451   return ($res);
1455 function recurse($rule, $variables)
1457   $result= array();
1459   if (!count($variables)){
1460     return array($rule);
1461   }
1463   reset($variables);
1464   $key= key($variables);
1465   $val= current($variables);
1466   unset ($variables[$key]);
1468   foreach($val as $possibility){
1469     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1470     $result= array_merge($result, recurse($nrule, $variables));
1471   }
1473   return ($result);
1477 function expand_id($rule, $attributes)
1479   /* Check for id rule */
1480   if(preg_match('/^id(:|#)\d+$/',$rule)){
1481     return (array("\{$rule}"));
1482   }
1484   /* Check for clean attribute */
1485   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1486     $rule= preg_replace('/^%/', '', $rule);
1487     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1488     return (array($val));
1489   }
1491   /* Check for attribute with parameters */
1492   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1493     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1494     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1495     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1496     $start= preg_replace ('/-.*$/', '', $param);
1497     $stop = preg_replace ('/^[^-]+-/', '', $param);
1499     /* Assemble results */
1500     $result= array();
1501     for ($i= $start; $i<= $stop; $i++){
1502       $result[]= substr($val, 0, $i);
1503     }
1504     return ($result);
1505   }
1507   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1508   return (array($rule));
1512 function gen_uids($rule, $attributes)
1514   global $config;
1516   /* Search for keys and fill the variables array with all 
1517      possible values for that key. */
1518   $part= "";
1519   $trigger= false;
1520   $stripped= "";
1521   $variables= array();
1523   for ($pos= 0; $pos < strlen($rule); $pos++){
1525     if ($rule[$pos] == "{" ){
1526       $trigger= true;
1527       $part= "";
1528       continue;
1529     }
1531     if ($rule[$pos] == "}" ){
1532       $variables[$pos]= expand_id($part, $attributes);
1533       $stripped.= "\{$pos}";
1534       $trigger= false;
1535       continue;
1536     }
1538     if ($trigger){
1539       $part.= $rule[$pos];
1540     } else {
1541       $stripped.= $rule[$pos];
1542     }
1543   }
1545   /* Recurse through all possible combinations */
1546   $proposed= recurse($stripped, $variables);
1548   /* Get list of used ID's */
1549   $used= array();
1550   $ldap= $config->get_ldap_link();
1551   $ldap->cd($config->current['BASE']);
1552   $ldap->search('(uid=*)');
1554   while($attrs= $ldap->fetch()){
1555     $used[]= $attrs['uid'][0];
1556   }
1558   /* Remove used uids and watch out for id tags */
1559   $ret= array();
1560   foreach($proposed as $uid){
1562     /* Check for id tag and modify uid if needed */
1563     if(preg_match('/\{id:\d+}/',$uid)){
1564       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1566       for ($i= 0; $i < pow(10,$size); $i++){
1567         $number= sprintf("%0".$size."d", $i);
1568         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1569         if (!in_array($res, $used)){
1570           $uid= $res;
1571           break;
1572         }
1573       }
1574     }
1576   if(preg_match('/\{id#\d+}/',$uid)){
1577     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1579     while (true){
1580       mt_srand((double) microtime()*1000000);
1581       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1582       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1583       if (!in_array($res, $used)){
1584         $uid= $res;
1585         break;
1586       }
1587     }
1588   }
1590 /* Don't assign used ones */
1591 if (!in_array($uid, $used)){
1592   $ret[]= $uid;
1596 return(array_unique($ret));
1600 function array_search_r($needle, $key, $haystack){
1602   foreach($haystack as $index => $value){
1603     $match= 0;
1605     if (is_array($value)){
1606       $match= array_search_r($needle, $key, $value);
1607     }
1609     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1610       $match=1;
1611     }
1613     if ($match){
1614       return 1;
1615     }
1616   }
1618   return 0;
1619
1622 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1623    Need to convert... */
1624 function to_byte($value) {
1625   $value= strtolower(trim($value));
1627   if(!is_numeric(substr($value, -1))) {
1629     switch(substr($value, -1)) {
1630       case 'g':
1631         $mult= 1073741824;
1632         break;
1633       case 'm':
1634         $mult= 1048576;
1635         break;
1636       case 'k':
1637         $mult= 1024;
1638         break;
1639     }
1641     return ($mult * (int)substr($value, 0, -1));
1642   } else {
1643     return $value;
1644   }
1648 function in_array_ics($value, $items)
1650   if (!is_array($items)){
1651     return (FALSE);
1652   }
1654   foreach ($items as $item){
1655     if (strtolower($item) == strtolower($value)) {
1656       return (TRUE);
1657     }
1658   }
1660   return (FALSE);
1661
1664 function generate_alphabet($count= 10)
1666   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1667   $alphabet= "";
1668   $c= 0;
1670   /* Fill cells with charaters */
1671   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1672     if ($c == 0){
1673       $alphabet.= "<tr>";
1674     }
1676     $ch = mb_substr($characters, $i, 1, "UTF8");
1677     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1678       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1680     if ($c++ == $count){
1681       $alphabet.= "</tr>";
1682       $c= 0;
1683     }
1684   }
1686   /* Fill remaining cells */
1687   while ($c++ <= $count){
1688     $alphabet.= "<td>&nbsp;</td>";
1689   }
1691   return ($alphabet);
1695 function validate($string)
1697   return (strip_tags(preg_replace('/\0/', '', $string)));
1700 function get_gosa_version()
1702   global $svn_revision, $svn_path;
1704   /* Extract informations */
1705   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1707   /* Release or development? */
1708   if (preg_match('%/gosa/trunk/%', $svn_path)){
1709     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1710   } else {
1711     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1712     return (sprintf(_("GOsa $release"), $revision));
1713   }
1717 function rmdirRecursive($path, $followLinks=false) {
1718   $dir= opendir($path);
1719   while($entry= readdir($dir)) {
1720     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1721       unlink($path."/".$entry);
1722     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1723       rmdirRecursive($path."/".$entry);
1724     }
1725   }
1726   closedir($dir);
1727   return rmdir($path);
1730 function scan_directory($path,$sort_desc=false)
1732   $ret = false;
1734   /* is this a dir ? */
1735   if(is_dir($path)) {
1737     /* is this path a readable one */
1738     if(is_readable($path)){
1740       /* Get contents and write it into an array */   
1741       $ret = array();    
1743       $dir = opendir($path);
1745       /* Is this a correct result ?*/
1746       if($dir){
1747         while($fp = readdir($dir))
1748           $ret[]= $fp;
1749       }
1750     }
1751   }
1752   /* Sort array ascending , like scandir */
1753   sort($ret);
1755   /* Sort descending if parameter is sort_desc is set */
1756   if($sort_desc) {
1757     $ret = array_reverse($ret);
1758   }
1760   return($ret);
1763 function clean_smarty_compile_dir($directory)
1765   global $svn_revision;
1767   if(is_dir($directory) && is_readable($directory)) {
1768     // Set revision filename to REVISION
1769     $revision_file= $directory."/REVISION";
1771     /* Is there a stamp containing the current revision? */
1772     if(!file_exists($revision_file)) {
1773       // create revision file
1774       create_revision($revision_file, $svn_revision);
1775     } else {
1776 # check for "$config->...['CONFIG']/revision" and the
1777 # contents should match the revision number
1778       if(!compare_revision($revision_file, $svn_revision)){
1779         // If revision differs, clean compile directory
1780         foreach(scan_directory($directory) as $file) {
1781           if(($file==".")||($file=="..")) continue;
1782           if( is_file($directory."/".$file) &&
1783               is_writable($directory."/".$file)) {
1784             // delete file
1785             if(!unlink($directory."/".$file)) {
1786               print_red("File ".$directory."/".$file." could not be deleted.");
1787               // This should never be reached
1788             }
1789           } elseif(is_dir($directory."/".$file) &&
1790               is_writable($directory."/".$file)) {
1791             // Just recursively delete it
1792             rmdirRecursive($directory."/".$file);
1793           }
1794         }
1795         // We should now create a fresh revision file
1796         clean_smarty_compile_dir($directory);
1797       } else {
1798         // Revision matches, nothing to do
1799       }
1800     }
1801   } else {
1802     // Smarty compile dir is not accessible
1803     // (Smarty will warn about this)
1804   }
1807 function create_revision($revision_file, $revision)
1809   $result= false;
1811   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1812     if($fh= fopen($revision_file, "w")) {
1813       if(fwrite($fh, $revision)) {
1814         $result= true;
1815       }
1816     }
1817     fclose($fh);
1818   } else {
1819     print_red("Can not write to revision file");
1820   }
1822   return $result;
1825 function compare_revision($revision_file, $revision)
1827   // false means revision differs
1828   $result= false;
1830   if(file_exists($revision_file) && is_readable($revision_file)) {
1831     // Open file
1832     if($fh= fopen($revision_file, "r")) {
1833       // Compare File contents with current revision
1834       if($revision == fread($fh, filesize($revision_file))) {
1835         $result= true;
1836       }
1837     } else {
1838       print_red("Can not open revision file");
1839     }
1840     // Close file
1841     fclose($fh);
1842   }
1844   return $result;
1847 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1849   $str = ""; // Our return value will be saved in this var
1851   $color  = dechex($percentage+150);
1852   $color2 = dechex(150 - $percentage);
1853   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1855   $progress = (int)(($percentage /100)*$width);
1857   /* Abort printing out percentage, if divs are to small */
1860   /* If theres a better solution for this, use it... */
1861   $str = "
1862     <div style=\" width:".($width)."px; 
1863     height:".($height)."px;
1864   background-color:#000000;
1865 padding:1px;\">
1867           <div style=\" width:".($width)."px;
1868         background-color:#$bgcolor;
1869 height:".($height)."px;\">
1871          <div style=\" width:".$progress."px;
1872 height:".$height."px;
1873        background-color:#".$color2.$color2.$color."; \">";
1876        if(($height >10)&&($showvalue)){
1877          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1878            <b>".$percentage."%</b>
1879            </font>";
1880        }
1882        $str.= "</div></div></div>";
1884        return($str);
1888 function array_key_ics($ikey, $items)
1890   /* Gather keys, make them lowercase */
1891   $tmp= array();
1892   foreach ($items as $key => $value){
1893     $tmp[strtolower($key)]= $key;
1894   }
1896   if (isset($tmp[strtolower($ikey)])){
1897     return($tmp[strtolower($ikey)]);
1898   }
1900   return ("");
1904 function search_config($arr, $name, $return)
1906   if (is_array($arr)){
1907     foreach ($arr as $a){
1908       if (isset($a['CLASS']) &&
1909           strtolower($a['CLASS']) == strtolower($name)){
1911         if (isset($a[$return])){
1912           return ($a[$return]);
1913         } else {
1914           return ("");
1915         }
1916       } else {
1917         $res= search_config ($a, $name, $return);
1918         if ($res != ""){
1919           return $res;
1920         }
1921       }
1922     }
1923   }
1924   return ("");
1928 function array_differs($src, $dst)
1930   /* If the count is differing, the arrays differ */
1931   if (count ($src) != count ($dst)){
1932     return (TRUE);
1933   }
1935   /* So the count is the same - lets check the contents */
1936   $differs= FALSE;
1937   foreach($src as $value){
1938     if (!in_array($value, $dst)){
1939       $differs= TRUE;
1940     }
1941   }
1943   return ($differs);
1947 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1948 ?>