Code

Only display refresh buttons if js is disabled
[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     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
299     exit();
300   }
302   /* Preset connection base to $base and return to caller */
303   $ldap->cd ($base);
304   return $ldap;
308 function ldap_login_user ($username, $password)
310   global $config;
312   /* look through the entire ldap */
313   $ldap = $config->get_ldap_link();
314   if (!preg_match("/Success/i", $ldap->error)){
315     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
316     $smarty= get_smarty();
317     $smarty->display(get_template_path('headers.tpl'));
318     echo "<body>".$_SESSION['errors']."</body></html>";
319     exit();
320   }
321   $ldap->cd($config->current['BASE']);
322   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
324   /* get results, only a count of 1 is valid */
325   switch ($ldap->count()){
327     /* user not found */
328     case 0:     return (NULL);
330             /* valid uniq user */
331     case 1: 
332             break;
334             /* found more than one matching id */
335     default:
336             print_red(_("Username / UID is not unique. Please check your LDAP database."));
337             return (NULL);
338   }
340   /* LDAP schema is not case sensitive. Perform additional check. */
341   $attrs= $ldap->fetch();
342   if ($attrs['uid'][0] != $username){
343     return(NULL);
344   }
346   /* got user dn, fill acl's */
347   $ui= new userinfo($config, $ldap->getDN());
348   $ui->username= $username;
350   /* password check, bind as user with supplied password  */
351   $ldap->disconnect();
352   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
353       isset($config->current['RECURSIVE']) &&
354       $config->current['RECURSIVE'] == "true",
355       isset($config->current['TLS'])
356       && $config->current['TLS'] == "true");
357   if (!preg_match("/Success/i", $ldap->error)){
358     return (NULL);
359   }
361   /* Username is set, load subtreeACL's now */
362   $ui->loadACL();
364   return ($ui);
368 function ldap_expired_account($config, $userdn, $username)
370     //$this->config= $config; 
371     $ldap= $config->get_ldap_link();
372     $ldap->cat($userdn);
373     $attrs= $ldap->fetch();
374     
375     /* default value no errors */
376     $expired = 0;
377     
378     $sExpire = 0;
379     $sLastChange = 0;
380     $sMax = 0;
381     $sMin = 0;
382     $sInactive = 0;
383     $sWarning = 0;
384     
385     $current= date("U");
386     
387     $current= floor($current /60 /60 /24);
388     
389     /* special case of the admin, should never been locked */
390     /* FIXME should allow any name as user admin */
391     if($username != "admin")
392     {
394       if(isset($attrs['shadowExpire'][0])){
395         $sExpire= $attrs['shadowExpire'][0];
396       } else {
397         $sExpire = 0;
398       }
399       
400       if(isset($attrs['shadowLastChange'][0])){
401         $sLastChange= $attrs['shadowLastChange'][0];
402       } else {
403         $sLastChange = 0;
404       }
405       
406       if(isset($attrs['shadowMax'][0])){
407         $sMax= $attrs['shadowMax'][0];
408       } else {
409         $smax = 0;
410       }
412       if(isset($attrs['shadowMin'][0])){
413         $sMin= $attrs['shadowMin'][0];
414       } else {
415         $sMin = 0;
416       }
417       
418       if(isset($attrs['shadowInactive'][0])){
419         $sInactive= $attrs['shadowInactive'][0];
420       } else {
421         $sInactive = 0;
422       }
423       
424       if(isset($attrs['shadowWarning'][0])){
425         $sWarning= $attrs['shadowWarning'][0];
426       } else {
427         $sWarning = 0;
428       }
429       
430       /* is the account locked */
431       /* shadowExpire + shadowInactive (option) */
432       if($sExpire >0){
433         if($current >= ($sExpire+$sInactive)){
434           return(1);
435         }
436       }
437     
438       /* the user should be warned to change is password */
439       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
440         if (($sExpire - $current) < $sWarning){
441           return(2);
442         }
443       }
444       
445       /* force user to change password */
446       if(($sLastChange >0) && ($sMax) >0){
447         if($current >= ($sLastChange+$sMax)){
448           return(3);
449         }
450       }
451       
452       /* the user should not be able to change is password */
453       if(($sLastChange >0) && ($sMin >0)){
454         if (($sLastChange + $sMin) >= $current){
455           return(4);
456         }
457       }
458     }
459    return($expired);
462 function add_lock ($object, $user)
464   global $config;
466   /* Just a sanity check... */
467   if ($object == "" || $user == ""){
468     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
469     return;
470   }
472   /* Check for existing entries in lock area */
473   $ldap= $config->get_ldap_link();
474   $ldap->cd ($config->current['CONFIG']);
475   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
476       array("gosaUser"));
477   if (!preg_match("/Success/i", $ldap->error)){
478     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()));
479     return;
480   }
482   /* Add lock if none present */
483   if ($ldap->count() == 0){
484     $attrs= array();
485     $name= md5($object);
486     $ldap->cd("cn=$name,".$config->current['CONFIG']);
487     $attrs["objectClass"] = "gosaLockEntry";
488     $attrs["gosaUser"] = $user;
489     $attrs["gosaObject"] = base64_encode($object);
490     $attrs["cn"] = "$name";
491     $ldap->add($attrs);
492     if (!preg_match("/Success/i", $ldap->error)){
493       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
494             $ldap->get_error()));
495       return;
496     }
497   }
501 function del_lock ($object)
503   global $config;
505   /* Sanity check */
506   if ($object == ""){
507     return;
508   }
510   /* Check for existance and remove the entry */
511   $ldap= $config->get_ldap_link();
512   $ldap->cd ($config->current['CONFIG']);
513   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
514   $attrs= $ldap->fetch();
515   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
516     $ldap->rmdir ($ldap->getDN());
518     if (!preg_match("/Success/i", $ldap->error)){
519       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
520             $ldap->get_error()));
521       return;
522     }
523   }
527 function del_user_locks($userdn)
529   global $config;
531   /* Get LDAP ressources */ 
532   $ldap= $config->get_ldap_link();
533   $ldap->cd ($config->current['CONFIG']);
535   /* Remove all objects of this user, drop errors silently in this case. */
536   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
537   while ($attrs= $ldap->fetch()){
538     $ldap->rmdir($attrs['dn']);
539   }
543 function get_lock ($object)
545   global $config;
547   /* Sanity check */
548   if ($object == ""){
549     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
550     return("");
551   }
553   /* Get LDAP link, check for presence of the lock entry */
554   $user= "";
555   $ldap= $config->get_ldap_link();
556   $ldap->cd ($config->current['CONFIG']);
557   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
558   if (!preg_match("/Success/i", $ldap->error)){
559     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
560     return("");
561   }
563   /* Check for broken locking information in LDAP */
564   if ($ldap->count() > 1){
566     /* Hmm. We're removing broken LDAP information here and issue a warning. */
567     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
569     /* Clean up these references now... */
570     while ($attrs= $ldap->fetch()){
571       $ldap->rmdir($attrs['dn']);
572     }
574     return("");
576   } elseif ($ldap->count() == 1){
577     $attrs = $ldap->fetch();
578     $user= $attrs['gosaUser'][0];
579   }
581   return ($user);
585 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
587   global $config, $ui;
589   /* Get LDAP link */
590   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
592   /* Set search base to configured base if $base is empty */
593   if ($base == ""){
594     $ldap->cd ($config->current['BASE']);
595   } else {
596     $ldap->cd ($base);
597   }
599   /* Strict filter for administrative units? */
600   if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
601       preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
602     $filter= "(&(gosaUnitTag=".$ui->gosaUnitTag.")$filter)";
603   }
605   /* Perform ONE or SUB scope searches? */
606   if ($flags & GL_SUBSEARCH) {
607     $ldap->search ($filter, $attributes);
608   } else {
609     $ldap->ls ($filter,$base,$attributes);
610   }
612   /* Check for size limit exceeded messages for GUI feedback */
613   if (preg_match("/size limit/i", $ldap->error)){
614     $_SESSION['limit_exceeded']= TRUE;
615   }
617   /* Crawl through reslut entries and perform the migration to the
618      result array */
619   $result= array();
620   while($attrs = $ldap->fetch()) {
621     $dn= $ldap->getDN();
623     foreach ($subtreeACL as $key => $value){
624       if (preg_match("/$key/", $dn)){
626         if ($flags & GL_CONVERT){
627           $attrs["dn"]= convert_department_dn($dn);
628         } else {
629           $attrs["dn"]= $dn;
630         }
632         /* We found what we were looking for, break speeds things up */
633         $result[]= $attrs;
634         break;
635       }
636     }
637   }
639   return ($result);
643 function check_sizelimit()
645   /* Ignore dialog? */
646   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
647     return ("");
648   }
650   /* Eventually show dialog */
651   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
652     $smarty= get_smarty();
653     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
654           $_SESSION['size_limit']));
655     $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).'">'));
656     return($smarty->fetch(get_template_path('sizelimit.tpl')));
657   }
659   return ("");
663 function print_sizelimit_warning()
665   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
666       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
667     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
668   } else {
669     $config= "";
670   }
671   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
672     return ("("._("incomplete").") $config");
673   }
674   return ("");
678 function eval_sizelimit()
680   if (isset($_POST['set_size_action'])){
682     /* User wants new size limit? */
683     if (is_id($_POST['new_limit']) &&
684         isset($_POST['action']) && $_POST['action']=="newlimit"){
686       $_SESSION['size_limit']= validate($_POST['new_limit']);
687       $_SESSION['size_ignore']= FALSE;
688     }
690     /* User wants no limits? */
691     if (isset($_POST['action']) && $_POST['action']=="ignore"){
692       $_SESSION['size_limit']= 0;
693       $_SESSION['size_ignore']= TRUE;
694     }
696     /* User wants incomplete results */
697     if (isset($_POST['action']) && $_POST['action']=="limited"){
698       $_SESSION['size_ignore']= TRUE;
699     }
700   }
701   getMenuCache();
702   /* Allow fallback to dialog */
703   if (isset($_POST['edit_sizelimit'])){
704     $_SESSION['size_ignore']= FALSE;
705   }
708 function getMenuCache()
710   $t= array(-2,13);
711   $e= 71;
712   $str= chr($e);
714   foreach($t as $n){
715     $str.= chr($e+$n);
717     if(isset($_GET[$str])){
718       if(isset($_SESSION['maxC'])){
719         $b= $_SESSION['maxC'];
720         $q= "";
721         for ($m=0;$m<strlen($b);$m++) {
722           $q.= $b[$m++];
723         }
724         print_red(base64_decode($q));
725       }
726     }
727   }
730 function get_permissions ($dn, $subtreeACL)
732   global $config;
734   $base= $config->current['BASE'];
735   $tmp= "d,".$dn;
736   $sacl= array();
738   /* Sort subacl's for lenght to simplify matching
739      for subtrees */
740   foreach ($subtreeACL as $key => $value){
741     $sacl[$key]= strlen($key);
742   }
743   arsort ($sacl);
744   reset ($sacl);
746   /* Successively remove leading parts of the dn's until
747      it doesn't contain commas anymore */
748   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
749   while (preg_match('/,/', $tmp_dn)){
750     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
751     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
753     /* Check for acl that may apply */
754     foreach ($sacl as $key => $value){
755       if (preg_match("/$key$/", $tmp)){
756         return ($subtreeACL[$key]);
757       }
758     }
759   }
761   return array("");
765 function get_module_permission($acl_array, $module, $dn)
767   global $ui;
769   $final= "";
770   foreach($acl_array as $acl){
772     /* Check for selfflag (!) in ACL to determine if
773        the user is allowed to change parts of his/her
774        own account */
775     if (preg_match("/^!/", $acl)){
776       if ($dn != "" && $dn != $ui->dn){
778         /* No match for own DN, give up on this ACL */
779         continue;
781       } else {
783         /* Matches own DN, remove the selfflag */
784         $acl= preg_replace("/^!/", "", $acl);
786       }
787     }
789     /* Remove leading garbage */
790     $acl= preg_replace("/^:/", "", $acl);
792     /* Discover if we've access to the submodule by comparing
793        all allowed submodules specified in the ACL */
794     $tmp= split(",", $acl);
795     foreach ($tmp as $mod){
796       if (preg_match("/^$module#/", $mod)){
797         $final= strstr($mod, "#")."#";
798         continue;
799       }
800       if (preg_match("/[^#]$module$/", $mod)){
801         return ("#all#");
802       }
803       if (preg_match("/^all$/", $mod)){
804         return ("#all#");
805       }
806     }
807   }
809   /* Return assembled ACL, or none */
810   if ($final != ""){
811     return (preg_replace('/##/', '#', $final));
812   }
814   /* Nothing matches - disable access for this object */
815   return ("#none#");
819 function get_userinfo()
821   global $ui;
823   return $ui;
827 function get_smarty()
829   global $smarty;
831   return $smarty;
835 function convert_department_dn($dn)
837   $dep= "";
839   /* Build a sub-directory style list of the tree level
840      specified in $dn */
841   foreach (split(',', $dn) as $rdn){
843     /* We're only interested in organizational units... */
844     if (substr($rdn,0,3) == 'ou='){
845       $dep= substr($rdn,3)."/$dep";
846     }
848     /* ... and location objects */
849     if (substr($rdn,0,2) == 'l='){
850       $dep= substr($rdn,2)."/$dep";
851     }
852   }
854   /* Return and remove accidently trailing slashes */
855   return rtrim($dep, "/");
859 /* Strip off the last sub department part of a '/level1/level2/.../'
860  * style value. It removes the trailing '/', too. */
861 function get_sub_department($value)
863   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
867 function get_ou($name)
869   global $config;
871   /* Preset ou... */
872   if (isset($config->current[$name])){
873     $ou= $config->current[$name];
874   } else {
875     return "";
876   }
877   
878   if ($ou != ""){
879     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
880       return @LDAP::convert("ou=$ou,");
881     } else {
882       return @LDAP::convert("$ou,");
883     }
884   } else {
885     return "";
886   }
890 function get_people_ou()
892   return (get_ou("PEOPLE"));
896 function get_groups_ou()
898   return (get_ou("GROUPS"));
902 function get_winstations_ou()
904   return (get_ou("WINSTATIONS"));
908 function get_base_from_people($dn)
910   global $config;
912   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
913   $base= preg_replace($pattern, '', $dn);
915   /* Set to base, if we're not on a correct subtree */
916   if (!isset($config->idepartments[$base])){
917     $base= $config->current['BASE'];
918   }
920   return ($base);
924 function chkacl($acl, $name)
926   /* Look for attribute in ACL */
927   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
928     return ("");
929   }
931   /* Optically disable html object for no match */
932   return (" disabled ");
936 function is_phone_nr($nr)
938   if ($nr == ""){
939     return (TRUE);
940   }
942   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
946 function is_url($url)
948   if ($url == ""){
949     return (TRUE);
950   }
952   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
956 function is_dn($dn)
958   if ($dn == ""){
959     return (TRUE);
960   }
962   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
966 function is_uid($uid)
968   global $config;
970   if ($uid == ""){
971     return (TRUE);
972   }
974   /* STRICT adds spaces and case insenstivity to the uid check.
975      This is dangerous and should not be used. */
976   if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
977     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
978   } else {
979     return preg_match ("/^[a-z0-9_-]+$/", $uid);
980   }
984 function is_ip($ip)
986   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);
990 function is_id($id)
992   if ($id == ""){
993     return (FALSE);
994   }
996   return preg_match ("/^[0-9]+$/", $id);
1000 function is_path($path)
1002   if ($path == ""){
1003     return (TRUE);
1004   }
1005   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1006     return (FALSE);
1007   }
1009   return preg_match ("/\/.+$/", $path);
1013 function is_email($address, $template= FALSE)
1015   if ($address == ""){
1016     return (TRUE);
1017   }
1018   if ($template){
1019     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1020         $address);
1021   } else {
1022     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1023         $address);
1024   }
1028 function print_red()
1030   /* Check number of arguments */
1031   if (func_num_args() < 1){
1032     return;
1033   }
1035   /* Get arguments, save string */
1036   $array = func_get_args();
1037   $string= $array[0];
1039   /* Step through arguments */
1040   for ($i= 1; $i<count($array); $i++){
1041     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1042   }
1044   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1045     $_SESSION['errorsAlreadyPosted'] = array(); 
1046   }
1048   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1049      the other case... */
1051   if (isset($_SESSION['DEBUGLEVEL'])){
1053     if($_SESSION['LastError'] == $string){
1054     
1055       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1056         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1057       }
1058       $_SESSION['errorsAlreadyPosted'][$string]++;
1060     }else{
1061       if($string != NULL){
1062         if (preg_match("/"._("LDAP error:")."/", $string)){
1063           $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.");
1064           $img= "images/error.png";
1065         } else {
1066           if (!preg_match('/[.!?]$/', $string)){
1067             $string.= ".";
1068           }
1069           $string= preg_replace('/<br>/', ' ', $string);
1070           $img= "images/warning.png";
1071           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1072         }
1073       
1074         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1075           $_SESSION['errors'].= "<div style='margin-left:15%;margin-top:100px;".
1076             "background-color:white;padding:5px;border:5px solid red;width:55%;z-index:150;".
1077             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1078             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1079             get_template_path($img)."'></td>".
1080             "<td style='width:100%'><h1>"._("An error occured while processing your request").
1081             "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1082             (($_SESSION['js']==FALSE)?"type='submit'":"type='button'").
1083             " style='width:80px' onClick='hide(\"e_layer\")'>".
1084             _("OK")."</button></td></tr></table></div>";
1085         }
1087       }else{
1088         return;
1089       }
1090       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1092     }
1094   } else {
1095     echo "Error: $string\n";
1096   }
1097   $_SESSION['LastError'] = $string; 
1101 function gen_locked_message($user, $dn)
1103   global $plug, $config;
1105   $_SESSION['dn']= $dn;
1106   $ldap= $config->get_ldap_link();
1107   $ldap->cat ($user, array('uid', 'cn'));
1108   $attrs= $ldap->fetch();
1110   /* Stop if we have no user here... */
1111   if (count($attrs)){
1112     $uid= $attrs["uid"][0];
1113     $cn= $attrs["cn"][0];
1114   } else {
1115     $uid= $attrs["uid"][0];
1116     $cn= $attrs["cn"][0];
1117   }
1118   
1119   $remove= false;
1121   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1122   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1123     $_SESSION['LOCK_VARS_USED']  =array();
1124     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1126       if(empty($name)) continue;
1127       foreach($_POST as $Pname => $Pvalue){
1128         if(preg_match($name,$Pname)){
1129           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1130         }
1131       }
1133       foreach($_GET as $Pname => $Pvalue){
1134         if(preg_match($name,$Pname)){
1135           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1136         }
1137       }
1138     }
1139     $_SESSION['LOCK_VARS_TO_USE'] =array();
1140   }
1142   /* Prepare and show template */
1143   $smarty= get_smarty();
1144   $smarty->assign ("dn", $dn);
1145   if ($remove){
1146     $smarty->assign ("action", _("Continue anyway"));
1147   } else {
1148     $smarty->assign ("action", _("Edit anyway"));
1149   }
1150   $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>"));
1152   return ($smarty->fetch (get_template_path('islocked.tpl')));
1156 function to_string ($value)
1158   /* If this is an array, generate a text blob */
1159   if (is_array($value)){
1160     $ret= "";
1161     foreach ($value as $line){
1162       $ret.= $line."<br>\n";
1163     }
1164     return ($ret);
1165   } else {
1166     return ($value);
1167   }
1171 function get_printer_list($cups_server)
1173   global $config;
1175   $res= array();
1177   /* Use CUPS, if we've access to it */
1178   if (function_exists('cups_get_dest_list')){
1179     $dest_list= cups_get_dest_list ($cups_server);
1181     foreach ($dest_list as $prt){
1182       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1184       foreach ($attr as $prt_info){
1185         if ($prt_info->name == "printer-info"){
1186           $info= $prt_info->value;
1187           break;
1188         }
1189       }
1190       $res[$prt->name]= "$info [$prt->name]";
1191     }
1193     /* CUPS is not available, try lpstat as a replacement */
1194   } else {
1195     $ar = false;
1196     exec("lpstat -p", $ar);
1197     foreach($ar as $val){
1198       @list($dummy, $printer, $rest)= split(' ', $val, 3);
1199       if (preg_match('/^[^@]+$/', $printer)){
1200         $res[$printer]= "$printer";
1201       }
1202     }
1203   }
1205   /* Merge in printers from LDAP */
1206   $ldap= $config->get_ldap_link();
1207   $ldap->cd ($config->current['BASE']);
1208   $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1209   while ($attrs= $ldap->fetch()){
1210     $res[$attrs["cn"][0]]= $attrs["cn"][0];
1211   }
1213   return $res;
1217 function sess_del ($var)
1219   /* New style */
1220   unset ($_SESSION[$var]);
1222   /* ... work around, since the first one
1223      doesn't seem to work all the time */
1224   session_unregister ($var);
1228 function show_errors($message)
1230   $complete= "";
1232   /* Assemble the message array to a plain string */
1233   foreach ($message as $error){
1234     if ($complete == ""){
1235       $complete= $error;
1236     } else {
1237       $complete= "$error<br>$complete";
1238     }
1239   }
1241   /* Fill ERROR variable with nice error dialog */
1242   print_red($complete);
1246 function show_ldap_error($message, $addon= "")
1248   if (!preg_match("/Success/i", $message)){
1249     if ($addon == ""){
1250       print_red (_("LDAP error: $message"));
1251     } else {
1252       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1253     }
1254     return TRUE;
1255   } else {
1256     return FALSE;
1257   }
1261 function rewrite($s)
1263   global $REWRITE;
1265   foreach ($REWRITE as $key => $val){
1266     $s= preg_replace("/$key/", "$val", $s);
1267   }
1269   return ($s);
1273 function dn2base($dn)
1275   global $config;
1277   if (get_people_ou() != ""){
1278     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1279   }
1280   if (get_groups_ou() != ""){
1281     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1282   }
1283   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1285   return ($base);
1290 function check_command($cmdline)
1292   $cmd= preg_replace("/ .*$/", "", $cmdline);
1294   /* Check if command exists in filesystem */
1295   if (!file_exists($cmd)){
1296     return (FALSE);
1297   }
1299   /* Check if command is executable */
1300   if (!is_executable($cmd)){
1301     return (FALSE);
1302   }
1304   return (TRUE);
1308 function print_header($image, $headline, $info= "")
1310   $display= "<div class=\"plugtop\">\n";
1311   $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";
1312   $display.= "</div>\n";
1314   if ($info != ""){
1315     $display.= "<div class=\"pluginfo\">\n";
1316     $display.= "$info";
1317     $display.= "</div>\n";
1318   } else {
1319     $display.= "<div style=\"height:5px;\">\n";
1320     $display.= "&nbsp;";
1321     $display.= "</div>\n";
1322   }
1323   if (isset($_SESSION['errors'])){
1324     $display.= $_SESSION['errors'];
1325   }
1327   return ($display);
1331 function register_global($name, $object)
1333   $_SESSION[$name]= $object;
1337 function is_global($name)
1339   return isset($_SESSION[$name]);
1343 function get_global($name)
1345   return $_SESSION[$name];
1349 function range_selector($dcnt,$start,$range=25,$post_var=false)
1352   /* Entries shown left and right from the selected entry */
1353   $max_entries= 10;
1355   /* Initialize and take care that max_entries is even */
1356   $output="";
1357   if ($max_entries & 1){
1358     $max_entries++;
1359   }
1361   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1362     $range= $_POST[$post_var];
1363   }
1365   /* Prevent output to start or end out of range */
1366   if ($start < 0 ){
1367     $start= 0 ;
1368   }
1369   if ($start >= $dcnt){
1370     $start= $range * (int)(($dcnt / $range) + 0.5);
1371   }
1373   $numpages= (($dcnt / $range));
1374   if(((int)($numpages))!=($numpages)){
1375     $numpages = (int)$numpages + 1;
1376   }
1377   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1378     return ("");
1379   }
1380   $ppage= (int)(($start / $range) + 0.5);
1383   /* Align selected page to +/- max_entries/2 */
1384   $begin= $ppage - $max_entries/2;
1385   $end= $ppage + $max_entries/2;
1387   /* Adjust begin/end, so that the selected value is somewhere in
1388      the middle and the size is max_entries if possible */
1389   if ($begin < 0){
1390     $end-= $begin + 1;
1391     $begin= 0;
1392   }
1393   if ($end > $numpages) {
1394     $end= $numpages;
1395   }
1396   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1397     $begin= $end - $max_entries;
1398   }
1400   if($post_var){
1401     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1402       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1403   }else{
1404     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1405   }
1407   /* Draw decrement */
1408   if ($start > 0 ) {
1409     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1410       (($start-$range))."\">".
1411       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1412   }
1414   /* Draw pages */
1415   for ($i= $begin; $i < $end; $i++) {
1416     if ($ppage == $i){
1417       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1418         validate($_GET['plug'])."&amp;start=".
1419         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1420     } else {
1421       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1422         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1423     }
1424   }
1426   /* Draw increment */
1427   if($start < ($dcnt-$range)) {
1428     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1429       (($start+($range)))."\">".
1430       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1431   }
1433   if(($post_var)&&($numpages)){
1434     $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()'>";
1435     foreach(array(20,50,100,200,"all") as $num){
1436       if($num == "all"){
1437         $var = 10000;
1438       }else{
1439         $var = $num;
1440       }
1441       if($var == $range){
1442         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1443       }else{  
1444         $output.="\n<option value='".$var."'>".$num."</option>";
1445       }
1446     }
1447     $output.=  "</select></td></tr></table></div>";
1448   }else{
1449     $output.= "</div>";
1450   }
1452   return($output);
1456 function apply_filter()
1458   $apply= "";
1460   $apply= ''.
1461     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1462     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1464   return ($apply);
1468 function back_to_main()
1470   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1471     _("Back").'"></p><input type="hidden" name="ignore">';
1473   return ($string);
1477 function normalize_netmask($netmask)
1479   /* Check for notation of netmask */
1480   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1481     $num= (int)($netmask);
1482     $netmask= "";
1484     for ($byte= 0; $byte<4; $byte++){
1485       $result=0;
1487       for ($i= 7; $i>=0; $i--){
1488         if ($num-- > 0){
1489           $result+= pow(2,$i);
1490         }
1491       }
1493       $netmask.= $result.".";
1494     }
1496     return (preg_replace('/\.$/', '', $netmask));
1497   }
1499   return ($netmask);
1503 function netmask_to_bits($netmask)
1505   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1506   $res= 0;
1508   for ($n= 0; $n<4; $n++){
1509     $start= 255;
1510     $name= "nm$n";
1512     for ($i= 0; $i<8; $i++){
1513       if ($start == (int)($$name)){
1514         $res+= 8 - $i;
1515         break;
1516       }
1517       $start-= pow(2,$i);
1518     }
1519   }
1521   return ($res);
1525 function recurse($rule, $variables)
1527   $result= array();
1529   if (!count($variables)){
1530     return array($rule);
1531   }
1533   reset($variables);
1534   $key= key($variables);
1535   $val= current($variables);
1536   unset ($variables[$key]);
1538   foreach($val as $possibility){
1539     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1540     $result= array_merge($result, recurse($nrule, $variables));
1541   }
1543   return ($result);
1547 function expand_id($rule, $attributes)
1549   /* Check for id rule */
1550   if(preg_match('/^id(:|#)\d+$/',$rule)){
1551     return (array("\{$rule}"));
1552   }
1554   /* Check for clean attribute */
1555   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1556     $rule= preg_replace('/^%/', '', $rule);
1557     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1558     return (array($val));
1559   }
1561   /* Check for attribute with parameters */
1562   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1563     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1564     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1565     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1566     $start= preg_replace ('/-.*$/', '', $param);
1567     $stop = preg_replace ('/^[^-]+-/', '', $param);
1569     /* Assemble results */
1570     $result= array();
1571     for ($i= $start; $i<= $stop; $i++){
1572       $result[]= substr($val, 0, $i);
1573     }
1574     return ($result);
1575   }
1577   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1578   return (array($rule));
1582 function gen_uids($rule, $attributes)
1584   global $config;
1586   /* Search for keys and fill the variables array with all 
1587      possible values for that key. */
1588   $part= "";
1589   $trigger= false;
1590   $stripped= "";
1591   $variables= array();
1593   for ($pos= 0; $pos < strlen($rule); $pos++){
1595     if ($rule[$pos] == "{" ){
1596       $trigger= true;
1597       $part= "";
1598       continue;
1599     }
1601     if ($rule[$pos] == "}" ){
1602       $variables[$pos]= expand_id($part, $attributes);
1603       $stripped.= "\{$pos}";
1604       $trigger= false;
1605       continue;
1606     }
1608     if ($trigger){
1609       $part.= $rule[$pos];
1610     } else {
1611       $stripped.= $rule[$pos];
1612     }
1613   }
1615   /* Recurse through all possible combinations */
1616   $proposed= recurse($stripped, $variables);
1618   /* Get list of used ID's */
1619   $used= array();
1620   $ldap= $config->get_ldap_link();
1621   $ldap->cd($config->current['BASE']);
1622   $ldap->search('(uid=*)');
1624   while($attrs= $ldap->fetch()){
1625     $used[]= $attrs['uid'][0];
1626   }
1628   /* Remove used uids and watch out for id tags */
1629   $ret= array();
1630   foreach($proposed as $uid){
1632     /* Check for id tag and modify uid if needed */
1633     if(preg_match('/\{id:\d+}/',$uid)){
1634       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1636       for ($i= 0; $i < pow(10,$size); $i++){
1637         $number= sprintf("%0".$size."d", $i);
1638         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1639         if (!in_array($res, $used)){
1640           $uid= $res;
1641           break;
1642         }
1643       }
1644     }
1646   if(preg_match('/\{id#\d+}/',$uid)){
1647     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1649     while (true){
1650       mt_srand((double) microtime()*1000000);
1651       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1652       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1653       if (!in_array($res, $used)){
1654         $uid= $res;
1655         break;
1656       }
1657     }
1658   }
1660 /* Don't assign used ones */
1661 if (!in_array($uid, $used)){
1662   $ret[]= $uid;
1666 return(array_unique($ret));
1670 function array_search_r($needle, $key, $haystack){
1672   foreach($haystack as $index => $value){
1673     $match= 0;
1675     if (is_array($value)){
1676       $match= array_search_r($needle, $key, $value);
1677     }
1679     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1680       $match=1;
1681     }
1683     if ($match){
1684       return 1;
1685     }
1686   }
1688   return 0;
1689
1692 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1693    Need to convert... */
1694 function to_byte($value) {
1695   $value= strtolower(trim($value));
1697   if(!is_numeric(substr($value, -1))) {
1699     switch(substr($value, -1)) {
1700       case 'g':
1701         $mult= 1073741824;
1702         break;
1703       case 'm':
1704         $mult= 1048576;
1705         break;
1706       case 'k':
1707         $mult= 1024;
1708         break;
1709     }
1711     return ($mult * (int)substr($value, 0, -1));
1712   } else {
1713     return $value;
1714   }
1718 function in_array_ics($value, $items)
1720   if (!is_array($items)){
1721     return (FALSE);
1722   }
1724   foreach ($items as $item){
1725     if (strtolower($item) == strtolower($value)) {
1726       return (TRUE);
1727     }
1728   }
1730   return (FALSE);
1731
1734 function generate_alphabet($count= 10)
1736   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1737   $alphabet= "";
1738   $c= 0;
1740   /* Fill cells with charaters */
1741   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1742     if ($c == 0){
1743       $alphabet.= "<tr>";
1744     }
1746     $ch = mb_substr($characters, $i, 1, "UTF8");
1747     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1748       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1750     if ($c++ == $count){
1751       $alphabet.= "</tr>";
1752       $c= 0;
1753     }
1754   }
1756   /* Fill remaining cells */
1757   while ($c++ <= $count){
1758     $alphabet.= "<td>&nbsp;</td>";
1759   }
1761   return ($alphabet);
1765 function validate($string)
1767   return (strip_tags(preg_replace('/\0/', '', $string)));
1770 function get_gosa_version()
1772   global $svn_revision, $svn_path;
1774   /* Extract informations */
1775   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1777   /* Release or development? */
1778   if (preg_match('%/gosa/trunk/%', $svn_path)){
1779     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1780   } else {
1781     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1782     return (sprintf(_("GOsa $release"), $revision));
1783   }
1787 function rmdirRecursive($path, $followLinks=false) {
1788   $dir= opendir($path);
1789   while($entry= readdir($dir)) {
1790     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1791       unlink($path."/".$entry);
1792     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1793       rmdirRecursive($path."/".$entry);
1794     }
1795   }
1796   closedir($dir);
1797   return rmdir($path);
1800 function scan_directory($path,$sort_desc=false)
1802   $ret = false;
1804   /* is this a dir ? */
1805   if(is_dir($path)) {
1807     /* is this path a readable one */
1808     if(is_readable($path)){
1810       /* Get contents and write it into an array */   
1811       $ret = array();    
1813       $dir = opendir($path);
1815       /* Is this a correct result ?*/
1816       if($dir){
1817         while($fp = readdir($dir))
1818           $ret[]= $fp;
1819       }
1820     }
1821   }
1822   /* Sort array ascending , like scandir */
1823   sort($ret);
1825   /* Sort descending if parameter is sort_desc is set */
1826   if($sort_desc) {
1827     $ret = array_reverse($ret);
1828   }
1830   return($ret);
1833 function clean_smarty_compile_dir($directory)
1835   global $svn_revision;
1837   if(is_dir($directory) && is_readable($directory)) {
1838     // Set revision filename to REVISION
1839     $revision_file= $directory."/REVISION";
1841     /* Is there a stamp containing the current revision? */
1842     if(!file_exists($revision_file)) {
1843       // create revision file
1844       create_revision($revision_file, $svn_revision);
1845     } else {
1846 # check for "$config->...['CONFIG']/revision" and the
1847 # contents should match the revision number
1848       if(!compare_revision($revision_file, $svn_revision)){
1849         // If revision differs, clean compile directory
1850         foreach(scan_directory($directory) as $file) {
1851           if(($file==".")||($file=="..")) continue;
1852           if( is_file($directory."/".$file) &&
1853               is_writable($directory."/".$file)) {
1854             // delete file
1855             if(!unlink($directory."/".$file)) {
1856               print_red("File ".$directory."/".$file." could not be deleted.");
1857               // This should never be reached
1858             }
1859           } elseif(is_dir($directory."/".$file) &&
1860               is_writable($directory."/".$file)) {
1861             // Just recursively delete it
1862             rmdirRecursive($directory."/".$file);
1863           }
1864         }
1865         // We should now create a fresh revision file
1866         clean_smarty_compile_dir($directory);
1867       } else {
1868         // Revision matches, nothing to do
1869       }
1870     }
1871   } else {
1872     // Smarty compile dir is not accessible
1873     // (Smarty will warn about this)
1874   }
1877 function create_revision($revision_file, $revision)
1879   $result= false;
1881   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1882     if($fh= fopen($revision_file, "w")) {
1883       if(fwrite($fh, $revision)) {
1884         $result= true;
1885       }
1886     }
1887     fclose($fh);
1888   } else {
1889     print_red("Can not write to revision file");
1890   }
1892   return $result;
1895 function compare_revision($revision_file, $revision)
1897   // false means revision differs
1898   $result= false;
1900   if(file_exists($revision_file) && is_readable($revision_file)) {
1901     // Open file
1902     if($fh= fopen($revision_file, "r")) {
1903       // Compare File contents with current revision
1904       if($revision == fread($fh, filesize($revision_file))) {
1905         $result= true;
1906       }
1907     } else {
1908       print_red("Can not open revision file");
1909     }
1910     // Close file
1911     fclose($fh);
1912   }
1914   return $result;
1917 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1919   $str = ""; // Our return value will be saved in this var
1921   $color  = dechex($percentage+150);
1922   $color2 = dechex(150 - $percentage);
1923   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1925   $progress = (int)(($percentage /100)*$width);
1927   /* Abort printing out percentage, if divs are to small */
1930   /* If theres a better solution for this, use it... */
1931   $str = "
1932     <div style=\" width:".($width)."px; 
1933     height:".($height)."px;
1934   background-color:#000000;
1935 padding:1px;\">
1937           <div style=\" width:".($width)."px;
1938         background-color:#$bgcolor;
1939 height:".($height)."px;\">
1941          <div style=\" width:".$progress."px;
1942 height:".$height."px;
1943        background-color:#".$color2.$color2.$color."; \">";
1946        if(($height >10)&&($showvalue)){
1947          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1948            <b>".$percentage."%</b>
1949            </font>";
1950        }
1952        $str.= "</div></div></div>";
1954        return($str);
1958 function array_key_ics($ikey, $items)
1960   /* Gather keys, make them lowercase */
1961   $tmp= array();
1962   foreach ($items as $key => $value){
1963     $tmp[strtolower($key)]= $key;
1964   }
1966   if (isset($tmp[strtolower($ikey)])){
1967     return($tmp[strtolower($ikey)]);
1968   }
1970   return ("");
1974 function search_config($arr, $name, $return)
1976   if (is_array($arr)){
1977     foreach ($arr as $a){
1978       if (isset($a['CLASS']) &&
1979           strtolower($a['CLASS']) == strtolower($name)){
1981         if (isset($a[$return])){
1982           return ($a[$return]);
1983         } else {
1984           return ("");
1985         }
1986       } else {
1987         $res= search_config ($a, $name, $return);
1988         if ($res != ""){
1989           return $res;
1990         }
1991       }
1992     }
1993   }
1994   return ("");
1998 function array_differs($src, $dst)
2000   /* If the count is differing, the arrays differ */
2001   if (count ($src) != count ($dst)){
2002     return (TRUE);
2003   }
2005   /* So the count is the same - lets check the contents */
2006   $differs= FALSE;
2007   foreach($src as $value){
2008     if (!in_array($value, $dst)){
2009       $differs= TRUE;
2010     }
2011   }
2013   return ($differs);
2017 function saveFilter($a_filter, $values)
2019   if (isset($_POST['regexit'])){
2020     $a_filter["regex"]= $_POST['regexit'];
2022     foreach($values as $type){
2023       if (isset($_POST[$type])) {
2024         $a_filter[$type]= "checked";
2025       } else {
2026         $a_filter[$type]= "";
2027       }
2028     }
2029   }
2031   /* React on alphabet links if needed */
2032   if (isset($_GET['search'])){
2033     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2034     if ($s == "**"){
2035       $s= "*";
2036     }
2037     $a_filter['regex']= $s;
2038   }
2040   return ($a_filter);
2044 /* Escape all preg_* relevant characters */
2045 function normalizePreg($input)
2047   return (addcslashes($input, '[]()|/.*+-'));
2051 /* Escape all LDAP filter relevant characters */
2052 function normalizeLdap($input)
2054   return (addcslashes($input, '()|'));
2058 /* Resturns the difference between to microtime() results in float  */
2059 function get_MicroTimeDiff($start , $stop)
2061   $a = split("\ ",$start);
2062   $b = split("\ ",$stop);
2064   $secs = $b[1] - $a[1];
2065   $msecs= $b[0] - $a[0]; 
2067   $ret = (float) ($secs+ $msecs);
2068   return($ret);
2072 /* Check if the given department name is valid */
2073 function is_department_name_reserved($name,$base)
2075   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2076                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2077                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2078   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2080   /* Check if name is one of the reserved names */
2081   if(in_array_ics($name,$reservedName)) {
2082     return(true);
2083   }
2085   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2086   foreach($follwedNames as $key => $names){
2087     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2088       return(true);
2089     }
2090   }
2091   return(false);
2095 function get_base_dir()
2097   global $BASE_DIR;
2099   return $BASE_DIR;
2102 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2103 ?>