Code

Fixed copy & paste
[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_plugin.inc");
40 require_once ("class_acl.inc");
41 require_once ("class_pluglist.inc");
42 require_once ("class_userinfo.inc");
43 require_once ("class_tabs.inc");
44 require_once ("class_mail-methods.inc");
45 require_once ("class_password-methods.inc");
46 require_once ("functions_debug.inc");
47 require_once ("functions_dns.inc");
48 require_once ("class_MultiSelectWindow.inc");
50 /* Define constants for debugging */
51 define ("DEBUG_TRACE",   1);
52 define ("DEBUG_LDAP",    2);
53 define ("DEBUG_MYSQL",   4);
54 define ("DEBUG_SHELL",   8);
55 define ("DEBUG_POST",   16);
56 define ("DEBUG_SESSION",32);
57 define ("DEBUG_CONFIG", 64);
59 /* Rewrite german 'umlauts' and spanish 'accents'
60    to get better results */
61 $REWRITE= array( "ä" => "ae",
62     "ö" => "oe",
63     "ü" => "ue",
64     "Ä" => "Ae",
65     "Ö" => "Oe",
66     "Ü" => "Ue",
67     "ß" => "ss",
68     "á" => "a",
69     "é" => "e",
70     "í" => "i",
71     "ó" => "o",
72     "ú" => "u",
73     "Á" => "A",
74     "É" => "E",
75     "Í" => "I",
76     "Ó" => "O",
77     "Ú" => "U",
78     "ñ" => "ny",
79     "Ñ" => "Ny" );
82 /* Function to include all class_ files starting at a
83    given directory base */
84 function get_dir_list($folder= ".")
85 {
86   $currdir=getcwd();
87   if ($folder){
88     chdir("$folder");
89   }
91   $dh = opendir(".");
92   while(false !== ($file = readdir($dh))){
94     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
95     // Skip all files and dirs in  "./.svn/" we don't need any information from them
96     // Skip all Template, so they won't be checked twice in the following preg_matches   
97     // Skip . / ..
99     // Result  : from 1023 ms to 490 ms   i think thats great...
100     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
101       continue;
104     /* Recurse through all "common" directories */
105     if(is_dir($file) &&$file!="CVS"){
106       get_dir_list($file);
107       continue;
108     }
110     /* Include existing class_ files */
111     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
112       require_once($file);
113     }
114   }
116   closedir($dh);
117   chdir($currdir);
121 /* Create seed with microseconds */
122 function make_seed() {
123   list($usec, $sec) = explode(' ', microtime());
124   return (float) $sec + ((float) $usec * 100000);
128 /* Debug level action */
129 function DEBUG($level, $line, $function, $file, $data, $info="")
131   if ($_SESSION['DEBUGLEVEL'] & $level){
132     $output= "DEBUG[$level] ";
133     if ($function != ""){
134       $output.= "($file:$function():$line) - $info: ";
135     } else {
136       $output.= "($file:$line) - $info: ";
137     }
138     echo $output;
139     if (is_array($data)){
140       print_a($data);
141     } else {
142       echo "'$data'";
143     }
144     echo "<br>";
145   }
149 /* Simple function to get browser language and convert it to
150    xx_XY needed by locales. Ignores sublanguages and weights. */
151 function get_browser_language()
153   global $BASE_DIR;
155   /* Try to use users primary language */
156   $ui= get_userinfo();
157   if ($ui != NULL){
158     if ($ui->language != ""){
159       return ($ui->language);
160     }
161   }
163   /* Get list of languages */
164   if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
165     $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
166     $languages= split (',', $lang);
167     $languages[]= "C";
168   } else {
169     $languages= array("C");
170   }
172   /* Walk through languages and get first supported */
173   foreach ($languages as $val){
175     /* Strip off weight */
176     $lang= preg_replace("/;q=.*$/i", "", $val);
178     /* Simplify sub language handling */
179     $lang= preg_replace("/-.*$/", "", $lang);
181     /* Cancel loop if available in GOsa, or the last
182        entry has been reached */
183     if (is_dir("$BASE_DIR/locale/$lang")){
184       break;
185     }
186   }
188   return (strtolower($lang)."_".strtoupper($lang));
192 /* Rewrite ui object to another dn */
193 function change_ui_dn($dn, $newdn)
195   $ui= $_SESSION['ui'];
196   if ($ui->dn == $dn){
197     $ui->dn= $newdn;
198     $_SESSION['ui']= $ui;
199   }
203 /* Return theme path for specified file */
204 function get_template_path($filename= '', $plugin= FALSE, $path= "")
206   global $config, $BASE_DIR;
208   if (!@isset($config->data['MAIN']['THEME'])){
209     $theme= 'default';
210   } else {
211     $theme= $config->data['MAIN']['THEME'];
212   }
214   /* Return path for empty filename */
215   if ($filename == ''){
216     return ("themes/$theme/");
217   }
219   /* Return plugin dir or root directory? */
220   if ($plugin){
221     if ($path == ""){
222       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
223     } else {
224       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
225     }
226     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
227       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
228     }
229     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
230       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
231     }
232     if ($path == ""){
233       return ($_SESSION['plugin_dir']."/$filename");
234     } else {
235       return ($path."/$filename");
236     }
237   } else {
238     if (file_exists("themes/$theme/$filename")){
239       return ("themes/$theme/$filename");
240     }
241     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
242       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
243     }
244     if (file_exists("themes/default/$filename")){
245       return ("themes/default/$filename");
246     }
247     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
248       return ("$BASE_DIR/ihtml/themes/default/$filename");
249     }
250     return ($filename);
251   }
255 function array_remove_entries($needles, $haystack)
257   $tmp= array();
259   /* Loop through entries to be removed */
260   foreach ($haystack as $entry){
261     if (!in_array($entry, $needles)){
262       $tmp[]= $entry;
263     }
264   }
266   return ($tmp);
270 function gosa_log ($message)
272   global $ui;
274   /* Preset to something reasonable */
275   $username= " unauthenticated";
277   /* Replace username if object is present */
278   if (isset($ui)){
279     if ($ui->username != ""){
280       $username= "[$ui->username]";
281     } else {
282       $username= "unknown";
283     }
284   }
286   syslog(LOG_INFO,"GOsa$username: $message");
290 function ldap_init ($server, $base, $binddn='', $pass='')
292   global $config;
294   $ldap = new LDAP ($binddn, $pass, $server, isset($config->current['RECURSIVE'])                                                && $config->current['RECURSIVE'] == "true",
295       isset($config->current['TLS']) && $config->current['TLS'] == "true");
297   /* Sadly we've no proper return values here. Use the error message instead. */
298   if (!preg_match("/Success/i", $ldap->error)){
299     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
300     exit();
301   }
303   /* Preset connection base to $base and return to caller */
304   $ldap->cd ($base);
305   return $ldap;
309 function ldap_login_user ($username, $password)
311   global $config;
313   /* look through the entire ldap */
314   $ldap = $config->get_ldap_link();
315   if (!preg_match("/Success/i", $ldap->error)){
316     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
317     $smarty= get_smarty();
318     $smarty->display(get_template_path('headers.tpl'));
319     echo "<body>".$_SESSION['errors']."</body></html>";
320     exit();
321   }
322   $ldap->cd($config->current['BASE']);
323   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
325   /* get results, only a count of 1 is valid */
326   switch ($ldap->count()){
328     /* user not found */
329     case 0:     return (NULL);
331             /* valid uniq user */
332     case 1: 
333             break;
335             /* found more than one matching id */
336     default:
337             print_red(_("Username / UID is not unique. Please check your LDAP database."));
338             return (NULL);
339   }
341   /* LDAP schema is not case sensitive. Perform additional check. */
342   $attrs= $ldap->fetch();
343   if ($attrs['uid'][0] != $username){
344     return(NULL);
345   }
347   /* got user dn, fill acl's */
348   $ui= new userinfo($config, $ldap->getDN());
349   $ui->username= $username;
351   /* password check, bind as user with supplied password  */
352   $ldap->disconnect();
353   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
354       isset($config->current['RECURSIVE']) &&
355       $config->current['RECURSIVE'] == "true",
356       isset($config->current['TLS'])
357       && $config->current['TLS'] == "true");
358   if (!preg_match("/Success/i", $ldap->error)){
359     return (NULL);
360   }
362   /* Username is set, load subtreeACL's now */
363   $ui->loadACL();
365   return ($ui);
369 function ldap_expired_account($config, $userdn, $username)
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, $category, $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   /* Perform ONE or SUB scope searches? */
600   if ($flags & GL_SUBSEARCH) {
601     $ldap->search ($filter, $attributes);
602   } else {
603     $ldap->ls ($filter,$base,$attributes);
604   }
606   /* Check for size limit exceeded messages for GUI feedback */
607   if (preg_match("/size limit/i", $ldap->error)){
608     $_SESSION['limit_exceeded']= TRUE;
609   }
611   /* Crawl through reslut entries and perform the migration to the
612      result array */
613   $result= array();
615   while($attrs = $ldap->fetch()) {
616     $dn= $ldap->getDN();
618     /* Sort in every value that fits the permissions */
619     if (is_array($category)){
620       foreach ($category as $o){
621         if ($ui->get_category_permissions($dn, $o) != ""){
622           if ($flags & GL_CONVERT){
623             $attrs["dn"]= convert_department_dn($dn);
624           } else {
625             $attrs["dn"]= $dn;
626           }
628           /* We found what we were looking for, break speeds things up */
629           $result[]= $attrs;
630         }
631       }
632     } else {
633       if ($ui->get_category_permissions($dn, $category) != ""){
634         if ($flags & GL_CONVERT){
635           $attrs["dn"]= convert_department_dn($dn);
636         } else {
637           $attrs["dn"]= $dn;
638         }
640         /* We found what we were looking for, break speeds things up */
641         $result[]= $attrs;
642       }
643     }
644   }
646   return ($result);
650 function check_sizelimit()
652   /* Ignore dialog? */
653   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
654     return ("");
655   }
657   /* Eventually show dialog */
658   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
659     $smarty= get_smarty();
660     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
661           $_SESSION['size_limit']));
662     $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).'">'));
663     return($smarty->fetch(get_template_path('sizelimit.tpl')));
664   }
666   return ("");
670 function print_sizelimit_warning()
672   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
673       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
674     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
675   } else {
676     $config= "";
677   }
678   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
679     return ("("._("incomplete").") $config");
680   }
681   return ("");
685 function eval_sizelimit()
687   if (isset($_POST['set_size_action'])){
689     /* User wants new size limit? */
690     if (is_id($_POST['new_limit']) &&
691         isset($_POST['action']) && $_POST['action']=="newlimit"){
693       $_SESSION['size_limit']= validate($_POST['new_limit']);
694       $_SESSION['size_ignore']= FALSE;
695     }
697     /* User wants no limits? */
698     if (isset($_POST['action']) && $_POST['action']=="ignore"){
699       $_SESSION['size_limit']= 0;
700       $_SESSION['size_ignore']= TRUE;
701     }
703     /* User wants incomplete results */
704     if (isset($_POST['action']) && $_POST['action']=="limited"){
705       $_SESSION['size_ignore']= TRUE;
706     }
707   }
708   getMenuCache();
709   /* Allow fallback to dialog */
710   if (isset($_POST['edit_sizelimit'])){
711     $_SESSION['size_ignore']= FALSE;
712   }
715 function getMenuCache()
717   $t= array(-2,13);
718   $e= 71;
719   $str= chr($e);
721   foreach($t as $n){
722     $str.= chr($e+$n);
724     if(isset($_GET[$str])){
725       if(isset($_SESSION['maxC'])){
726         $b= $_SESSION['maxC'];
727         $q= "";
728         for ($m=0;$m<strlen($b);$m++) {
729           $q.= $b[$m++];
730         }
731         print_red(base64_decode($q));
732       }
733     }
734   }
738 function get_permissions ()
740   /* Look for attribute in ACL */
741   trigger_error("Don't use get_permissions() its obsolete. Use userinfo::get_permissions() instead.");
742   return array("");
746 function get_module_permission()
748   trigger_error("Don't use get_module_permission() its obsolete.");
749   return ("#none#");
753 function get_userinfo()
755   global $ui;
757   return $ui;
761 function get_smarty()
763   global $smarty;
765   return $smarty;
769 function convert_department_dn($dn)
771   $dep= "";
773   /* Build a sub-directory style list of the tree level
774      specified in $dn */
775   foreach (split(',', $dn) as $rdn){
777     /* We're only interested in organizational units... */
778     if (substr($rdn,0,3) == 'ou='){
779       $dep= substr($rdn,3)."/$dep";
780     }
782     /* ... and location objects */
783     if (substr($rdn,0,2) == 'l='){
784       $dep= substr($rdn,2)."/$dep";
785     }
786   }
788   /* Return and remove accidently trailing slashes */
789   return rtrim($dep, "/");
793 /* Strip off the last sub department part of a '/level1/level2/.../'
794  * style value. It removes the trailing '/', too. */
795 function get_sub_department($value)
797   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
801 function get_ou($name)
803   global $config;
805   /* Preset ou... */
806   if (isset($config->current[$name])){
807     $ou= $config->current[$name];
808   } else {
809     return "";
810   }
811   
812   if ($ou != ""){
813     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
814       return @LDAP::convert("ou=$ou,");
815     } else {
816       return @LDAP::convert("$ou,");
817     }
818   } else {
819     return "";
820   }
824 function get_people_ou()
826   return (get_ou("PEOPLE"));
830 function get_groups_ou()
832   return (get_ou("GROUPS"));
836 function get_winstations_ou()
838   return (get_ou("WINSTATIONS"));
842 function get_base_from_people($dn)
844   global $config;
846   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
847   $base= preg_replace($pattern, '', $dn);
849   /* Set to base, if we're not on a correct subtree */
850   if (!isset($config->idepartments[$base])){
851     $base= $config->current['BASE'];
852   }
854   return ($base);
858 function chkacl()
860   /* Look for attribute in ACL */
861   trigger_error("Don't use chkacl() its obsolete. Use userinfo::getacl() instead.");
862   return("-deprecated-");
866 function is_phone_nr($nr)
868   if ($nr == ""){
869     return (TRUE);
870   }
872   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
876 function is_url($url)
878   if ($url == ""){
879     return (TRUE);
880   }
882   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
886 function is_dn($dn)
888   if ($dn == ""){
889     return (TRUE);
890   }
892   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
896 function is_uid($uid)
898   global $config;
900   if ($uid == ""){
901     return (TRUE);
902   }
904   /* STRICT adds spaces and case insenstivity to the uid check.
905      This is dangerous and should not be used. */
906   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
907     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
908   } else {
909     return preg_match ("/^[a-z0-9_-]+$/", $uid);
910   }
914 function is_ip($ip)
916   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);
920 function is_mac($mac)
922   return preg_match("/^[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]$/i", $mac);
926 /* Checks if the given ip address dosen't match 
927     "is_ip" because there is also a sub net mask given */
928 function is_ip_with_subnetmask($ip)
930         /* Generate list of valid submasks */
931         $res = array();
932         for($e = 0 ; $e <= 32; $e++){
933                 $res[$e] = $e;
934         }
935         $i[0] =255;
936         $i[1] =255;
937         $i[2] =255;
938         $i[3] =255;
939         for($a= 3 ; $a >= 0 ; $a --){
940                 $c = 1;
941                 while($i[$a] > 0 ){
942                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
943                         $res[$str] = $str;
944                         $i[$a] -=$c;
945                         $c = 2*$c;
946                 }
947         }
948         $res["0.0.0.0"] = "0.0.0.0";
949         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
950                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
951                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
952                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
953                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
954                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
955                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
956                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
958                 $mask = preg_replace("/^\//","",$mask);
959                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
960                         return(TRUE);
961                 }
962         }
963         return(FALSE);
966 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
967 function is_domain($str)
969   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
974 function is_id($id)
976   if ($id == ""){
977     return (FALSE);
978   }
980   return preg_match ("/^[0-9]+$/", $id);
984 function is_path($path)
986   if ($path == ""){
987     return (TRUE);
988   }
989   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
990     return (FALSE);
991   }
993   return preg_match ("/\/.+$/", $path);
997 function is_email($address, $template= FALSE)
999   if ($address == ""){
1000     return (TRUE);
1001   }
1002   if ($template){
1003     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1004         $address);
1005   } else {
1006     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1007         $address);
1008   }
1012 function print_red()
1014   /* Check number of arguments */
1015   if (func_num_args() < 1){
1016     return;
1017   }
1019   /* Get arguments, save string */
1020   $array = func_get_args();
1021   $string= $array[0];
1023   /* Step through arguments */
1024   for ($i= 1; $i<count($array); $i++){
1025     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1026   }
1028   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1029     $_SESSION['errorsAlreadyPosted'] = array(); 
1030   }
1032   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1033      the other case... */
1035   if (isset($_SESSION['DEBUGLEVEL'])){
1037     if($_SESSION['LastError'] == $string){
1038     
1039       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1040         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1041       }
1042       $_SESSION['errorsAlreadyPosted'][$string]++;
1044     }else{
1045       if($string != NULL){
1046         if (preg_match("/"._("LDAP error:")."/", $string)){
1047           $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.");
1048           $img= "images/error.png";
1049         } else {
1050           if (!preg_match('/[.!?]$/', $string)){
1051             $string.= ".";
1052           }
1053           $string= preg_replace('/<br>/', ' ', $string);
1054           $img= "images/warning.png";
1055           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1056         }
1057       
1058         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1059           $_SESSION['errors'].= "<div style='margin-left:15%;margin-top:100px;".
1060             "background-color:white;padding:5px;border:5px solid red;width:55%;z-index:150;".
1061             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1062             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1063             get_template_path($img)."'></td>".
1064             "<td style='width:100%'><h1>"._("An error occured while processing your request").
1065             "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1066             (($_SESSION['js']==FALSE)?"type='submit'":"type='button'").
1067             " style='width:80px' onClick='hide(\"e_layer\")'>".
1068             _("OK")."</button></td></tr></table></div>";
1069         }
1071       }else{
1072         return;
1073       }
1074       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1076     }
1078   } else {
1079     echo "Error: $string\n";
1080   }
1081   $_SESSION['LastError'] = $string; 
1085 function gen_locked_message($user, $dn)
1087   global $plug, $config;
1089   $_SESSION['dn']= $dn;
1090   $ldap= $config->get_ldap_link();
1091   $ldap->cat ($user, array('uid', 'cn'));
1092   $attrs= $ldap->fetch();
1094   /* Stop if we have no user here... */
1095   if (count($attrs)){
1096     $uid= $attrs["uid"][0];
1097     $cn= $attrs["cn"][0];
1098   } else {
1099     $uid= $attrs["uid"][0];
1100     $cn= $attrs["cn"][0];
1101   }
1102   
1103   $remove= false;
1105   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1106   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1107     $_SESSION['LOCK_VARS_USED']  =array();
1108     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1110       if(empty($name)) continue;
1111       foreach($_POST as $Pname => $Pvalue){
1112         if(preg_match($name,$Pname)){
1113           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1114         }
1115       }
1117       foreach($_GET as $Pname => $Pvalue){
1118         if(preg_match($name,$Pname)){
1119           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1120         }
1121       }
1122     }
1123     $_SESSION['LOCK_VARS_TO_USE'] =array();
1124   }
1126   /* Prepare and show template */
1127   $smarty= get_smarty();
1128   $smarty->assign ("dn", $dn);
1129   if ($remove){
1130     $smarty->assign ("action", _("Continue anyway"));
1131   } else {
1132     $smarty->assign ("action", _("Edit anyway"));
1133   }
1134   $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>"));
1136   return ($smarty->fetch (get_template_path('islocked.tpl')));
1140 function to_string ($value)
1142   /* If this is an array, generate a text blob */
1143   if (is_array($value)){
1144     $ret= "";
1145     foreach ($value as $line){
1146       $ret.= $line."<br>\n";
1147     }
1148     return ($ret);
1149   } else {
1150     return ($value);
1151   }
1155 function get_printer_list($cups_server)
1157   global $config;
1159   $res= array();
1161   /* Use CUPS, if we've access to it */
1162   if (function_exists('cups_get_dest_list')){
1163     $dest_list= cups_get_dest_list ($cups_server);
1165     foreach ($dest_list as $prt){
1166       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1168       foreach ($attr as $prt_info){
1169         if ($prt_info->name == "printer-info"){
1170           $info= $prt_info->value;
1171           break;
1172         }
1173       }
1174       $res[$prt->name]= "$info [$prt->name]";
1175     }
1177     /* CUPS is not available, try lpstat as a replacement */
1178   } else {
1179     $ar = false;
1180     exec("lpstat -p", $ar);
1181     foreach($ar as $val){
1182       @list($dummy, $printer, $rest)= split(' ', $val, 3);
1183       if (preg_match('/^[^@]+$/', $printer)){
1184         $res[$printer]= "$printer";
1185       }
1186     }
1187   }
1189   /* Merge in printers from LDAP */
1190   $ldap= $config->get_ldap_link();
1191   $ldap->cd ($config->current['BASE']);
1192   $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1194   return $res;
1198 function sess_del ($var)
1200   /* New style */
1201   unset ($_SESSION[$var]);
1203   /* ... work around, since the first one
1204      doesn't seem to work all the time */
1205   session_unregister ($var);
1209 function show_errors($message)
1211   $complete= "";
1213   /* Assemble the message array to a plain string */
1214   foreach ($message as $error){
1215     if ($complete == ""){
1216       $complete= $error;
1217     } else {
1218       $complete= "$error<br>$complete";
1219     }
1220   }
1222   /* Fill ERROR variable with nice error dialog */
1223   print_red($complete);
1227 function show_ldap_error($message, $addon= "")
1229   if (!preg_match("/Success/i", $message)){
1230     if ($addon == ""){
1231       print_red (_("LDAP error: $message"));
1232     } else {
1233       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1234     }
1235     return TRUE;
1236   } else {
1237     return FALSE;
1238   }
1242 function rewrite($s)
1244   global $REWRITE;
1246   foreach ($REWRITE as $key => $val){
1247     $s= preg_replace("/$key/", "$val", $s);
1248   }
1250   return ($s);
1254 function dn2base($dn)
1256   global $config;
1258   if (get_people_ou() != ""){
1259     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1260   }
1261   if (get_groups_ou() != ""){
1262     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1263   }
1264   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1266   return ($base);
1271 function check_command($cmdline)
1273   $cmd= preg_replace("/ .*$/", "", $cmdline);
1275   /* Check if command exists in filesystem */
1276   if (!file_exists($cmd)){
1277     return (FALSE);
1278   }
1280   /* Check if command is executable */
1281   if (!is_executable($cmd)){
1282     return (FALSE);
1283   }
1285   return (TRUE);
1289 function print_header($image, $headline, $info= "")
1291   $display= "<div class=\"plugtop\">\n";
1292   $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";
1293   $display.= "</div>\n";
1295   if ($info != ""){
1296     $display.= "<div class=\"pluginfo\">\n";
1297     $display.= "$info";
1298     $display.= "</div>\n";
1299   } else {
1300     $display.= "<div style=\"height:5px;\">\n";
1301     $display.= "&nbsp;";
1302     $display.= "</div>\n";
1303   }
1304   if (isset($_SESSION['errors'])){
1305     $display.= $_SESSION['errors'];
1306   }
1308   return ($display);
1312 function register_global($name, $object)
1314   $_SESSION[$name]= $object;
1318 function is_global($name)
1320   return isset($_SESSION[$name]);
1324 function get_global($name)
1326   return $_SESSION[$name];
1330 function range_selector($dcnt,$start,$range=25,$post_var=false)
1333   /* Entries shown left and right from the selected entry */
1334   $max_entries= 10;
1336   /* Initialize and take care that max_entries is even */
1337   $output="";
1338   if ($max_entries & 1){
1339     $max_entries++;
1340   }
1342   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1343     $range= $_POST[$post_var];
1344   }
1346   /* Prevent output to start or end out of range */
1347   if ($start < 0 ){
1348     $start= 0 ;
1349   }
1350   if ($start >= $dcnt){
1351     $start= $range * (int)(($dcnt / $range) + 0.5);
1352   }
1354   $numpages= (($dcnt / $range));
1355   if(((int)($numpages))!=($numpages)){
1356     $numpages = (int)$numpages + 1;
1357   }
1358   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1359     return ("");
1360   }
1361   $ppage= (int)(($start / $range) + 0.5);
1364   /* Align selected page to +/- max_entries/2 */
1365   $begin= $ppage - $max_entries/2;
1366   $end= $ppage + $max_entries/2;
1368   /* Adjust begin/end, so that the selected value is somewhere in
1369      the middle and the size is max_entries if possible */
1370   if ($begin < 0){
1371     $end-= $begin + 1;
1372     $begin= 0;
1373   }
1374   if ($end > $numpages) {
1375     $end= $numpages;
1376   }
1377   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1378     $begin= $end - $max_entries;
1379   }
1381   if($post_var){
1382     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1383       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1384   }else{
1385     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1386   }
1388   /* Draw decrement */
1389   if ($start > 0 ) {
1390     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1391       (($start-$range))."\">".
1392       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1393   }
1395   /* Draw pages */
1396   for ($i= $begin; $i < $end; $i++) {
1397     if ($ppage == $i){
1398       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1399         validate($_GET['plug'])."&amp;start=".
1400         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1401     } else {
1402       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1403         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1404     }
1405   }
1407   /* Draw increment */
1408   if($start < ($dcnt-$range)) {
1409     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1410       (($start+($range)))."\">".
1411       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1412   }
1414   if(($post_var)&&($numpages)){
1415     $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()'>";
1416     foreach(array(20,50,100,200,"all") as $num){
1417       if($num == "all"){
1418         $var = 10000;
1419       }else{
1420         $var = $num;
1421       }
1422       if($var == $range){
1423         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1424       }else{  
1425         $output.="\n<option value='".$var."'>".$num."</option>";
1426       }
1427     }
1428     $output.=  "</select></td></tr></table></div>";
1429   }else{
1430     $output.= "</div>";
1431   }
1433   return($output);
1437 function apply_filter()
1439   $apply= "";
1441   $apply= ''.
1442     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1443     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1445   return ($apply);
1449 function back_to_main()
1451   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1452     _("Back").'"></p><input type="hidden" name="ignore">';
1454   return ($string);
1458 function normalize_netmask($netmask)
1460   /* Check for notation of netmask */
1461   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1462     $num= (int)($netmask);
1463     $netmask= "";
1465     for ($byte= 0; $byte<4; $byte++){
1466       $result=0;
1468       for ($i= 7; $i>=0; $i--){
1469         if ($num-- > 0){
1470           $result+= pow(2,$i);
1471         }
1472       }
1474       $netmask.= $result.".";
1475     }
1477     return (preg_replace('/\.$/', '', $netmask));
1478   }
1480   return ($netmask);
1484 function netmask_to_bits($netmask)
1486   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1487   $res= 0;
1489   for ($n= 0; $n<4; $n++){
1490     $start= 255;
1491     $name= "nm$n";
1493     for ($i= 0; $i<8; $i++){
1494       if ($start == (int)($$name)){
1495         $res+= 8 - $i;
1496         break;
1497       }
1498       $start-= pow(2,$i);
1499     }
1500   }
1502   return ($res);
1506 function recurse($rule, $variables)
1508   $result= array();
1510   if (!count($variables)){
1511     return array($rule);
1512   }
1514   reset($variables);
1515   $key= key($variables);
1516   $val= current($variables);
1517   unset ($variables[$key]);
1519   foreach($val as $possibility){
1520     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1521     $result= array_merge($result, recurse($nrule, $variables));
1522   }
1524   return ($result);
1528 function expand_id($rule, $attributes)
1530   /* Check for id rule */
1531   if(preg_match('/^id(:|#)\d+$/',$rule)){
1532     return (array("\{$rule}"));
1533   }
1535   /* Check for clean attribute */
1536   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1537     $rule= preg_replace('/^%/', '', $rule);
1538     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1539     return (array($val));
1540   }
1542   /* Check for attribute with parameters */
1543   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1544     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1545     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1546     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1547     $start= preg_replace ('/-.*$/', '', $param);
1548     $stop = preg_replace ('/^[^-]+-/', '', $param);
1550     /* Assemble results */
1551     $result= array();
1552     for ($i= $start; $i<= $stop; $i++){
1553       $result[]= substr($val, 0, $i);
1554     }
1555     return ($result);
1556   }
1558   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1559   return (array($rule));
1563 function gen_uids($rule, $attributes)
1565   global $config;
1567   /* Search for keys and fill the variables array with all 
1568      possible values for that key. */
1569   $part= "";
1570   $trigger= false;
1571   $stripped= "";
1572   $variables= array();
1574   for ($pos= 0; $pos < strlen($rule); $pos++){
1576     if ($rule[$pos] == "{" ){
1577       $trigger= true;
1578       $part= "";
1579       continue;
1580     }
1582     if ($rule[$pos] == "}" ){
1583       $variables[$pos]= expand_id($part, $attributes);
1584       $stripped.= "\{$pos}";
1585       $trigger= false;
1586       continue;
1587     }
1589     if ($trigger){
1590       $part.= $rule[$pos];
1591     } else {
1592       $stripped.= $rule[$pos];
1593     }
1594   }
1596   /* Recurse through all possible combinations */
1597   $proposed= recurse($stripped, $variables);
1599   /* Get list of used ID's */
1600   $used= array();
1601   $ldap= $config->get_ldap_link();
1602   $ldap->cd($config->current['BASE']);
1603   $ldap->search('(uid=*)');
1605   while($attrs= $ldap->fetch()){
1606     $used[]= $attrs['uid'][0];
1607   }
1609   /* Remove used uids and watch out for id tags */
1610   $ret= array();
1611   foreach($proposed as $uid){
1613     /* Check for id tag and modify uid if needed */
1614     if(preg_match('/\{id:\d+}/',$uid)){
1615       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1617       for ($i= 0; $i < pow(10,$size); $i++){
1618         $number= sprintf("%0".$size."d", $i);
1619         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1620         if (!in_array($res, $used)){
1621           $uid= $res;
1622           break;
1623         }
1624       }
1625     }
1627   if(preg_match('/\{id#\d+}/',$uid)){
1628     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1630     while (true){
1631       mt_srand((double) microtime()*1000000);
1632       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1633       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1634       if (!in_array($res, $used)){
1635         $uid= $res;
1636         break;
1637       }
1638     }
1639   }
1641 /* Don't assign used ones */
1642 if (!in_array($uid, $used)){
1643   $ret[]= $uid;
1647 return(array_unique($ret));
1651 function array_search_r($needle, $key, $haystack){
1653   foreach($haystack as $index => $value){
1654     $match= 0;
1656     if (is_array($value)){
1657       $match= array_search_r($needle, $key, $value);
1658     }
1660     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1661       $match=1;
1662     }
1664     if ($match){
1665       return 1;
1666     }
1667   }
1669   return 0;
1670
1673 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1674    Need to convert... */
1675 function to_byte($value) {
1676   $value= strtolower(trim($value));
1678   if(!is_numeric(substr($value, -1))) {
1680     switch(substr($value, -1)) {
1681       case 'g':
1682         $mult= 1073741824;
1683         break;
1684       case 'm':
1685         $mult= 1048576;
1686         break;
1687       case 'k':
1688         $mult= 1024;
1689         break;
1690     }
1692     return ($mult * (int)substr($value, 0, -1));
1693   } else {
1694     return $value;
1695   }
1699 function in_array_ics($value, $items)
1701   if (!is_array($items)){
1702     return (FALSE);
1703   }
1705   foreach ($items as $item){
1706     if (strtolower($item) == strtolower($value)) {
1707       return (TRUE);
1708     }
1709   }
1711   return (FALSE);
1712
1715 function generate_alphabet($count= 10)
1717   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1718   $alphabet= "";
1719   $c= 0;
1721   /* Fill cells with charaters */
1722   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1723     if ($c == 0){
1724       $alphabet.= "<tr>";
1725     }
1727     $ch = mb_substr($characters, $i, 1, "UTF8");
1728     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1729       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1731     if ($c++ == $count){
1732       $alphabet.= "</tr>";
1733       $c= 0;
1734     }
1735   }
1737   /* Fill remaining cells */
1738   while ($c++ <= $count){
1739     $alphabet.= "<td>&nbsp;</td>";
1740   }
1742   return ($alphabet);
1746 function validate($string)
1748   return (strip_tags(preg_replace('/\0/', '', $string)));
1751 function get_gosa_version()
1753   global $svn_revision, $svn_path;
1755   /* Extract informations */
1756   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1758   /* Release or development? */
1759   if (preg_match('%/gosa/trunk/%', $svn_path)){
1760     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1761   } else {
1762     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1763     return (sprintf(_("GOsa $release"), $revision));
1764   }
1768 function rmdirRecursive($path, $followLinks=false) {
1769   $dir= opendir($path);
1770   while($entry= readdir($dir)) {
1771     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1772       unlink($path."/".$entry);
1773     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1774       rmdirRecursive($path."/".$entry);
1775     }
1776   }
1777   closedir($dir);
1778   return rmdir($path);
1781 function scan_directory($path,$sort_desc=false)
1783   $ret = false;
1785   /* is this a dir ? */
1786   if(is_dir($path)) {
1788     /* is this path a readable one */
1789     if(is_readable($path)){
1791       /* Get contents and write it into an array */   
1792       $ret = array();    
1794       $dir = opendir($path);
1796       /* Is this a correct result ?*/
1797       if($dir){
1798         while($fp = readdir($dir))
1799           $ret[]= $fp;
1800       }
1801     }
1802   }
1803   /* Sort array ascending , like scandir */
1804   sort($ret);
1806   /* Sort descending if parameter is sort_desc is set */
1807   if($sort_desc) {
1808     $ret = array_reverse($ret);
1809   }
1811   return($ret);
1814 function clean_smarty_compile_dir($directory)
1816   global $svn_revision;
1818   if(is_dir($directory) && is_readable($directory)) {
1819     // Set revision filename to REVISION
1820     $revision_file= $directory."/REVISION";
1822     /* Is there a stamp containing the current revision? */
1823     if(!file_exists($revision_file)) {
1824       // create revision file
1825       create_revision($revision_file, $svn_revision);
1826     } else {
1827 # check for "$config->...['CONFIG']/revision" and the
1828 # contents should match the revision number
1829       if(!compare_revision($revision_file, $svn_revision)){
1830         // If revision differs, clean compile directory
1831         foreach(scan_directory($directory) as $file) {
1832           if(($file==".")||($file=="..")) continue;
1833           if( is_file($directory."/".$file) &&
1834               is_writable($directory."/".$file)) {
1835             // delete file
1836             if(!unlink($directory."/".$file)) {
1837               print_red("File ".$directory."/".$file." could not be deleted.");
1838               // This should never be reached
1839             }
1840           } elseif(is_dir($directory."/".$file) &&
1841               is_writable($directory."/".$file)) {
1842             // Just recursively delete it
1843             rmdirRecursive($directory."/".$file);
1844           }
1845         }
1846         // We should now create a fresh revision file
1847         clean_smarty_compile_dir($directory);
1848       } else {
1849         // Revision matches, nothing to do
1850       }
1851     }
1852   } else {
1853     // Smarty compile dir is not accessible
1854     // (Smarty will warn about this)
1855   }
1858 function create_revision($revision_file, $revision)
1860   $result= false;
1862   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1863     if($fh= fopen($revision_file, "w")) {
1864       if(fwrite($fh, $revision)) {
1865         $result= true;
1866       }
1867     }
1868     fclose($fh);
1869   } else {
1870     print_red("Can not write to revision file");
1871   }
1873   return $result;
1876 function compare_revision($revision_file, $revision)
1878   // false means revision differs
1879   $result= false;
1881   if(file_exists($revision_file) && is_readable($revision_file)) {
1882     // Open file
1883     if($fh= fopen($revision_file, "r")) {
1884       // Compare File contents with current revision
1885       if($revision == fread($fh, filesize($revision_file))) {
1886         $result= true;
1887       }
1888     } else {
1889       print_red("Can not open revision file");
1890     }
1891     // Close file
1892     fclose($fh);
1893   }
1895   return $result;
1898 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1900   $str = ""; // Our return value will be saved in this var
1902   $color  = dechex($percentage+150);
1903   $color2 = dechex(150 - $percentage);
1904   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1906   $progress = (int)(($percentage /100)*$width);
1908   /* Abort printing out percentage, if divs are to small */
1911   /* If theres a better solution for this, use it... */
1912   $str = "
1913     <div style=\" width:".($width)."px; 
1914     height:".($height)."px;
1915   background-color:#000000;
1916 padding:1px;\">
1918           <div style=\" width:".($width)."px;
1919         background-color:#$bgcolor;
1920 height:".($height)."px;\">
1922          <div style=\" width:".$progress."px;
1923 height:".$height."px;
1924        background-color:#".$color2.$color2.$color."; \">";
1927        if(($height >10)&&($showvalue)){
1928          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1929            <b>".$percentage."%</b>
1930            </font>";
1931        }
1933        $str.= "</div></div></div>";
1935        return($str);
1939 function array_key_ics($ikey, $items)
1941   /* Gather keys, make them lowercase */
1942   $tmp= array();
1943   foreach ($items as $key => $value){
1944     $tmp[strtolower($key)]= $key;
1945   }
1947   if (isset($tmp[strtolower($ikey)])){
1948     return($tmp[strtolower($ikey)]);
1949   }
1951   return ("");
1955 function search_config($arr, $name, $return)
1957   if (is_array($arr)){
1958     foreach ($arr as $a){
1959       if (isset($a['CLASS']) &&
1960           strtolower($a['CLASS']) == strtolower($name)){
1962         if (isset($a[$return])){
1963           return ($a[$return]);
1964         } else {
1965           return ("");
1966         }
1967       } else {
1968         $res= search_config ($a, $name, $return);
1969         if ($res != ""){
1970           return $res;
1971         }
1972       }
1973     }
1974   }
1975   return ("");
1979 function array_differs($src, $dst)
1981   /* If the count is differing, the arrays differ */
1982   if (count ($src) != count ($dst)){
1983     return (TRUE);
1984   }
1986   /* So the count is the same - lets check the contents */
1987   $differs= FALSE;
1988   foreach($src as $value){
1989     if (!in_array($value, $dst)){
1990       $differs= TRUE;
1991     }
1992   }
1994   return ($differs);
1998 function saveFilter($a_filter, $values)
2000   if (isset($_POST['regexit'])){
2001     $a_filter["regex"]= $_POST['regexit'];
2003     foreach($values as $type){
2004       if (isset($_POST[$type])) {
2005         $a_filter[$type]= "checked";
2006       } else {
2007         $a_filter[$type]= "";
2008       }
2009     }
2010   }
2012   /* React on alphabet links if needed */
2013   if (isset($_GET['search'])){
2014     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2015     if ($s == "**"){
2016       $s= "*";
2017     }
2018     $a_filter['regex']= $s;
2019   }
2021   return ($a_filter);
2025 /* Escape all preg_* relevant characters */
2026 function normalizePreg($input)
2028   return (addcslashes($input, '[]()|/.*+-'));
2032 /* Escape all LDAP filter relevant characters */
2033 function normalizeLdap($input)
2035   return (addcslashes($input, '()|'));
2039 /* Resturns the difference between to microtime() results in float  */
2040 function get_MicroTimeDiff($start , $stop)
2042   $a = split("\ ",$start);
2043   $b = split("\ ",$stop);
2045   $secs = $b[1] - $a[1];
2046   $msecs= $b[0] - $a[0]; 
2048   $ret = (float) ($secs+ $msecs);
2049   return($ret);
2053 /* Check if the given department name is valid */
2054 function is_department_name_reserved($name,$base)
2056   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2057                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2058                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2059   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2061   /* Check if name is one of the reserved names */
2062   if(in_array_ics($name,$reservedName)) {
2063     return(true);
2064   }
2066   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2067   foreach($follwedNames as $key => $names){
2068     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2069       return(true);
2070     }
2071   }
2072   return(false);
2076 function get_base_dir()
2078   global $BASE_DIR;
2080   return $BASE_DIR;
2084 function obj_is_readable($dn, $object, $attribute)
2086   global $ui;
2088   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2092 function obj_is_writable($dn, $object, $attribute)
2094   global $ui;
2096   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2100 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2102   /* Initialize variables */
2103   $ret  = array("count" => 0);  // Set count to 0
2104   $next = true;                 // if false, then skip next loops and return
2105   $cnt  = 0;                    // Current number of loops
2106   $max  = 100;                  // Just for security, prevent looops
2107   $ldap = NULL;                 // To check if created result a valid
2108   $keep = "";                   // save last failed parse string
2110   /* Check each parsed dn in ldap ? */
2111   if($config!=NULL && $verify_in_ldap){
2112     $ldap = $config->get_ldap_link();
2113   }
2115   $Diff = ldap_explode_dn($dn,0);
2117   /* Lets start */
2118   $called = false;
2119   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2121     $cnt ++;
2122     if(!preg_match("/,/",$dn)){
2123       $next = false;
2124     }
2125     $object = preg_replace("/[,].*$/","",$dn);
2126     $dn     = preg_replace("/^[^,]+,/","",$dn);
2128     $called = true;
2130     /* Check if current dn is valid */
2131     if($ldap!=NULL){
2132       $ldap->cd($dn);
2133       $ldap->cat($dn,array("dn"));
2134       if($ldap->count()){
2135         $ret[]  = $keep.$object;
2136         $keep   = "";
2137       }else{
2138         $keep  .= $object.",";
2139       }
2140     }else{
2141       $ret[]  = $keep.$object;
2142       $keep   = "";
2143     }
2144   }
2146   /* No dn was posted */
2147   if($cnt == 0 && !empty($dn)){
2148     $ret[] = $dn;
2149   }
2151   /* Append the rest */
2152   $test = $keep.$dn;
2153   if($called && !empty($test)){
2154     $ret[] = $keep.$dn;
2155   }
2156   $ret['count'] = count($ret) - 1;
2158   $diff = array_diff($ret,$Diff);
2159   if($diff){
2160     print_a(array("Diff" => $diff,"OLD" => $Diff,"NEW"=> $ret,"DEBUG"=> debug_backtrace()));
2161   }
2162   return($ret);
2165 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2166 ?>