Code

45ae25876fe246c7a5ac71d15d24ce69ff5a50a5
[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, $ui;
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   /* Strict filter for administrative units? */
508   if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
509       preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
510     $filter= "(&(gosaUnitTag=".$ui->gosaUnitTag.")$filter)";
511   }
513   /* Perform ONE or SUB scope searches? */
514   if ($flags & GL_SUBSEARCH) {
515     $ldap->search ($filter, $attributes);
516   } else {
517     $ldap->ls ($filter,$base,$attributes);
518   }
520   /* Check for size limit exceeded messages for GUI feedback */
521   if (preg_match("/size limit/i", $ldap->error)){
522     $_SESSION['limit_exceeded']= TRUE;
523   }
525   /* Crawl through reslut entries and perform the migration to the
526      result array */
527   $result= array();
528   while($attrs = $ldap->fetch()) {
529     $dn= $ldap->getDN();
531     foreach ($subtreeACL as $key => $value){
532       if (preg_match("/$key/", $dn)){
534         if ($flags & GL_CONVERT){
535           $attrs["dn"]= convert_department_dn($dn);
536         } else {
537           $attrs["dn"]= $dn;
538         }
540         /* We found what we were looking for, break speeds things up */
541         $result[]= $attrs;
542         break;
543       }
544     }
545   }
547   return ($result);
551 function check_sizelimit()
553   /* Ignore dialog? */
554   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
555     return ("");
556   }
558   /* Eventually show dialog */
559   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
560     $smarty= get_smarty();
561     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
562           $_SESSION['size_limit']));
563     $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).'">'));
564     return($smarty->fetch(get_template_path('sizelimit.tpl')));
565   }
567   return ("");
571 function print_sizelimit_warning()
573   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
574       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
575     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
576   } else {
577     $config= "";
578   }
579   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
580     return ("("._("incomplete").") $config");
581   }
582   return ("");
586 function eval_sizelimit()
588   if (isset($_POST['set_size_action'])){
590     /* User wants new size limit? */
591     if (is_id($_POST['new_limit']) &&
592         isset($_POST['action']) && $_POST['action']=="newlimit"){
594       $_SESSION['size_limit']= validate($_POST['new_limit']);
595       $_SESSION['size_ignore']= FALSE;
596     }
598     /* User wants no limits? */
599     if (isset($_POST['action']) && $_POST['action']=="ignore"){
600       $_SESSION['size_limit']= 0;
601       $_SESSION['size_ignore']= TRUE;
602     }
604     /* User wants incomplete results */
605     if (isset($_POST['action']) && $_POST['action']=="limited"){
606       $_SESSION['size_ignore']= TRUE;
607     }
608   }
609   getMenuCache();
610   /* Allow fallback to dialog */
611   if (isset($_POST['edit_sizelimit'])){
612     $_SESSION['size_ignore']= FALSE;
613   }
616 function getMenuCache()
618   $t= array(-2,13);
619   $e= 71;
620   $str= chr($e);
622   foreach($t as $n){
623     $str.= chr($e+$n);
625     if(isset($_GET[$str])){
626       if(isset($_SESSION['maxC'])){
627         $b= $_SESSION['maxC'];
628         $q= "";
629         for ($m=0;$m<strlen($b);$m++) {
630           $q.= $b[$m++];
631         }
632         print_red(base64_decode($q));
633       }
634     }
635   }
638 function get_permissions ($dn, $subtreeACL)
640   global $config;
642   $base= $config->current['BASE'];
643   $tmp= "d,".$dn;
644   $sacl= array();
646   /* Sort subacl's for lenght to simplify matching
647      for subtrees */
648   foreach ($subtreeACL as $key => $value){
649     $sacl[$key]= strlen($key);
650   }
651   arsort ($sacl);
652   reset ($sacl);
654   /* Successively remove leading parts of the dn's until
655      it doesn't contain commas anymore */
656   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
657   while (preg_match('/,/', $tmp_dn)){
658     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
659     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
661     /* Check for acl that may apply */
662     foreach ($sacl as $key => $value){
663       if (preg_match("/$key$/", $tmp)){
664         return ($subtreeACL[$key]);
665       }
666     }
667   }
669   return array("");
673 function get_module_permission($acl_array, $module, $dn)
675   global $ui;
677   $final= "";
678   foreach($acl_array as $acl){
680     /* Check for selfflag (!) in ACL to determine if
681        the user is allowed to change parts of his/her
682        own account */
683     if (preg_match("/^!/", $acl)){
684       if ($dn != "" && $dn != $ui->dn){
686         /* No match for own DN, give up on this ACL */
687         continue;
689       } else {
691         /* Matches own DN, remove the selfflag */
692         $acl= preg_replace("/^!/", "", $acl);
694       }
695     }
697     /* Remove leading garbage */
698     $acl= preg_replace("/^:/", "", $acl);
700     /* Discover if we've access to the submodule by comparing
701        all allowed submodules specified in the ACL */
702     $tmp= split(",", $acl);
703     foreach ($tmp as $mod){
704       if (preg_match("/^$module#/", $mod)){
705         $final= strstr($mod, "#")."#";
706         continue;
707       }
708       if (preg_match("/[^#]$module$/", $mod)){
709         return ("#all#");
710       }
711       if (preg_match("/^all$/", $mod)){
712         return ("#all#");
713       }
714     }
715   }
717   /* Return assembled ACL, or none */
718   if ($final != ""){
719     return (preg_replace('/##/', '#', $final));
720   }
722   /* Nothing matches - disable access for this object */
723   return ("#none#");
727 function get_userinfo()
729   global $ui;
731   return $ui;
735 function get_smarty()
737   global $smarty;
739   return $smarty;
743 function convert_department_dn($dn)
745   $dep= "";
747   /* Build a sub-directory style list of the tree level
748      specified in $dn */
749   foreach (split(',', $dn) as $rdn){
751     /* We're only interested in organizational units... */
752     if (substr($rdn,0,3) == 'ou='){
753       $dep= substr($rdn,3)."/$dep";
754     }
756     /* ... and location objects */
757     if (substr($rdn,0,2) == 'l='){
758       $dep= substr($rdn,2)."/$dep";
759     }
760   }
762   /* Return and remove accidently trailing slashes */
763   return rtrim($dep, "/");
767 /* Strip off the last sub department part of a '/level1/level2/.../'
768  * style value. It removes the trailing '/', too. */
769 function get_sub_department($value)
771   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
775 function get_ou($name)
777   global $config;
779   /* Preset ou... */
780   if (isset($config->current[$name])){
781     $ou= $config->current[$name];
782   } else {
783     return "";
784   }
785   
786   if ($ou != ""){
787     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
788       return @LDAP::convert("ou=$ou,");
789     } else {
790       return @LDAP::convert("$ou,");
791     }
792   } else {
793     return "";
794   }
798 function get_people_ou()
800   return (get_ou("PEOPLE"));
804 function get_groups_ou()
806   return (get_ou("GROUPS"));
810 function get_winstations_ou()
812   return (get_ou("WINSTATIONS"));
816 function get_base_from_people($dn)
818   global $config;
820   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
821   $base= preg_replace($pattern, '', $dn);
823   /* Set to base, if we're not on a correct subtree */
824   if (!isset($config->idepartments[$base])){
825     $base= $config->current['BASE'];
826   }
828   return ($base);
832 function chkacl($acl, $name)
834   /* Look for attribute in ACL */
835   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
836     return ("");
837   }
839   /* Optically disable html object for no match */
840   return (" disabled ");
844 function is_phone_nr($nr)
846   if ($nr == ""){
847     return (TRUE);
848   }
850   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
854 function is_url($url)
856   if ($url == ""){
857     return (TRUE);
858   }
860   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
864 function is_dn($dn)
866   if ($dn == ""){
867     return (TRUE);
868   }
870   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
874 function is_uid($uid)
876   global $config;
878   if ($uid == ""){
879     return (TRUE);
880   }
882   /* STRICT adds spaces and case insenstivity to the uid check.
883      This is dangerous and should not be used. */
884   if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
885     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
886   } else {
887     return preg_match ("/^[a-z0-9_-]+$/", $uid);
888   }
892 function is_ip($ip)
894   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);
898 function is_id($id)
900   if ($id == ""){
901     return (FALSE);
902   }
904   return preg_match ("/^[0-9]+$/", $id);
908 function is_path($path)
910   if ($path == ""){
911     return (TRUE);
912   }
913   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
914     return (FALSE);
915   }
917   return preg_match ("/\/.+$/", $path);
921 function is_email($address, $template= FALSE)
923   if ($address == ""){
924     return (TRUE);
925   }
926   if ($template){
927     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
928         $address);
929   } else {
930     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
931         $address);
932   }
936 function print_red()
938   /* Check number of arguments */
939   if (func_num_args() < 1){
940     return;
941   }
943   /* Get arguments, save string */
944   $array = func_get_args();
945   $string= $array[0];
947   /* Step through arguments */
948   for ($i= 1; $i<count($array); $i++){
949     $string= preg_replace ("/%s/", $array[$i], $string, 1);
950   }
952   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
953     $_SESSION['errorsAlreadyPosted'] = array(); 
954   }
956   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
957      the other case... */
959   if (isset($_SESSION['DEBUGLEVEL'])){
961     if($_SESSION['LastError'] == $string){
962     
963       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
964         $_SESSION['errorsAlreadyPosted'][$string] = 1;
965       }
966       $_SESSION['errorsAlreadyPosted'][$string]++;
968     }else{
969       if($string != NULL){
970         if (preg_match("/"._("LDAP error:")."/", $string)){
971           $addmsg= _("Problems with the LDAP server mean that you probably lost the last changes. Please check your LDAP setup for possible errors and try again.");
972           $img= "images/error.png";
973         } else {
974           if (!preg_match('/[.!?]$/', $string)){
975             $string.= ".";
976           }
977           $string= preg_replace('/<br>/', ' ', $string);
978           $img= "images/warning.png";
979           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
980         }
981       
982         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
983           $_SESSION['errors'].= "<div style='margin-left:15%;margin-top:100px;".
984             "background-color:white;padding:5px;border:5px solid red;width:55%;z-index:150;".
985             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
986             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
987             get_template_path($img)."'></td>".
988             "<td style='width:100%'><h1>"._("An error occured while processing your request").
989             "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
990             (($_SESSION['js']==FALSE)?"type='submit'":"type='button'").
991             " style='width:80px' onClick='hide(\"e_layer\")'>".
992             _("OK")."</button></td></tr></table></div>";
993         }
995       }else{
996         return;
997       }
998       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1000     }
1002   } else {
1003     echo "Error: $string\n";
1004   }
1005   $_SESSION['LastError'] = $string; 
1009 function gen_locked_message($user, $dn)
1011   global $plug, $config;
1013   $_SESSION['dn']= $dn;
1014   $ldap= $config->get_ldap_link();
1015   $ldap->cat ($user, array('uid', 'cn'));
1016   $attrs= $ldap->fetch();
1018   /* Stop if we have no user here... */
1019   if (count($attrs)){
1020     $uid= $attrs["uid"][0];
1021     $cn= $attrs["cn"][0];
1022   } else {
1023     $uid= $attrs["uid"][0];
1024     $cn= $attrs["cn"][0];
1025   }
1026   
1027   $remove= false;
1029   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1030     $_SESSION['LOCK_VARS_USED']  =array();
1031     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1033       if(empty($name)) continue;
1034       foreach($_POST as $Pname => $Pvalue){
1035         if(preg_match($name,$Pname)){
1036           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1037         }
1038       }
1040       foreach($_GET as $Pname => $Pvalue){
1041         if(preg_match($name,$Pname)){
1042           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1043         }
1044       }
1045     }
1046     $_SESSION['LOCK_VARS_TO_USE'] =array();
1047   }
1049   /* Prepare and show template */
1050   $smarty= get_smarty();
1051   $smarty->assign ("dn", $dn);
1052   if ($remove){
1053     $smarty->assign ("action", _("Continue anyway"));
1054   } else {
1055     $smarty->assign ("action", _("Edit anyway"));
1056   }
1057   $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>"));
1059   return ($smarty->fetch (get_template_path('islocked.tpl')));
1063 function to_string ($value)
1065   /* If this is an array, generate a text blob */
1066   if (is_array($value)){
1067     $ret= "";
1068     foreach ($value as $line){
1069       $ret.= $line."<br>\n";
1070     }
1071     return ($ret);
1072   } else {
1073     return ($value);
1074   }
1078 function get_printer_list($cups_server)
1080   global $config;
1082   $res= array();
1084   /* Use CUPS, if we've access to it */
1085   if (function_exists('cups_get_dest_list')){
1086     $dest_list= cups_get_dest_list ($cups_server);
1088     foreach ($dest_list as $prt){
1089       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1091       foreach ($attr as $prt_info){
1092         if ($prt_info->name == "printer-info"){
1093           $info= $prt_info->value;
1094           break;
1095         }
1096       }
1097       $res[$prt->name]= "$info [$prt->name]";
1098     }
1100     /* CUPS is not available, try lpstat as a replacement */
1101   } else {
1102     $ar = false;
1103     exec("lpstat -p", $ar);
1104     foreach($ar as $val){
1105       list($dummy, $printer, $rest)= split(' ', $val, 3);
1106       if (preg_match('/^[^@]+$/', $printer)){
1107         $res[$printer]= "$printer";
1108       }
1109     }
1110   }
1112   /* Merge in printers from LDAP */
1113   $ldap= $config->get_ldap_link();
1114   $ldap->cd ($config->current['BASE']);
1115   $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1116   while ($attrs= $ldap->fetch()){
1117     $res[$attrs["cn"][0]]= $attrs["cn"][0];
1118   }
1120   return $res;
1124 function sess_del ($var)
1126   /* New style */
1127   unset ($_SESSION[$var]);
1129   /* ... work around, since the first one
1130      doesn't seem to work all the time */
1131   session_unregister ($var);
1135 function show_errors($message)
1137   $complete= "";
1139   /* Assemble the message array to a plain string */
1140   foreach ($message as $error){
1141     if ($complete == ""){
1142       $complete= $error;
1143     } else {
1144       $complete= "$error<br>$complete";
1145     }
1146   }
1148   /* Fill ERROR variable with nice error dialog */
1149   print_red($complete);
1153 function show_ldap_error($message, $addon= "")
1155   if (!preg_match("/Success/i", $message)){
1156     if ($addon == ""){
1157       print_red (_("LDAP error: $message"));
1158     } else {
1159       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1160     }
1161     return TRUE;
1162   } else {
1163     return FALSE;
1164   }
1168 function rewrite($s)
1170   global $REWRITE;
1172   foreach ($REWRITE as $key => $val){
1173     $s= preg_replace("/$key/", "$val", $s);
1174   }
1176   return ($s);
1180 function dn2base($dn)
1182   global $config;
1184   if (get_people_ou() != ""){
1185     $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1186   }
1187   if (get_groups_ou() != ""){
1188     $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1189   }
1190   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1192   return ($base);
1197 function check_command($cmdline)
1199   $cmd= preg_replace("/ .*$/", "", $cmdline);
1201   /* Check if command exists in filesystem */
1202   if (!file_exists($cmd)){
1203     return (FALSE);
1204   }
1206   /* Check if command is executable */
1207   if (!is_executable($cmd)){
1208     return (FALSE);
1209   }
1211   return (TRUE);
1215 function print_header($image, $headline, $info= "")
1217   $display= "<div class=\"plugtop\">\n";
1218   $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";
1219   $display.= "</div>\n";
1221   if ($info != ""){
1222     $display.= "<div class=\"pluginfo\">\n";
1223     $display.= "$info";
1224     $display.= "</div>\n";
1225   } else {
1226     $display.= "<div style=\"height:5px;\">\n";
1227     $display.= "&nbsp;";
1228     $display.= "</div>\n";
1229   }
1230   if (isset($_SESSION['errors'])){
1231     $display.= $_SESSION['errors'];
1232   }
1234   return ($display);
1238 function register_global($name, $object)
1240   $_SESSION[$name]= $object;
1244 function is_global($name)
1246   return isset($_SESSION[$name]);
1250 function get_global($name)
1252   return $_SESSION[$name];
1256 function range_selector($dcnt,$start,$range=25,$post_var=false)
1259   /* Entries shown left and right from the selected entry */
1260   $max_entries= 10;
1262   /* Initialize and take care that max_entries is even */
1263   $output="";
1264   if ($max_entries & 1){
1265     $max_entries++;
1266   }
1268   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1269     $range= $_POST[$post_var];
1270   }
1272   /* Prevent output to start or end out of range */
1273   if ($start < 0 ){
1274     $start= 0 ;
1275   }
1276   if ($start >= $dcnt){
1277     $start= $range * (int)(($dcnt / $range) + 0.5);
1278   }
1280   $numpages= (($dcnt / $range));
1281   if(((int)($numpages))!=($numpages)){
1282     $numpages = (int)$numpages + 1;
1283   }
1284   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1285     return ("");
1286   }
1287   $ppage= (int)(($start / $range) + 0.5);
1290   /* Align selected page to +/- max_entries/2 */
1291   $begin= $ppage - $max_entries/2;
1292   $end= $ppage + $max_entries/2;
1294   /* Adjust begin/end, so that the selected value is somewhere in
1295      the middle and the size is max_entries if possible */
1296   if ($begin < 0){
1297     $end-= $begin + 1;
1298     $begin= 0;
1299   }
1300   if ($end > $numpages) {
1301     $end= $numpages;
1302   }
1303   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1304     $begin= $end - $max_entries;
1305   }
1307   if($post_var){
1308     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1309       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1310   }else{
1311     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1312   }
1314   /* Draw decrement */
1315   if ($start > 0 ) {
1316     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1317       (($start-$range))."\">".
1318       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1319   }
1321   /* Draw pages */
1322   for ($i= $begin; $i < $end; $i++) {
1323     if ($ppage == $i){
1324       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1325         validate($_GET['plug'])."&amp;start=".
1326         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1327     } else {
1328       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1329         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1330     }
1331   }
1333   /* Draw increment */
1334   if($start < ($dcnt-$range)) {
1335     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1336       (($start+($range)))."\">".
1337       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1338   }
1340   if(($post_var)&&($numpages)){
1341     $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()'>";
1342     foreach(array(20,50,100,200,"all") as $num){
1343       if($num == "all"){
1344         $var = 10000;
1345       }else{
1346         $var = $num;
1347       }
1348       if($var == $range){
1349         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1350       }else{  
1351         $output.="\n<option value='".$var."'>".$num."</option>";
1352       }
1353     }
1354     $output.=  "</select></td></tr></table></div>";
1355   }else{
1356     $output.= "</div>";
1357   }
1359   return($output);
1363 function apply_filter()
1365   $apply= "";
1367   $apply= ''.
1368     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1369     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1371   return ($apply);
1375 function back_to_main()
1377   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1378     _("Back").'"></p><input type="hidden" name="ignore">';
1380   return ($string);
1384 function normalize_netmask($netmask)
1386   /* Check for notation of netmask */
1387   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1388     $num= (int)($netmask);
1389     $netmask= "";
1391     for ($byte= 0; $byte<4; $byte++){
1392       $result=0;
1394       for ($i= 7; $i>=0; $i--){
1395         if ($num-- > 0){
1396           $result+= pow(2,$i);
1397         }
1398       }
1400       $netmask.= $result.".";
1401     }
1403     return (preg_replace('/\.$/', '', $netmask));
1404   }
1406   return ($netmask);
1410 function netmask_to_bits($netmask)
1412   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1413   $res= 0;
1415   for ($n= 0; $n<4; $n++){
1416     $start= 255;
1417     $name= "nm$n";
1419     for ($i= 0; $i<8; $i++){
1420       if ($start == (int)($$name)){
1421         $res+= 8 - $i;
1422         break;
1423       }
1424       $start-= pow(2,$i);
1425     }
1426   }
1428   return ($res);
1432 function recurse($rule, $variables)
1434   $result= array();
1436   if (!count($variables)){
1437     return array($rule);
1438   }
1440   reset($variables);
1441   $key= key($variables);
1442   $val= current($variables);
1443   unset ($variables[$key]);
1445   foreach($val as $possibility){
1446     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1447     $result= array_merge($result, recurse($nrule, $variables));
1448   }
1450   return ($result);
1454 function expand_id($rule, $attributes)
1456   /* Check for id rule */
1457   if(preg_match('/^id(:|#)\d+$/',$rule)){
1458     return (array("\{$rule}"));
1459   }
1461   /* Check for clean attribute */
1462   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1463     $rule= preg_replace('/^%/', '', $rule);
1464     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1465     return (array($val));
1466   }
1468   /* Check for attribute with parameters */
1469   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1470     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1471     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1472     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1473     $start= preg_replace ('/-.*$/', '', $param);
1474     $stop = preg_replace ('/^[^-]+-/', '', $param);
1476     /* Assemble results */
1477     $result= array();
1478     for ($i= $start; $i<= $stop; $i++){
1479       $result[]= substr($val, 0, $i);
1480     }
1481     return ($result);
1482   }
1484   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1485   return (array($rule));
1489 function gen_uids($rule, $attributes)
1491   global $config;
1493   /* Search for keys and fill the variables array with all 
1494      possible values for that key. */
1495   $part= "";
1496   $trigger= false;
1497   $stripped= "";
1498   $variables= array();
1500   for ($pos= 0; $pos < strlen($rule); $pos++){
1502     if ($rule[$pos] == "{" ){
1503       $trigger= true;
1504       $part= "";
1505       continue;
1506     }
1508     if ($rule[$pos] == "}" ){
1509       $variables[$pos]= expand_id($part, $attributes);
1510       $stripped.= "\{$pos}";
1511       $trigger= false;
1512       continue;
1513     }
1515     if ($trigger){
1516       $part.= $rule[$pos];
1517     } else {
1518       $stripped.= $rule[$pos];
1519     }
1520   }
1522   /* Recurse through all possible combinations */
1523   $proposed= recurse($stripped, $variables);
1525   /* Get list of used ID's */
1526   $used= array();
1527   $ldap= $config->get_ldap_link();
1528   $ldap->cd($config->current['BASE']);
1529   $ldap->search('(uid=*)');
1531   while($attrs= $ldap->fetch()){
1532     $used[]= $attrs['uid'][0];
1533   }
1535   /* Remove used uids and watch out for id tags */
1536   $ret= array();
1537   foreach($proposed as $uid){
1539     /* Check for id tag and modify uid if needed */
1540     if(preg_match('/\{id:\d+}/',$uid)){
1541       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1543       for ($i= 0; $i < pow(10,$size); $i++){
1544         $number= sprintf("%0".$size."d", $i);
1545         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1546         if (!in_array($res, $used)){
1547           $uid= $res;
1548           break;
1549         }
1550       }
1551     }
1553   if(preg_match('/\{id#\d+}/',$uid)){
1554     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1556     while (true){
1557       mt_srand((double) microtime()*1000000);
1558       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1559       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1560       if (!in_array($res, $used)){
1561         $uid= $res;
1562         break;
1563       }
1564     }
1565   }
1567 /* Don't assign used ones */
1568 if (!in_array($uid, $used)){
1569   $ret[]= $uid;
1573 return(array_unique($ret));
1577 function array_search_r($needle, $key, $haystack){
1579   foreach($haystack as $index => $value){
1580     $match= 0;
1582     if (is_array($value)){
1583       $match= array_search_r($needle, $key, $value);
1584     }
1586     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1587       $match=1;
1588     }
1590     if ($match){
1591       return 1;
1592     }
1593   }
1595   return 0;
1596
1599 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1600    Need to convert... */
1601 function to_byte($value) {
1602   $value= strtolower(trim($value));
1604   if(!is_numeric(substr($value, -1))) {
1606     switch(substr($value, -1)) {
1607       case 'g':
1608         $mult= 1073741824;
1609         break;
1610       case 'm':
1611         $mult= 1048576;
1612         break;
1613       case 'k':
1614         $mult= 1024;
1615         break;
1616     }
1618     return ($mult * (int)substr($value, 0, -1));
1619   } else {
1620     return $value;
1621   }
1625 function in_array_ics($value, $items)
1627   if (!is_array($items)){
1628     return (FALSE);
1629   }
1631   foreach ($items as $item){
1632     if (strtolower($item) == strtolower($value)) {
1633       return (TRUE);
1634     }
1635   }
1637   return (FALSE);
1638
1641 function generate_alphabet($count= 10)
1643   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1644   $alphabet= "";
1645   $c= 0;
1647   /* Fill cells with charaters */
1648   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1649     if ($c == 0){
1650       $alphabet.= "<tr>";
1651     }
1653     $ch = mb_substr($characters, $i, 1, "UTF8");
1654     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1655       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1657     if ($c++ == $count){
1658       $alphabet.= "</tr>";
1659       $c= 0;
1660     }
1661   }
1663   /* Fill remaining cells */
1664   while ($c++ <= $count){
1665     $alphabet.= "<td>&nbsp;</td>";
1666   }
1668   return ($alphabet);
1672 function validate($string)
1674   return (strip_tags(preg_replace('/\0/', '', $string)));
1677 function get_gosa_version()
1679   global $svn_revision, $svn_path;
1681   /* Extract informations */
1682   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1684   /* Release or development? */
1685   if (preg_match('%/gosa/trunk/%', $svn_path)){
1686     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1687   } else {
1688     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1689     return (sprintf(_("GOsa $release"), $revision));
1690   }
1694 function rmdirRecursive($path, $followLinks=false) {
1695   $dir= opendir($path);
1696   while($entry= readdir($dir)) {
1697     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1698       unlink($path."/".$entry);
1699     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1700       rmdirRecursive($path."/".$entry);
1701     }
1702   }
1703   closedir($dir);
1704   return rmdir($path);
1707 function scan_directory($path,$sort_desc=false)
1709   $ret = false;
1711   /* is this a dir ? */
1712   if(is_dir($path)) {
1714     /* is this path a readable one */
1715     if(is_readable($path)){
1717       /* Get contents and write it into an array */   
1718       $ret = array();    
1720       $dir = opendir($path);
1722       /* Is this a correct result ?*/
1723       if($dir){
1724         while($fp = readdir($dir))
1725           $ret[]= $fp;
1726       }
1727     }
1728   }
1729   /* Sort array ascending , like scandir */
1730   sort($ret);
1732   /* Sort descending if parameter is sort_desc is set */
1733   if($sort_desc) {
1734     $ret = array_reverse($ret);
1735   }
1737   return($ret);
1740 function clean_smarty_compile_dir($directory)
1742   global $svn_revision;
1744   if(is_dir($directory) && is_readable($directory)) {
1745     // Set revision filename to REVISION
1746     $revision_file= $directory."/REVISION";
1748     /* Is there a stamp containing the current revision? */
1749     if(!file_exists($revision_file)) {
1750       // create revision file
1751       create_revision($revision_file, $svn_revision);
1752     } else {
1753 # check for "$config->...['CONFIG']/revision" and the
1754 # contents should match the revision number
1755       if(!compare_revision($revision_file, $svn_revision)){
1756         // If revision differs, clean compile directory
1757         foreach(scan_directory($directory) as $file) {
1758           if(($file==".")||($file=="..")) continue;
1759           if( is_file($directory."/".$file) &&
1760               is_writable($directory."/".$file)) {
1761             // delete file
1762             if(!unlink($directory."/".$file)) {
1763               print_red("File ".$directory."/".$file." could not be deleted.");
1764               // This should never be reached
1765             }
1766           } elseif(is_dir($directory."/".$file) &&
1767               is_writable($directory."/".$file)) {
1768             // Just recursively delete it
1769             rmdirRecursive($directory."/".$file);
1770           }
1771         }
1772         // We should now create a fresh revision file
1773         clean_smarty_compile_dir($directory);
1774       } else {
1775         // Revision matches, nothing to do
1776       }
1777     }
1778   } else {
1779     // Smarty compile dir is not accessible
1780     // (Smarty will warn about this)
1781   }
1784 function create_revision($revision_file, $revision)
1786   $result= false;
1788   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1789     if($fh= fopen($revision_file, "w")) {
1790       if(fwrite($fh, $revision)) {
1791         $result= true;
1792       }
1793     }
1794     fclose($fh);
1795   } else {
1796     print_red("Can not write to revision file");
1797   }
1799   return $result;
1802 function compare_revision($revision_file, $revision)
1804   // false means revision differs
1805   $result= false;
1807   if(file_exists($revision_file) && is_readable($revision_file)) {
1808     // Open file
1809     if($fh= fopen($revision_file, "r")) {
1810       // Compare File contents with current revision
1811       if($revision == fread($fh, filesize($revision_file))) {
1812         $result= true;
1813       }
1814     } else {
1815       print_red("Can not open revision file");
1816     }
1817     // Close file
1818     fclose($fh);
1819   }
1821   return $result;
1824 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1826   $str = ""; // Our return value will be saved in this var
1828   $color  = dechex($percentage+150);
1829   $color2 = dechex(150 - $percentage);
1830   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1832   $progress = (int)(($percentage /100)*$width);
1834   /* Abort printing out percentage, if divs are to small */
1837   /* If theres a better solution for this, use it... */
1838   $str = "
1839     <div style=\" width:".($width)."px; 
1840     height:".($height)."px;
1841   background-color:#000000;
1842 padding:1px;\">
1844           <div style=\" width:".($width)."px;
1845         background-color:#$bgcolor;
1846 height:".($height)."px;\">
1848          <div style=\" width:".$progress."px;
1849 height:".$height."px;
1850        background-color:#".$color2.$color2.$color."; \">";
1853        if(($height >10)&&($showvalue)){
1854          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1855            <b>".$percentage."%</b>
1856            </font>";
1857        }
1859        $str.= "</div></div></div>";
1861        return($str);
1865 function array_key_ics($ikey, $items)
1867   /* Gather keys, make them lowercase */
1868   $tmp= array();
1869   foreach ($items as $key => $value){
1870     $tmp[strtolower($key)]= $key;
1871   }
1873   if (isset($tmp[strtolower($ikey)])){
1874     return($tmp[strtolower($ikey)]);
1875   }
1877   return ("");
1881 function search_config($arr, $name, $return)
1883   if (is_array($arr)){
1884     foreach ($arr as $a){
1885       if (isset($a['CLASS']) &&
1886           strtolower($a['CLASS']) == strtolower($name)){
1888         if (isset($a[$return])){
1889           return ($a[$return]);
1890         } else {
1891           return ("");
1892         }
1893       } else {
1894         $res= search_config ($a, $name, $return);
1895         if ($res != ""){
1896           return $res;
1897         }
1898       }
1899     }
1900   }
1901   return ("");
1905 function array_differs($src, $dst)
1907   /* If the count is differing, the arrays differ */
1908   if (count ($src) != count ($dst)){
1909     return (TRUE);
1910   }
1912   /* So the count is the same - lets check the contents */
1913   $differs= FALSE;
1914   foreach($src as $value){
1915     if (!in_array($value, $dst)){
1916       $differs= TRUE;
1917     }
1918   }
1920   return ($differs);
1924 function saveFilter($a_filter, $values)
1926   if (isset($_POST['regexit'])){
1927     $a_filter["regex"]= $_POST['regexit'];
1929     foreach($values as $type){
1930       if (isset($_POST[$type])) {
1931         $a_filter[$type]= "checked";
1932       } else {
1933         $a_filter[$type]= "";
1934       }
1935     }
1936   }
1938   /* React on alphabet links if needed */
1939   if (isset($_GET['search'])){
1940     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
1941     if ($s == "**"){
1942       $s= "*";
1943     }
1944     $a_filter['regex']= $s;
1945   }
1947   return ($a_filter);
1951 /* Escape all preg_* relevant characters */
1952 function normalizePreg($input)
1954   return (addcslashes($input, '[]()|/.*+-'));
1958 /* Escape all LDAP filter relevant characters */
1959 function normalizeLdap($input)
1961   return (addcslashes($input, '()|'));
1965 /* Resturns the difference between to microtime() results in float  */
1966 function get_MicroTimeDiff($start , $stop)
1968   $a = split("\ ",$start);
1969   $b = split("\ ",$stop);
1971   $secs = $b[1] - $a[1];
1972   $msecs= $b[0] - $a[0]; 
1974   $ret = (float) ($secs+ $msecs);
1975   return($ret);
1979 /* Check if the given department name is valid */
1980 function is_department_name_reserved($name,$base)
1982   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
1983                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
1984                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
1986   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disks","packages","variables","profiles");
1988   /* Check if name is one of the reserved names */
1989   if(in_array_ics($name,$reservedName)) {
1990     return(true);
1991   }
1993   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
1994   foreach($follwedNames as $key => $names){
1995     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
1996       return(true);
1997     }
1998   }
1999   return(false);
2003 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2004 ?>