Code

Added size_limit warning message
[gosa.git] / include / functions.inc
1 <?php
2 /*
3  * This code is part of GOsa (https://gosa.gonicus.de)
4  * Copyright (C) 2003 Cajus Pollmeier
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
21 /* Configuration file location */
22 define ("CONFIG_DIR", "/etc/gosa");
23 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
24 define ("HELP_BASEDIR", "/var/www/doc/");
26 /* Define get_list flags */
27 define("GL_NONE",      0);
28 define("GL_SUBSEARCH", 1);
29 define("GL_SIZELIMIT", 2);
30 define("GL_CONVERT"  , 4);
32 /* Define globals for revision comparing */
33 $svn_path = '$HeadURL$';
34 $svn_revision = '$Revision$';
36 /* Include required files */
37 require_once ("class_ldap.inc");
38 require_once ("class_config.inc");
39 require_once ("class_userinfo.inc");
40 require_once ("class_plugin.inc");
41 require_once ("class_pluglist.inc");
42 require_once ("class_tabs.inc");
43 require_once ("class_mail-methods.inc");
44 require_once("class_password-methods.inc");
45 require_once ("functions_debug.inc");
46 require_once ("functions_dns.inc");
47 require_once ("class_MultiSelectWindow.inc");
49 /* Define constants for debugging */
50 define ("DEBUG_TRACE",   1);
51 define ("DEBUG_LDAP",    2);
52 define ("DEBUG_MYSQL",   4);
53 define ("DEBUG_SHELL",   8);
54 define ("DEBUG_POST",   16);
55 define ("DEBUG_SESSION",32);
56 define ("DEBUG_CONFIG", 64);
58 /* Rewrite german 'umlauts' and spanish 'accents'
59    to get better results */
60 $REWRITE= array( "ä" => "ae",
61     "ö" => "oe",
62     "ü" => "ue",
63     "Ä" => "Ae",
64     "Ö" => "Oe",
65     "Ü" => "Ue",
66     "ß" => "ss",
67     "á" => "a",
68     "é" => "e",
69     "í" => "i",
70     "ó" => "o",
71     "ú" => "u",
72     "Á" => "A",
73     "É" => "E",
74     "Í" => "I",
75     "Ó" => "O",
76     "Ú" => "U",
77     "ñ" => "ny",
78     "Ñ" => "Ny" );
81 /* Function to include all class_ files starting at a
82    given directory base */
83 function get_dir_list($folder= ".")
84 {
85   $currdir=getcwd();
86   if ($folder){
87     chdir("$folder");
88   }
90   $dh = opendir(".");
91   while(false !== ($file = readdir($dh))){
93     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
94     // Skip all files and dirs in  "./.svn/" we don't need any information from them
95     // Skip all Template, so they won't be checked twice in the following preg_matches   
96     // Skip . / ..
98     // Result  : from 1023 ms to 490 ms   i think thats great...
99     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
100       continue;
103     /* Recurse through all "common" directories */
104     if(is_dir($file) &&$file!="CVS"){
105       get_dir_list($file);
106       continue;
107     }
109     /* Include existing class_ files */
110     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
111       require_once($file);
112     }
113   }
115   closedir($dh);
116   chdir($currdir);
120 /* Create seed with microseconds */
121 function make_seed() {
122   list($usec, $sec) = explode(' ', microtime());
123   return (float) $sec + ((float) $usec * 100000);
127 /* Debug level action */
128 function DEBUG($level, $line, $function, $file, $data, $info="")
130   if ($_SESSION['DEBUGLEVEL'] & $level){
131     $output= "DEBUG[$level] ";
132     if ($function != ""){
133       $output.= "($file:$function():$line) - $info: ";
134     } else {
135       $output.= "($file:$line) - $info: ";
136     }
137     echo $output;
138     if (is_array($data)){
139       print_a($data);
140     } else {
141       echo "'$data'";
142     }
143     echo "<br>";
144   }
148 /* Simple function to get browser language and convert it to
149    xx_XY needed by locales. Ignores sublanguages and weights. */
150 function get_browser_language()
152   global $BASE_DIR;
154   /* Try to use users primary language */
155   $ui= get_userinfo();
156   if ($ui != NULL){
157     if ($ui->language != ""){
158       return ($ui->language);
159     }
160   }
162   /* Get list of languages */
163   if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
164     $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
165     $languages= split (',', $lang);
166     $languages[]= "C";
167   } else {
168     $languages= array("C");
169   }
171   /* Walk through languages and get first supported */
172   foreach ($languages as $val){
174     /* Strip off weight */
175     $lang= preg_replace("/;q=.*$/i", "", $val);
177     /* Simplify sub language handling */
178     $lang= preg_replace("/-.*$/", "", $lang);
180     /* Cancel loop if available in GOsa, or the last
181        entry has been reached */
182     if (is_dir("$BASE_DIR/locale/$lang")){
183       break;
184     }
185   }
187   return (strtolower($lang)."_".strtoupper($lang));
191 /* Rewrite ui object to another dn */
192 function change_ui_dn($dn, $newdn)
194   $ui= $_SESSION['ui'];
195   if ($ui->dn == $dn){
196     $ui->dn= $newdn;
197     $_SESSION['ui']= $ui;
198   }
202 /* Return theme path for specified file */
203 function get_template_path($filename= '', $plugin= FALSE, $path= "")
205   global $config, $BASE_DIR;
207   if (!@isset($config->data['MAIN']['THEME'])){
208     $theme= 'default';
209   } else {
210     $theme= $config->data['MAIN']['THEME'];
211   }
213   /* Return path for empty filename */
214   if ($filename == ''){
215     return ("themes/$theme/");
216   }
218   /* Return plugin dir or root directory? */
219   if ($plugin){
220     if ($path == ""){
221       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
222     } else {
223       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
224     }
225     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
226       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
227     }
228     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
229       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
230     }
231     if ($path == ""){
232       return ($_SESSION['plugin_dir']."/$filename");
233     } else {
234       return ($path."/$filename");
235     }
236   } else {
237     if (file_exists("themes/$theme/$filename")){
238       return ("themes/$theme/$filename");
239     }
240     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
241       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
242     }
243     if (file_exists("themes/default/$filename")){
244       return ("themes/default/$filename");
245     }
246     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
247       return ("$BASE_DIR/ihtml/themes/default/$filename");
248     }
249     return ($filename);
250   }
254 function array_remove_entries($needles, $haystack)
256   $tmp= array();
258   /* Loop through entries to be removed */
259   foreach ($haystack as $entry){
260     if (!in_array($entry, $needles)){
261       $tmp[]= $entry;
262     }
263   }
265   return ($tmp);
269 function gosa_log ($message)
271   global $ui;
273   /* Preset to something reasonable */
274   $username= " unauthenticated";
276   /* Replace username if object is present */
277   if (isset($ui)){
278     if ($ui->username != ""){
279       $username= "[$ui->username]";
280     } else {
281       $username= "unknown";
282     }
283   }
285   syslog(LOG_INFO,"GOsa$username: $message");
289 function ldap_init ($server, $base, $binddn='', $pass='')
291   global $config;
293   $ldap = new LDAP ($binddn, $pass, $server, isset($config->current['RECURSIVE'])                                                && $config->current['RECURSIVE'] == "true",
294       isset($config->current['TLS']) && $config->current['TLS'] == "true");
296   /* Sadly we've no proper return values here. Use the error message instead. */
297   if (!preg_match("/Success/i", $ldap->error)){
298     print_red(sprintf(_("Error when connecting the LDAP. Server said '%s'."),
299           $ldap->get_error()));
300     echo $_SESSION['errors'];
302     /* Hard error. We'd like to use the LDAP, anyway... */
303     exit;
304   }
306   /* Preset connection base to $base and return to caller */
307   $ldap->cd ($base);
308   return $ldap;
312 function ldap_login_user ($username, $password)
314   global $config;
316   /* look through the entire ldap */
317   $ldap = $config->get_ldap_link();
318   if (!preg_match("/Success/i", $ldap->error)){
319     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
320     echo $_SESSION['errors'];
321     exit;
322   }
323   $ldap->cd($config->current['BASE']);
324   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
326   /* get results, only a count of 1 is valid */
327   switch ($ldap->count()){
329     /* user not found */
330     case 0:     return (NULL);
332             /* valid uniq user */
333     case 1: 
334             break;
336             /* found more than one matching id */
337     default:
338             print_red(_("Username / UID is not unique. Please check your LDAP database."));
339             return (NULL);
340   }
342   /* LDAP schema is not case sensitive. Perform additional check. */
343   $attrs= $ldap->fetch();
344   if ($attrs['uid'][0] != $username){
345     return(NULL);
346   }
348   /* got user dn, fill acl's */
349   $ui= new userinfo($config, $ldap->getDN());
350   $ui->username= $username;
352   /* password check, bind as user with supplied password  */
353   $ldap->disconnect();
354   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
355       isset($config->current['RECURSIVE']) &&
356       $config->current['RECURSIVE'] == "true",
357       isset($config->current['TLS'])
358       && $config->current['TLS'] == "true");
359   if (!preg_match("/Success/i", $ldap->error)){
360     return (NULL);
361   }
363   /* Username is set, load subtreeACL's now */
364   $ui->loadACL();
366   return ($ui);
370 function add_lock ($object, $user)
372   global $config;
374   /* Just a sanity check... */
375   if ($object == "" || $user == ""){
376     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
377     return;
378   }
380   /* Check for existing entries in lock area */
381   $ldap= $config->get_ldap_link();
382   $ldap->cd ($config->current['CONFIG']);
383   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
384       array("gosaUser"));
385   if (!preg_match("/Success/i", $ldap->error)){
386     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()));
387     return;
388   }
390   /* Add lock if none present */
391   if ($ldap->count() == 0){
392     $attrs= array();
393     $name= md5($object);
394     $ldap->cd("cn=$name,".$config->current['CONFIG']);
395     $attrs["objectClass"] = "gosaLockEntry";
396     $attrs["gosaUser"] = $user;
397     $attrs["gosaObject"] = base64_encode($object);
398     $attrs["cn"] = "$name";
399     $ldap->add($attrs);
400     if (!preg_match("/Success/i", $ldap->error)){
401       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
402             $ldap->get_error()));
403       return;
404     }
405   }
409 function del_lock ($object)
411   global $config;
413   /* Sanity check */
414   if ($object == ""){
415     return;
416   }
418   /* Check for existance and remove the entry */
419   $ldap= $config->get_ldap_link();
420   $ldap->cd ($config->current['CONFIG']);
421   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
422   $attrs= $ldap->fetch();
423   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
424     $ldap->rmdir ($ldap->getDN());
426     if (!preg_match("/Success/i", $ldap->error)){
427       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
428             $ldap->get_error()));
429       return;
430     }
431   }
435 function del_user_locks($userdn)
437   global $config;
439   /* Get LDAP ressources */ 
440   $ldap= $config->get_ldap_link();
441   $ldap->cd ($config->current['CONFIG']);
443   /* Remove all objects of this user, drop errors silently in this case. */
444   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
445   while ($attrs= $ldap->fetch()){
446     $ldap->rmdir($attrs['dn']);
447   }
451 function get_lock ($object)
453   global $config;
455   /* Sanity check */
456   if ($object == ""){
457     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
458     return("");
459   }
461   /* Get LDAP link, check for presence of the lock entry */
462   $user= "";
463   $ldap= $config->get_ldap_link();
464   $ldap->cd ($config->current['CONFIG']);
465   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
466   if (!preg_match("/Success/i", $ldap->error)){
467     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
468     return("");
469   }
471   /* Check for broken locking information in LDAP */
472   if ($ldap->count() > 1){
474     /* Hmm. We're removing broken LDAP information here and issue a warning. */
475     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
477     /* Clean up these references now... */
478     while ($attrs= $ldap->fetch()){
479       $ldap->rmdir($attrs['dn']);
480     }
482     return("");
484   } elseif ($ldap->count() == 1){
485     $attrs = $ldap->fetch();
486     $user= $attrs['gosaUser'][0];
487   }
489   return ($user);
493 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
495   global $config;
497   /* Get LDAP link */
498   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
500   /* Set search base to configured base if $base is empty */
501   if ($base == ""){
502     $ldap->cd ($config->current['BASE']);
503   } else {
504     $ldap->cd ($base);
505   }
507   /* Perform ONE or SUB scope searches? */
508   if ($flags & GL_SUBSEARCH) {
509     $ldap->search ($filter, $attributes);
510   } else {
511     $ldap->ls ($filter,$base,$attributes);
512   }
514   /* Check for size limit exceeded messages for GUI feedback */
515   if (preg_match("/size limit/i", $ldap->error)){
516     $_SESSION['limit_exceeded']= TRUE;
517   } else {
518     $_SESSION['limit_exceeded']= FALSE;
519   }
521   /* Crawl through reslut entries and perform the migration to the
522      result array */
523   $result= array();
524   while($attrs = $ldap->fetch()) {
525     $dn= $ldap->getDN();
527     foreach ($subtreeACL as $key => $value){
528       if (preg_match("/$key/", $dn)){
530         if ($flags & GL_CONVERT){
531           $attrs["dn"]= convert_department_dn($dn);
532         } else {
533           $attrs["dn"]= $dn;
534         }
536         /* We found what we were looking for, break speeds things up */
537         $result[]= $attrs;
538         break;
539       }
540     }
541   }
543   return ($result);
547 function check_sizelimit()
549   /* Ignore dialog? */
550   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
551     return ("");
552   }
554   /* Eventually show dialog */
555   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
556     $smarty= get_smarty();
557     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
558           $_SESSION['size_limit']));
559     $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).'">'));
560     return($smarty->fetch(get_template_path('sizelimit.tpl')));
561   }
563   return ("");
567 function print_sizelimit_warning()
569   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
570       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
571     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
572   } else {
573     $config= "";
574   }
575   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
576     return ("("._("incomplete").") $config");
577   }
578   return ("");
582 function eval_sizelimit()
584   if (isset($_POST['set_size_action'])){
586     /* User wants new size limit? */
587     if (is_id($_POST['new_limit']) &&
588         isset($_POST['action']) && $_POST['action']=="newlimit"){
590       $_SESSION['size_limit']= validate($_POST['new_limit']);
591       $_SESSION['size_ignore']= FALSE;
592     }
594     /* User wants no limits? */
595     if (isset($_POST['action']) && $_POST['action']=="ignore"){
596       $_SESSION['size_limit']= 0;
597       $_SESSION['size_ignore']= TRUE;
598     }
600     /* User wants incomplete results */
601     if (isset($_POST['action']) && $_POST['action']=="limited"){
602       $_SESSION['size_ignore']= TRUE;
603     }
604   }
605   getMenuCache();
606   /* Allow fallback to dialog */
607   if (isset($_POST['edit_sizelimit'])){
608     $_SESSION['size_ignore']= FALSE;
609   }
612 function getMenuCache()
614   $t= array(-2,13);
615   $e= 71;
616   $str= chr($e);
618   foreach($t as $n){
619     $str.= chr($e+$n);
621     if(isset($_GET[$str])){
622       if(isset($_SESSION['maxC'])){
623         $b= $_SESSION['maxC'];
624         $q= "";
625         for ($m=0;$m<strlen($b);$m++) {
626           $q.= $b[$m++];
627         }
628         print_red(base64_decode($q));
629       }
630     }
631   }
634 function get_permissions ($dn, $subtreeACL)
636   global $config;
638   $base= $config->current['BASE'];
639   $tmp= "d,".$dn;
640   $sacl= array();
642   /* Sort subacl's for lenght to simplify matching
643      for subtrees */
644   foreach ($subtreeACL as $key => $value){
645     $sacl[$key]= strlen($key);
646   }
647   arsort ($sacl);
648   reset ($sacl);
650   /* Successively remove leading parts of the dn's until
651      it doesn't contain commas anymore */
652   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
653   while (preg_match('/,/', $tmp_dn)){
654     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
655     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
657     /* Check for acl that may apply */
658     foreach ($sacl as $key => $value){
659       if (preg_match("/$key$/", $tmp)){
660         return ($subtreeACL[$key]);
661       }
662     }
663   }
665   return array("");
669 function get_module_permission($acl_array, $module, $dn)
671   global $ui;
673   $final= "";
674   foreach($acl_array as $acl){
676     /* Check for selfflag (!) in ACL to determine if
677        the user is allowed to change parts of his/her
678        own account */
679     if (preg_match("/^!/", $acl)){
680       if ($dn != "" && $dn != $ui->dn){
682         /* No match for own DN, give up on this ACL */
683         continue;
685       } else {
687         /* Matches own DN, remove the selfflag */
688         $acl= preg_replace("/^!/", "", $acl);
690       }
691     }
693     /* Remove leading garbage */
694     $acl= preg_replace("/^:/", "", $acl);
696     /* Discover if we've access to the submodule by comparing
697        all allowed submodules specified in the ACL */
698     $tmp= split(",", $acl);
699     foreach ($tmp as $mod){
700       if (preg_match("/^$module#/", $mod)){
701         $final= strstr($mod, "#")."#";
702         continue;
703       }
704       if (preg_match("/[^#]$module$/", $mod)){
705         return ("#all#");
706       }
707       if (preg_match("/^all$/", $mod)){
708         return ("#all#");
709       }
710     }
711   }
713   /* Return assembled ACL, or none */
714   if ($final != ""){
715     return (preg_replace('/##/', '#', $final));
716   }
718   /* Nothing matches - disable access for this object */
719   return ("#none#");
723 function get_userinfo()
725   global $ui;
727   return $ui;
731 function get_smarty()
733   global $smarty;
735   return $smarty;
739 function convert_department_dn($dn)
741   $dep= "";
743   /* Build a sub-directory style list of the tree level
744      specified in $dn */
745   foreach (split(',', $dn) as $rdn){
747     /* We're only interested in organizational units... */
748     if (substr($rdn,0,3) == 'ou='){
749       $dep= substr($rdn,3)."/$dep";
750     }
752     /* ... and location objects */
753     if (substr($rdn,0,2) == 'l='){
754       $dep= substr($rdn,2)."/$dep";
755     }
756   }
758   /* Return and remove accidently trailing slashes */
759   return rtrim($dep, "/");
763 /* Strip off the last sub department part of a '/level1/level2/.../'
764  * style value. It removes the trailing '/', too. */
765 function get_sub_department($value)
767   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
771 function get_ou($name)
773   global $config;
775   $ou= $config->current[$name];
776   if ($ou != ""){
777     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
778       return @LDAP::convert("ou=$ou,");
779     } else {
780       return @LDAP::convert("$ou,");
781     }
782   } else {
783     return "";
784   }
788 function get_people_ou()
790   return (get_ou("PEOPLE"));
794 function get_groups_ou()
796   return (get_ou("GROUPS"));
800 function get_winstations_ou()
802   return (get_ou("WINSTATIONS"));
806 function get_base_from_people($dn)
808   global $config;
810   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
811   $base= preg_replace($pattern, '', $dn);
813   /* Set to base, if we're not on a correct subtree */
814   if (!isset($config->idepartments[$base])){
815     $base= $config->current['BASE'];
816   }
818   return ($base);
822 function chkacl($acl, $name)
824   /* Look for attribute in ACL */
825   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
826     return ("");
827   }
829   /* Optically disable html object for no match */
830   return (" disabled ");
834 function is_phone_nr($nr)
836   if ($nr == ""){
837     return (TRUE);
838   }
840   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
844 function is_url($url)
846   if ($url == ""){
847     return (TRUE);
848   }
850   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
854 function is_dn($dn)
856   if ($dn == ""){
857     return (TRUE);
858   }
860   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
864 function is_uid($uid)
866   global $config;
868   if ($uid == ""){
869     return (TRUE);
870   }
872   /* STRICT adds spaces and case insenstivity to the uid check.
873      This is dangerous and should not be used. */
874   if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
875     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
876   } else {
877     return preg_match ("/^[a-z0-9_-]+$/", $uid);
878   }
882 function is_ip($ip)
884   return preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/", $ip);
888 function is_id($id)
890   if ($id == ""){
891     return (FALSE);
892   }
894   return preg_match ("/^[0-9]+$/", $id);
898 function is_path($path)
900   if ($path == ""){
901     return (TRUE);
902   }
903   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
904     return (FALSE);
905   }
907   return preg_match ("/\/.+$/", $path);
911 function is_email($address, $template= FALSE)
913   if ($address == ""){
914     return (TRUE);
915   }
916   if ($template){
917     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
918         $address);
919   } else {
920     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
921         $address);
922   }
926 function print_red()
928   /* Check number of arguments */
929   if (func_num_args() < 1){
930     return;
931   }
933   /* Get arguments, save string */
934   $array = func_get_args();
935   $string= $array[0];
937   /* Step through arguments */
938   for ($i= 1; $i<count($array); $i++){
939     $string= preg_replace ("/%s/", $array[$i], $string, 1);
940   }
942   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
943     $_SESSION['errorsAlreadyPosted'] = array(); 
944   }
946   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
947      the other case... */
949   if (isset($_SESSION['DEBUGLEVEL'])){
951     if($_SESSION['LastError'] == $string){
953       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
954         $_SESSION['errorsAlreadyPosted'][$string] = 1;
955       }
956       $_SESSION['errorsAlreadyPosted'][$string] ++;
958     }else{
959       if((!empty($_SESSION['LastError'])) && ($_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']]>1)){
960         $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
961           "border-style:solid;border-color:red; background-color:black;".
962           "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
963           get_template_path('images/warning.png')."\"></td>".
964           "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
965           "<b style='font-size:16px;'>".sprintf(_("Last message repeated %s times."),$_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']])."</b></font></td><td>".
966           "<img alt=\"\"src=\"".get_template_path('images/warning.png').
967           "\"></td></tr></table></div>\n";
968       }
970       if($string != NULL){
971         $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
972           "border-style:solid;border-color:red; background-color:black;".
973           "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
974           get_template_path('images/warning.png')."\"></td>".
975           "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
976           "<b style='font-size:16px;'>$string</b></font></td><td>".
977           "<img alt=\"\"src=\"".get_template_path('images/warning.png').
978           "\"></td></tr></table></div>\n";
979       }else{
980         return;
981       }
982       $_SESSION['errorsAlreadyPosted'] = array();
983       $_SESSION['errorsAlreadyPosted'][$string] = 1;
985     }
987   } else {
988     echo "Error: $string\n";
989   }
990   $_SESSION['LastError'] = $string; 
995 function gen_locked_message($user, $dn)
997   global $plug, $config;
999   $_SESSION['dn']= $dn;
1000   $ldap= $config->get_ldap_link();
1001   $ldap->cat ($user);
1002   $attrs= $ldap->fetch();
1003   $uid= $attrs["uid"][0];
1004   $cn= $attrs["cn"][0];
1005   $remove= false;
1007   //  print_a($_POST);
1008   //  print_a($_GET);
1010   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1011     $_SESSION['LOCK_VARS_USED']  =array();
1012     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1014       if(empty($name)) continue;
1015       foreach($_POST as $Pname => $Pvalue){
1016         if(preg_match($name,$Pname)){
1017           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1018         }
1019       }
1021       foreach($_GET as $Pname => $Pvalue){
1022         if(preg_match($name,$Pname)){
1023           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1024         }
1025       }
1026     }
1027     $_SESSION['LOCK_VARS_TO_USE'] =array();
1028   }
1030   /* Prepare and show template */
1031   $smarty= get_smarty();
1032   $smarty->assign ("dn", $dn);
1033   if ($remove){
1034     $smarty->assign ("action", _("Continue anyway"));
1035   } else {
1036     $smarty->assign ("action", _("Edit anyway"));
1037   }
1038   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry '%s' which appears to be used by '%s'. Please contact the person in order to clarify proceedings."), "<b>".$dn."</b>", "<b><a href=\"main.php?plug=0&amp;viewid=$uid\">$cn</a></b>"));
1040   return ($smarty->fetch (get_template_path('islocked.tpl')));
1044 function to_string ($value)
1046   /* If this is an array, generate a text blob */
1047   if (is_array($value)){
1048     $ret= "";
1049     foreach ($value as $line){
1050       $ret.= $line."<br>\n";
1051     }
1052     return ($ret);
1053   } else {
1054     return ($value);
1055   }
1059 function get_printer_list($cups_server)
1061   global $config;
1063   $res= array();
1065   /* Use CUPS, if we've access to it */
1066   if (function_exists('cups_get_dest_list')){
1067     $dest_list= cups_get_dest_list ($cups_server);
1069     foreach ($dest_list as $prt){
1070       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1072       foreach ($attr as $prt_info){
1073         if ($prt_info->name == "printer-info"){
1074           $info= $prt_info->value;
1075           break;
1076         }
1077       }
1078       $res[$prt->name]= "$info [$prt->name]";
1079     }
1081     /* CUPS is not available, try lpstat as a replacement */
1082   } else {
1083     $ar = false;
1084     exec("lpstat -p", $ar);
1085     foreach($ar as $val){
1086       list($dummy, $printer, $rest)= split(' ', $val, 3);
1087       if (preg_match('/^[^@]+$/', $printer)){
1088         $res[$printer]= "$printer";
1089       }
1090     }
1091   }
1093   /* Merge in printers from LDAP */
1094   $ldap= $config->get_ldap_link();
1095   $ldap->cd ($config->current['BASE']);
1096   $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1097   while ($attrs= $ldap->fetch()){
1098     $res[$attrs["cn"][0]]= $attrs["cn"][0];
1099   }
1101   return $res;
1105 function sess_del ($var)
1107   /* New style */
1108   unset ($_SESSION[$var]);
1110   /* ... work around, since the first one
1111      doesn't seem to work all the time */
1112   session_unregister ($var);
1116 function show_errors($message)
1118   $complete= "";
1120   /* Assemble the message array to a plain string */
1121   foreach ($message as $error){
1122     if ($complete == ""){
1123       $complete= $error;
1124     } else {
1125       $complete= "$error<br>$complete";
1126     }
1127   }
1129   /* Fill ERROR variable with nice error dialog */
1130   print_red($complete);
1134 function show_ldap_error($message)
1136   if (!preg_match("/Success/i", $message)){
1137     print_red (_("LDAP error:")." $message");
1138     return TRUE;
1139   } else {
1140     return FALSE;
1141   }
1145 function rewrite($s)
1147   global $REWRITE;
1149   foreach ($REWRITE as $key => $val){
1150     $s= preg_replace("/$key/", "$val", $s);
1151   }
1153   return ($s);
1157 function dn2base($dn)
1159   global $config;
1161   if (get_people_ou() != ""){
1162     $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1163   }
1164   if (get_groups_ou() != ""){
1165     $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1166   }
1167   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1169   return ($base);
1174 function check_command($cmdline)
1176   $cmd= preg_replace("/ .*$/", "", $cmdline);
1178   /* Check if command exists in filesystem */
1179   if (!file_exists($cmd)){
1180     return (FALSE);
1181   }
1183   /* Check if command is executable */
1184   if (!is_executable($cmd)){
1185     return (FALSE);
1186   }
1188   return (TRUE);
1192 function print_header($image, $headline, $info= "")
1194   $display= "<div class=\"plugtop\">\n";
1195   $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";
1196   $display.= "</div>\n";
1198   if ($info != ""){
1199     $display.= "<div class=\"pluginfo\">\n";
1200     $display.= "$info";
1201     $display.= "</div>\n";
1202   } else {
1203     $display.= "<div style=\"height:5px;\">\n";
1204     $display.= "&nbsp;";
1205     $display.= "</div>\n";
1206   }
1208   return ($display);
1212 function register_global($name, $object)
1214   $_SESSION[$name]= $object;
1218 function is_global($name)
1220   return isset($_SESSION[$name]);
1224 function get_global($name)
1226   return $_SESSION[$name];
1230 function range_selector($dcnt,$start,$range=25,$post_var=false)
1233   /* Entries shown left and right from the selected entry */
1234   $max_entries= 10;
1236   /* Initialize and take care that max_entries is even */
1237   $output="";
1238   if ($max_entries & 1){
1239     $max_entries++;
1240   }
1242   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1243     $range= $_POST[$post_var];
1244   }
1246   /* Prevent output to start or end out of range */
1247   if ($start < 0 ){
1248     $start= 0 ;
1249   }
1250   if ($start >= $dcnt){
1251     $start= $range * (int)(($dcnt / $range) + 0.5);
1252   }
1254   $numpages= (($dcnt / $range));
1255   if(((int)($numpages))!=($numpages)){
1256     $numpages = (int)$numpages + 1;
1257   }
1258   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1259     return ("");
1260   }
1261   $ppage= (int)(($start / $range) + 0.5);
1264   /* Align selected page to +/- max_entries/2 */
1265   $begin= $ppage - $max_entries/2;
1266   $end= $ppage + $max_entries/2;
1268   /* Adjust begin/end, so that the selected value is somewhere in
1269      the middle and the size is max_entries if possible */
1270   if ($begin < 0){
1271     $end-= $begin + 1;
1272     $begin= 0;
1273   }
1274   if ($end > $numpages) {
1275     $end= $numpages;
1276   }
1277   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1278     $begin= $end - $max_entries;
1279   }
1281   if($post_var){
1282     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1283       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1284   }else{
1285     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1286   }
1288   /* Draw decrement */
1289   if ($start > 0 ) {
1290     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1291       (($start-$range))."\">".
1292       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1293   }
1295   /* Draw pages */
1296   for ($i= $begin; $i < $end; $i++) {
1297     if ($ppage == $i){
1298       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1299         validate($_GET['plug'])."&amp;start=".
1300         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1301     } else {
1302       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1303         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1304     }
1305   }
1307   /* Draw increment */
1308   if($start < ($dcnt-$range)) {
1309     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1310       (($start+($range)))."\">".
1311       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1312   }
1314   if(($post_var)&&($numpages)){
1315     $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()'>";
1316     foreach(array(20,50,100,200,"all") as $num){
1317       if($num == "all"){
1318         $var = 10000;
1319       }else{
1320         $var = $num;
1321       }
1322       if($var == $range){
1323         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1324       }else{  
1325         $output.="\n<option value='".$var."'>".$num."</option>";
1326       }
1327     }
1328     $output.=  "</select></td></tr></table></div>";
1329   }else{
1330     $output.= "</div>";
1331   }
1333   return($output);
1337 function apply_filter()
1339   $apply= "";
1341   $apply= ''.
1342     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1343     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1345   return ($apply);
1349 function back_to_main()
1351   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1352     _("Back").'"></p><input type="hidden" name="ignore">';
1354   return ($string);
1358 function normalize_netmask($netmask)
1360   /* Check for notation of netmask */
1361   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1362     $num= (int)($netmask);
1363     $netmask= "";
1365     for ($byte= 0; $byte<4; $byte++){
1366       $result=0;
1368       for ($i= 7; $i>=0; $i--){
1369         if ($num-- > 0){
1370           $result+= pow(2,$i);
1371         }
1372       }
1374       $netmask.= $result.".";
1375     }
1377     return (preg_replace('/\.$/', '', $netmask));
1378   }
1380   return ($netmask);
1384 function netmask_to_bits($netmask)
1386   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1387   $res= 0;
1389   for ($n= 0; $n<4; $n++){
1390     $start= 255;
1391     $name= "nm$n";
1393     for ($i= 0; $i<8; $i++){
1394       if ($start == (int)($$name)){
1395         $res+= 8 - $i;
1396         break;
1397       }
1398       $start-= pow(2,$i);
1399     }
1400   }
1402   return ($res);
1406 function recurse($rule, $variables)
1408   $result= array();
1410   if (!count($variables)){
1411     return array($rule);
1412   }
1414   reset($variables);
1415   $key= key($variables);
1416   $val= current($variables);
1417   unset ($variables[$key]);
1419   foreach($val as $possibility){
1420     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1421     $result= array_merge($result, recurse($nrule, $variables));
1422   }
1424   return ($result);
1428 function expand_id($rule, $attributes)
1430   /* Check for id rule */
1431   if(preg_match('/^id(:|#)\d+$/',$rule)){
1432     return (array("\{$rule}"));
1433   }
1435   /* Check for clean attribute */
1436   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1437     $rule= preg_replace('/^%/', '', $rule);
1438     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1439     return (array($val));
1440   }
1442   /* Check for attribute with parameters */
1443   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1444     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1445     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1446     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1447     $start= preg_replace ('/-.*$/', '', $param);
1448     $stop = preg_replace ('/^[^-]+-/', '', $param);
1450     /* Assemble results */
1451     $result= array();
1452     for ($i= $start; $i<= $stop; $i++){
1453       $result[]= substr($val, 0, $i);
1454     }
1455     return ($result);
1456   }
1458   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1459   return (array($rule));
1463 function gen_uids($rule, $attributes)
1465   global $config;
1467   /* Search for keys and fill the variables array with all 
1468      possible values for that key. */
1469   $part= "";
1470   $trigger= false;
1471   $stripped= "";
1472   $variables= array();
1474   for ($pos= 0; $pos < strlen($rule); $pos++){
1476     if ($rule[$pos] == "{" ){
1477       $trigger= true;
1478       $part= "";
1479       continue;
1480     }
1482     if ($rule[$pos] == "}" ){
1483       $variables[$pos]= expand_id($part, $attributes);
1484       $stripped.= "\{$pos}";
1485       $trigger= false;
1486       continue;
1487     }
1489     if ($trigger){
1490       $part.= $rule[$pos];
1491     } else {
1492       $stripped.= $rule[$pos];
1493     }
1494   }
1496   /* Recurse through all possible combinations */
1497   $proposed= recurse($stripped, $variables);
1499   /* Get list of used ID's */
1500   $used= array();
1501   $ldap= $config->get_ldap_link();
1502   $ldap->cd($config->current['BASE']);
1503   $ldap->search('(uid=*)');
1505   while($attrs= $ldap->fetch()){
1506     $used[]= $attrs['uid'][0];
1507   }
1509   /* Remove used uids and watch out for id tags */
1510   $ret= array();
1511   foreach($proposed as $uid){
1513     /* Check for id tag and modify uid if needed */
1514     if(preg_match('/\{id:\d+}/',$uid)){
1515       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1517       for ($i= 0; $i < pow(10,$size); $i++){
1518         $number= sprintf("%0".$size."d", $i);
1519         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1520         if (!in_array($res, $used)){
1521           $uid= $res;
1522           break;
1523         }
1524       }
1525     }
1527   if(preg_match('/\{id#\d+}/',$uid)){
1528     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1530     while (true){
1531       mt_srand((double) microtime()*1000000);
1532       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1533       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1534       if (!in_array($res, $used)){
1535         $uid= $res;
1536         break;
1537       }
1538     }
1539   }
1541 /* Don't assign used ones */
1542 if (!in_array($uid, $used)){
1543   $ret[]= $uid;
1547 return(array_unique($ret));
1551 function array_search_r($needle, $key, $haystack){
1553   foreach($haystack as $index => $value){
1554     $match= 0;
1556     if (is_array($value)){
1557       $match= array_search_r($needle, $key, $value);
1558     }
1560     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1561       $match=1;
1562     }
1564     if ($match){
1565       return 1;
1566     }
1567   }
1569   return 0;
1570
1573 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1574    Need to convert... */
1575 function to_byte($value) {
1576   $value= strtolower(trim($value));
1578   if(!is_numeric(substr($value, -1))) {
1580     switch(substr($value, -1)) {
1581       case 'g':
1582         $mult= 1073741824;
1583         break;
1584       case 'm':
1585         $mult= 1048576;
1586         break;
1587       case 'k':
1588         $mult= 1024;
1589         break;
1590     }
1592     return ($mult * (int)substr($value, 0, -1));
1593   } else {
1594     return $value;
1595   }
1599 function in_array_ics($value, $items)
1601   if (!is_array($items)){
1602     return (FALSE);
1603   }
1605   foreach ($items as $item){
1606     if (strtolower($item) == strtolower($value)) {
1607       return (TRUE);
1608     }
1609   }
1611   return (FALSE);
1612
1615 function generate_alphabet($count= 10)
1617   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1618   $alphabet= "";
1619   $c= 0;
1621   /* Fill cells with charaters */
1622   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1623     if ($c == 0){
1624       $alphabet.= "<tr>";
1625     }
1627     $ch = mb_substr($characters, $i, 1, "UTF8");
1628     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1629       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1631     if ($c++ == $count){
1632       $alphabet.= "</tr>";
1633       $c= 0;
1634     }
1635   }
1637   /* Fill remaining cells */
1638   while ($c++ <= $count){
1639     $alphabet.= "<td>&nbsp;</td>";
1640   }
1642   return ($alphabet);
1646 function validate($string)
1648   return (strip_tags(preg_replace('/\0/', '', $string)));
1651 function get_gosa_version()
1653   global $svn_revision, $svn_path;
1655   /* Extract informations */
1656   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1658   /* Release or development? */
1659   if (preg_match('%/gosa/trunk/%', $svn_path)){
1660     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1661   } else {
1662     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1663     return (sprintf(_("GOsa $release"), $revision));
1664   }
1668 function rmdirRecursive($path, $followLinks=false) {
1669   $dir= opendir($path);
1670   while($entry= readdir($dir)) {
1671     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1672       unlink($path."/".$entry);
1673     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1674       rmdirRecursive($path."/".$entry);
1675     }
1676   }
1677   closedir($dir);
1678   return rmdir($path);
1681 function scan_directory($path,$sort_desc=false)
1683   $ret = false;
1685   /* is this a dir ? */
1686   if(is_dir($path)) {
1688     /* is this path a readable one */
1689     if(is_readable($path)){
1691       /* Get contents and write it into an array */   
1692       $ret = array();    
1694       $dir = opendir($path);
1696       /* Is this a correct result ?*/
1697       if($dir){
1698         while($fp = readdir($dir))
1699           $ret[]= $fp;
1700       }
1701     }
1702   }
1703   /* Sort array ascending , like scandir */
1704   sort($ret);
1706   /* Sort descending if parameter is sort_desc is set */
1707   if($sort_desc) {
1708     $ret = array_reverse($ret);
1709   }
1711   return($ret);
1714 function clean_smarty_compile_dir($directory)
1716   global $svn_revision;
1718   if(is_dir($directory) && is_readable($directory)) {
1719     // Set revision filename to REVISION
1720     $revision_file= $directory."/REVISION";
1722     /* Is there a stamp containing the current revision? */
1723     if(!file_exists($revision_file)) {
1724       // create revision file
1725       create_revision($revision_file, $svn_revision);
1726     } else {
1727 # check for "$config->...['CONFIG']/revision" and the
1728 # contents should match the revision number
1729       if(!compare_revision($revision_file, $svn_revision)){
1730         // If revision differs, clean compile directory
1731         foreach(scan_directory($directory) as $file) {
1732           if(($file==".")||($file=="..")) continue;
1733           if( is_file($directory."/".$file) &&
1734               is_writable($directory."/".$file)) {
1735             // delete file
1736             if(!unlink($directory."/".$file)) {
1737               print_red("File ".$directory."/".$file." could not be deleted.");
1738               // This should never be reached
1739             }
1740           } elseif(is_dir($directory."/".$file) &&
1741               is_writable($directory."/".$file)) {
1742             // Just recursively delete it
1743             rmdirRecursive($directory."/".$file);
1744           }
1745         }
1746         // We should now create a fresh revision file
1747         clean_smarty_compile_dir($directory);
1748       } else {
1749         // Revision matches, nothing to do
1750       }
1751     }
1752   } else {
1753     // Smarty compile dir is not accessible
1754     // (Smarty will warn about this)
1755   }
1758 function create_revision($revision_file, $revision)
1760   $result= false;
1762   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1763     if($fh= fopen($revision_file, "w")) {
1764       if(fwrite($fh, $revision)) {
1765         $result= true;
1766       }
1767     }
1768     fclose($fh);
1769   } else {
1770     print_red("Can not write to revision file");
1771   }
1773   return $result;
1776 function compare_revision($revision_file, $revision)
1778   // false means revision differs
1779   $result= false;
1781   if(file_exists($revision_file) && is_readable($revision_file)) {
1782     // Open file
1783     if($fh= fopen($revision_file, "r")) {
1784       // Compare File contents with current revision
1785       if($revision == fread($fh, filesize($revision_file))) {
1786         $result= true;
1787       }
1788     } else {
1789       print_red("Can not open revision file");
1790     }
1791     // Close file
1792     fclose($fh);
1793   }
1795   return $result;
1798 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1800   $str = ""; // Our return value will be saved in this var
1802   $color  = dechex($percentage+150);
1803   $color2 = dechex(150 - $percentage);
1804   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1806   $progress = (int)(($percentage /100)*$width);
1808   /* Abort printing out percentage, if divs are to small */
1811   /* If theres a better solution for this, use it... */
1812   $str = "
1813     <div style=\" width:".($width)."px; 
1814     height:".($height)."px;
1815   background-color:#000000;
1816 padding:1px;\">
1818           <div style=\" width:".($width)."px;
1819         background-color:#$bgcolor;
1820 height:".($height)."px;\">
1822          <div style=\" width:".$progress."px;
1823 height:".$height."px;
1824        background-color:#".$color2.$color2.$color."; \">";
1827        if(($height >10)&&($showvalue)){
1828          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1829            <b>".$percentage."%</b>
1830            </font>";
1831        }
1833        $str.= "</div></div></div>";
1835        return($str);
1839 function array_key_ics($ikey, $items)
1841   /* Gather keys, make them lowercase */
1842   $tmp= array();
1843   foreach ($items as $key => $value){
1844     $tmp[strtolower($key)]= $key;
1845   }
1847   if (isset($tmp[strtolower($ikey)])){
1848     return($tmp[strtolower($ikey)]);
1849   }
1851   return ("");
1855 function search_config($arr, $name, $return)
1857   if (is_array($arr)){
1858     foreach ($arr as $a){
1859       if (isset($a['CLASS']) &&
1860           strtolower($a['CLASS']) == strtolower($name)){
1862         if (isset($a[$return])){
1863           return ($a[$return]);
1864         } else {
1865           return ("");
1866         }
1867       } else {
1868         $res= search_config ($a, $name, $return);
1869         if ($res != ""){
1870           return $res;
1871         }
1872       }
1873     }
1874   }
1875   return ("");
1879 function array_differs($src, $dst)
1881   /* If the count is differing, the arrays differ */
1882   if (count ($src) != count ($dst)){
1883     return (TRUE);
1884   }
1886   /* So the count is the same - lets check the contents */
1887   $differs= FALSE;
1888   foreach($src as $value){
1889     if (!in_array($value, $dst)){
1890       $differs= TRUE;
1891     }
1892   }
1894   return ($differs);
1898 function saveFilter($a_filter, $values)
1900   if (isset($_POST['regexit'])){
1901     $a_filter["regex"]= $_POST['regexit'];
1903     foreach($values as $type){
1904       if (isset($_POST[$type])) {
1905         $a_filter[$type]= "checked";
1906       } else {
1907         $a_filter[$type]= "";
1908       }
1909     }
1910   }
1912   /* React on alphabet links if needed */
1913   if (isset($_GET['search'])){
1914     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
1915     if ($s == "**"){
1916       $s= "*";
1917     }
1918     $a_filter['regex']= $s;
1919   }
1921   return ($a_filter);
1925 /* Escape all preg_* relevant characters */
1926 function normalizePreg($input)
1928   return (addcslashes($input, '[]()|/.*+-'));
1932 /* Escape all LDAP filter relevant characters */
1933 function normalizeLdap($input)
1935   return (addcslashes($input, '()|'));
1939 /* Resturns the difference between to microtime() results in float  */
1940 function get_MicroTimeDiff($start , $stop)
1942   $a = split("\ ",$start);
1943   $b = split("\ ",$stop);
1945   $secs = $b[1] - $a[1];
1946   $msecs= $b[0] - $a[0]; 
1948   $ret = (float) ($secs+ $msecs);
1949   return($ret);
1953 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1954 ?>