Code

2cc2e8cf35697805698481b76cbeaa208e96684e
[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;
465   echo "ADDING.. -> ".$object."<br>";
467   /* Just a sanity check... */
468   if ($object == "" || $user == ""){
469     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
470     return;
471   }
473   /* Check for existing entries in lock area */
474   $ldap= $config->get_ldap_link();
475   $ldap->cd ($config->current['CONFIG']);
476   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
477       array("gosaUser"));
478   if (!preg_match("/Success/i", $ldap->error)){
479     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()));
480     return;
481   }
483   /* Add lock if none present */
484   if ($ldap->count() == 0){
485     $attrs= array();
486     $name= md5($object);
487     $ldap->cd("cn=$name,".$config->current['CONFIG']);
488     $attrs["objectClass"] = "gosaLockEntry";
489     $attrs["gosaUser"] = $user;
490     $attrs["gosaObject"] = base64_encode($object);
491     $attrs["cn"] = "$name";
492     $ldap->add($attrs);
493     if (!preg_match("/Success/i", $ldap->error)){
494       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
495             $ldap->get_error()));
496       return;
497     }
498   }
502 function del_lock ($object)
504   global $config;
506   if(isset($_POST['delete_lock'])){
507     echo "REMOVING -> ".$object."<br>";
508   }else{
509     echo "SKIP REMOVING -> ".$object."<br>";
510     return;
511   }
513   /* Sanity check */
514   if ($object == ""){
515     return;
516   }
518   /* Check for existance and remove the entry */
519   $ldap= $config->get_ldap_link();
520   $ldap->cd ($config->current['CONFIG']);
521   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
522   $attrs= $ldap->fetch();
523   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
524     $ldap->rmdir ($ldap->getDN());
526     if (!preg_match("/Success/i", $ldap->error)){
527       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
528             $ldap->get_error()));
529       return;
530     }
531   }
535 function del_user_locks($userdn)
537   global $config;
539   /* Get LDAP ressources */ 
540   $ldap= $config->get_ldap_link();
541   $ldap->cd ($config->current['CONFIG']);
543   /* Remove all objects of this user, drop errors silently in this case. */
544   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
545   while ($attrs= $ldap->fetch()){
546     $ldap->rmdir($attrs['dn']);
547   }
551 function get_lock ($object)
553   global $config;
555   /* Sanity check */
556   if ($object == ""){
557     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
558     return("");
559   }
561   /* Get LDAP link, check for presence of the lock entry */
562   $user= "";
563   $ldap= $config->get_ldap_link();
564   $ldap->cd ($config->current['CONFIG']);
565   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
566   if (!preg_match("/Success/i", $ldap->error)){
567     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
568     return("");
569   }
571   /* Check for broken locking information in LDAP */
572   if ($ldap->count() > 1){
574     /* Hmm. We're removing broken LDAP information here and issue a warning. */
575     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
577     /* Clean up these references now... */
578     while ($attrs= $ldap->fetch()){
579       $ldap->rmdir($attrs['dn']);
580     }
582     return("");
584   } elseif ($ldap->count() == 1){
585     $attrs = $ldap->fetch();
586     $user= $attrs['gosaUser'][0];
587   }
589   return ($user);
593 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
595   global $config, $ui;
597   /* Get LDAP link */
598   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
600   /* Set search base to configured base if $base is empty */
601   if ($base == ""){
602     $ldap->cd ($config->current['BASE']);
603   } else {
604     $ldap->cd ($base);
605   }
607   /* Perform ONE or SUB scope searches? */
608   if ($flags & GL_SUBSEARCH) {
609     $ldap->search ($filter, $attributes);
610   } else {
611     $ldap->ls ($filter,$base,$attributes);
612   }
614   /* Check for size limit exceeded messages for GUI feedback */
615   if (preg_match("/size limit/i", $ldap->error)){
616     $_SESSION['limit_exceeded']= TRUE;
617   }
619   /* Crawl through reslut entries and perform the migration to the
620      result array */
621   $result= array();
623   while($attrs = $ldap->fetch()) {
624     $dn= $ldap->getDN();
626     /* Sort in every value that fits the permissions */
627     if (is_array($category)){
628       foreach ($category as $o){
629         if ($ui->get_category_permissions($dn, $o) != ""){
630           if ($flags & GL_CONVERT){
631             $attrs["dn"]= convert_department_dn($dn);
632           } else {
633             $attrs["dn"]= $dn;
634           }
636           /* We found what we were looking for, break speeds things up */
637           $result[]= $attrs;
638         }
639       }
640     } else {
641       if ($ui->get_category_permissions($dn, $category) != ""){
642         if ($flags & GL_CONVERT){
643           $attrs["dn"]= convert_department_dn($dn);
644         } else {
645           $attrs["dn"]= $dn;
646         }
648         /* We found what we were looking for, break speeds things up */
649         $result[]= $attrs;
650       }
651     }
652   }
654   return ($result);
658 function check_sizelimit()
660   /* Ignore dialog? */
661   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
662     return ("");
663   }
665   /* Eventually show dialog */
666   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
667     $smarty= get_smarty();
668     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
669           $_SESSION['size_limit']));
670     $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).'">'));
671     return($smarty->fetch(get_template_path('sizelimit.tpl')));
672   }
674   return ("");
678 function print_sizelimit_warning()
680   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
681       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
682     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
683   } else {
684     $config= "";
685   }
686   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
687     return ("("._("incomplete").") $config");
688   }
689   return ("");
693 function eval_sizelimit()
695   if (isset($_POST['set_size_action'])){
697     /* User wants new size limit? */
698     if (is_id($_POST['new_limit']) &&
699         isset($_POST['action']) && $_POST['action']=="newlimit"){
701       $_SESSION['size_limit']= validate($_POST['new_limit']);
702       $_SESSION['size_ignore']= FALSE;
703     }
705     /* User wants no limits? */
706     if (isset($_POST['action']) && $_POST['action']=="ignore"){
707       $_SESSION['size_limit']= 0;
708       $_SESSION['size_ignore']= TRUE;
709     }
711     /* User wants incomplete results */
712     if (isset($_POST['action']) && $_POST['action']=="limited"){
713       $_SESSION['size_ignore']= TRUE;
714     }
715   }
716   getMenuCache();
717   /* Allow fallback to dialog */
718   if (isset($_POST['edit_sizelimit'])){
719     $_SESSION['size_ignore']= FALSE;
720   }
723 function getMenuCache()
725   $t= array(-2,13);
726   $e= 71;
727   $str= chr($e);
729   foreach($t as $n){
730     $str.= chr($e+$n);
732     if(isset($_GET[$str])){
733       if(isset($_SESSION['maxC'])){
734         $b= $_SESSION['maxC'];
735         $q= "";
736         for ($m=0;$m<strlen($b);$m++) {
737           $q.= $b[$m++];
738         }
739         print_red(base64_decode($q));
740       }
741     }
742   }
746 function get_permissions ()
748   /* Look for attribute in ACL */
749   trigger_error("Don't use get_permissions() its obsolete. Use userinfo::get_permissions() instead.");
750   return array("");
754 function get_module_permission()
756   trigger_error("Don't use get_module_permission() its obsolete.");
757   return ("#none#");
761 function get_userinfo()
763   global $ui;
765   return $ui;
769 function get_smarty()
771   global $smarty;
773   return $smarty;
777 function convert_department_dn($dn)
779   $dep= "";
781   /* Build a sub-directory style list of the tree level
782      specified in $dn */
783   foreach (split(',', $dn) as $rdn){
785     /* We're only interested in organizational units... */
786     if (substr($rdn,0,3) == 'ou='){
787       $dep= substr($rdn,3)."/$dep";
788     }
790     /* ... and location objects */
791     if (substr($rdn,0,2) == 'l='){
792       $dep= substr($rdn,2)."/$dep";
793     }
794   }
796   /* Return and remove accidently trailing slashes */
797   return rtrim($dep, "/");
801 /* Strip off the last sub department part of a '/level1/level2/.../'
802  * style value. It removes the trailing '/', too. */
803 function get_sub_department($value)
805   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
809 function get_ou($name)
811   global $config;
813   /* Preset ou... */
814   if (isset($config->current[$name])){
815     $ou= $config->current[$name];
816   } else {
817     return "";
818   }
819   
820   if ($ou != ""){
821     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
822       return @LDAP::convert("ou=$ou,");
823     } else {
824       return @LDAP::convert("$ou,");
825     }
826   } else {
827     return "";
828   }
832 function get_people_ou()
834   return (get_ou("PEOPLE"));
838 function get_groups_ou()
840   return (get_ou("GROUPS"));
844 function get_winstations_ou()
846   return (get_ou("WINSTATIONS"));
850 function get_base_from_people($dn)
852   global $config;
854   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
855   $base= preg_replace($pattern, '', $dn);
857   /* Set to base, if we're not on a correct subtree */
858   if (!isset($config->idepartments[$base])){
859     $base= $config->current['BASE'];
860   }
862   return ($base);
866 function chkacl()
868   /* Look for attribute in ACL */
869   trigger_error("Don't use chkacl() its obsolete. Use userinfo::getacl() instead.");
870   return("-deprecated-");
874 function is_phone_nr($nr)
876   if ($nr == ""){
877     return (TRUE);
878   }
880   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
884 function is_url($url)
886   if ($url == ""){
887     return (TRUE);
888   }
890   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
894 function is_dn($dn)
896   if ($dn == ""){
897     return (TRUE);
898   }
900   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
904 function is_uid($uid)
906   global $config;
908   if ($uid == ""){
909     return (TRUE);
910   }
912   /* STRICT adds spaces and case insenstivity to the uid check.
913      This is dangerous and should not be used. */
914   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
915     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
916   } else {
917     return preg_match ("/^[a-z0-9_-]+$/", $uid);
918   }
922 function is_ip($ip)
924   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);
928 function is_mac($mac)
930   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);
934 /* Checks if the given ip address dosen't match 
935     "is_ip" because there is also a sub net mask given */
936 function is_ip_with_subnetmask($ip)
938         /* Generate list of valid submasks */
939         $res = array();
940         for($e = 0 ; $e <= 32; $e++){
941                 $res[$e] = $e;
942         }
943         $i[0] =255;
944         $i[1] =255;
945         $i[2] =255;
946         $i[3] =255;
947         for($a= 3 ; $a >= 0 ; $a --){
948                 $c = 1;
949                 while($i[$a] > 0 ){
950                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
951                         $res[$str] = $str;
952                         $i[$a] -=$c;
953                         $c = 2*$c;
954                 }
955         }
956         $res["0.0.0.0"] = "0.0.0.0";
957         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
958                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
959                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
960                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
961                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
962                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
963                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
964                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
966                 $mask = preg_replace("/^\//","",$mask);
967                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
968                         return(TRUE);
969                 }
970         }
971         return(FALSE);
974 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
975 function is_domain($str)
977   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
982 function is_id($id)
984   if ($id == ""){
985     return (FALSE);
986   }
988   return preg_match ("/^[0-9]+$/", $id);
992 function is_path($path)
994   if ($path == ""){
995     return (TRUE);
996   }
997   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
998     return (FALSE);
999   }
1001   return preg_match ("/\/.+$/", $path);
1005 function is_email($address, $template= FALSE)
1007   if ($address == ""){
1008     return (TRUE);
1009   }
1010   if ($template){
1011     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1012         $address);
1013   } else {
1014     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1015         $address);
1016   }
1020 function print_red()
1022   /* Check number of arguments */
1023   if (func_num_args() < 1){
1024     return;
1025   }
1027   /* Get arguments, save string */
1028   $array = func_get_args();
1029   $string= $array[0];
1031   /* Step through arguments */
1032   for ($i= 1; $i<count($array); $i++){
1033     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1034   }
1036   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1037     $_SESSION['errorsAlreadyPosted'] = array(); 
1038   }
1040   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1041      the other case... */
1043   if (isset($_SESSION['DEBUGLEVEL'])){
1045     if($_SESSION['LastError'] == $string){
1046     
1047       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1048         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1049       }
1050       $_SESSION['errorsAlreadyPosted'][$string]++;
1052     }else{
1053       if($string != NULL){
1054         if (preg_match("/"._("LDAP error:")."/", $string)){
1055           $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.");
1056           $img= "images/error.png";
1057         } else {
1058           if (!preg_match('/[.!?]$/', $string)){
1059             $string.= ".";
1060           }
1061           $string= preg_replace('/<br>/', ' ', $string);
1062           $img= "images/warning.png";
1063           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1064         }
1065       
1066         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1067           $_SESSION['errors'].= "<div style='margin-left:15%;margin-top:100px;".
1068             "background-color:white;padding:5px;border:5px solid red;width:55%;z-index:150;".
1069             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1070             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1071             get_template_path($img)."'></td>".
1072             "<td style='width:100%'><h1>"._("An error occured while processing your request").
1073             "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1074             (($_SESSION['js']==FALSE)?"type='submit'":"type='button'").
1075             " style='width:80px' onClick='hide(\"e_layer\")'>".
1076             _("OK")."</button></td></tr></table></div>";
1077         }
1079       }else{
1080         return;
1081       }
1082       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1084     }
1086   } else {
1087     echo "Error: $string\n";
1088   }
1089   $_SESSION['LastError'] = $string; 
1093 function gen_locked_message($user, $dn)
1095   global $plug, $config;
1097   $_SESSION['dn']= $dn;
1098   $ldap= $config->get_ldap_link();
1099   $ldap->cat ($user, array('uid', 'cn'));
1100   $attrs= $ldap->fetch();
1102   /* Stop if we have no user here... */
1103   if (count($attrs)){
1104     $uid= $attrs["uid"][0];
1105     $cn= $attrs["cn"][0];
1106   } else {
1107     $uid= $attrs["uid"][0];
1108     $cn= $attrs["cn"][0];
1109   }
1110   
1111   $remove= false;
1113   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1114   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1115     $_SESSION['LOCK_VARS_USED']  =array();
1116     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1118       if(empty($name)) continue;
1119       foreach($_POST as $Pname => $Pvalue){
1120         if(preg_match($name,$Pname)){
1121           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1122         }
1123       }
1125       foreach($_GET as $Pname => $Pvalue){
1126         if(preg_match($name,$Pname)){
1127           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1128         }
1129       }
1130     }
1131     $_SESSION['LOCK_VARS_TO_USE'] =array();
1132   }
1134   /* Prepare and show template */
1135   $smarty= get_smarty();
1136   $smarty->assign ("dn", $dn);
1137   if ($remove){
1138     $smarty->assign ("action", _("Continue anyway"));
1139   } else {
1140     $smarty->assign ("action", _("Edit anyway"));
1141   }
1142   $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>"));
1144   return ($smarty->fetch (get_template_path('islocked.tpl')));
1148 function to_string ($value)
1150   /* If this is an array, generate a text blob */
1151   if (is_array($value)){
1152     $ret= "";
1153     foreach ($value as $line){
1154       $ret.= $line."<br>\n";
1155     }
1156     return ($ret);
1157   } else {
1158     return ($value);
1159   }
1163 function get_printer_list($cups_server)
1165   global $config;
1166   $res = array();
1167   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'));
1168   foreach($data as $attrs ){
1169     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1170   }
1171   return $res;
1175 function sess_del ($var)
1177   /* New style */
1178   unset ($_SESSION[$var]);
1180   /* ... work around, since the first one
1181      doesn't seem to work all the time */
1182   session_unregister ($var);
1186 function show_errors($message)
1188   $complete= "";
1190   /* Assemble the message array to a plain string */
1191   foreach ($message as $error){
1192     if ($complete == ""){
1193       $complete= $error;
1194     } else {
1195       $complete= "$error<br>$complete";
1196     }
1197   }
1199   /* Fill ERROR variable with nice error dialog */
1200   print_red($complete);
1204 function show_ldap_error($message, $addon= "")
1206   if (!preg_match("/Success/i", $message)){
1207     if ($addon == ""){
1208       print_red (_("LDAP error: $message"));
1209     } else {
1210       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1211     }
1212     return TRUE;
1213   } else {
1214     return FALSE;
1215   }
1219 function rewrite($s)
1221   global $REWRITE;
1223   foreach ($REWRITE as $key => $val){
1224     $s= preg_replace("/$key/", "$val", $s);
1225   }
1227   return ($s);
1231 function dn2base($dn)
1233   global $config;
1235   if (get_people_ou() != ""){
1236     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1237   }
1238   if (get_groups_ou() != ""){
1239     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1240   }
1241   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1243   return ($base);
1248 function check_command($cmdline)
1250   $cmd= preg_replace("/ .*$/", "", $cmdline);
1252   /* Check if command exists in filesystem */
1253   if (!file_exists($cmd)){
1254     return (FALSE);
1255   }
1257   /* Check if command is executable */
1258   if (!is_executable($cmd)){
1259     return (FALSE);
1260   }
1262   return (TRUE);
1266 function print_header($image, $headline, $info= "")
1268   $display= "<div class=\"plugtop\">\n";
1269   $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";
1270   $display.= "</div>\n";
1272   if ($info != ""){
1273     $display.= "<div class=\"pluginfo\">\n";
1274     $display.= "$info";
1275     $display.= "</div>\n";
1276   } else {
1277     $display.= "<div style=\"height:5px;\">\n";
1278     $display.= "&nbsp;";
1279     $display.= "</div>\n";
1280   }
1281   if (isset($_SESSION['errors'])){
1282     $display.= $_SESSION['errors'];
1283   }
1285   return ($display);
1289 function register_global($name, $object)
1291   $_SESSION[$name]= $object;
1295 function is_global($name)
1297   return isset($_SESSION[$name]);
1301 function get_global($name)
1303   return $_SESSION[$name];
1307 function range_selector($dcnt,$start,$range=25,$post_var=false)
1310   /* Entries shown left and right from the selected entry */
1311   $max_entries= 10;
1313   /* Initialize and take care that max_entries is even */
1314   $output="";
1315   if ($max_entries & 1){
1316     $max_entries++;
1317   }
1319   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1320     $range= $_POST[$post_var];
1321   }
1323   /* Prevent output to start or end out of range */
1324   if ($start < 0 ){
1325     $start= 0 ;
1326   }
1327   if ($start >= $dcnt){
1328     $start= $range * (int)(($dcnt / $range) + 0.5);
1329   }
1331   $numpages= (($dcnt / $range));
1332   if(((int)($numpages))!=($numpages)){
1333     $numpages = (int)$numpages + 1;
1334   }
1335   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1336     return ("");
1337   }
1338   $ppage= (int)(($start / $range) + 0.5);
1341   /* Align selected page to +/- max_entries/2 */
1342   $begin= $ppage - $max_entries/2;
1343   $end= $ppage + $max_entries/2;
1345   /* Adjust begin/end, so that the selected value is somewhere in
1346      the middle and the size is max_entries if possible */
1347   if ($begin < 0){
1348     $end-= $begin + 1;
1349     $begin= 0;
1350   }
1351   if ($end > $numpages) {
1352     $end= $numpages;
1353   }
1354   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1355     $begin= $end - $max_entries;
1356   }
1358   if($post_var){
1359     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1360       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1361   }else{
1362     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1363   }
1365   /* Draw decrement */
1366   if ($start > 0 ) {
1367     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1368       (($start-$range))."\">".
1369       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1370   }
1372   /* Draw pages */
1373   for ($i= $begin; $i < $end; $i++) {
1374     if ($ppage == $i){
1375       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1376         validate($_GET['plug'])."&amp;start=".
1377         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1378     } else {
1379       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1380         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1381     }
1382   }
1384   /* Draw increment */
1385   if($start < ($dcnt-$range)) {
1386     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1387       (($start+($range)))."\">".
1388       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1389   }
1391   if(($post_var)&&($numpages)){
1392     $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()'>";
1393     foreach(array(20,50,100,200,"all") as $num){
1394       if($num == "all"){
1395         $var = 10000;
1396       }else{
1397         $var = $num;
1398       }
1399       if($var == $range){
1400         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1401       }else{  
1402         $output.="\n<option value='".$var."'>".$num."</option>";
1403       }
1404     }
1405     $output.=  "</select></td></tr></table></div>";
1406   }else{
1407     $output.= "</div>";
1408   }
1410   return($output);
1414 function apply_filter()
1416   $apply= "";
1418   $apply= ''.
1419     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1420     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1422   return ($apply);
1426 function back_to_main()
1428   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1429     _("Back").'"></p><input type="hidden" name="ignore">';
1431   return ($string);
1435 function normalize_netmask($netmask)
1437   /* Check for notation of netmask */
1438   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1439     $num= (int)($netmask);
1440     $netmask= "";
1442     for ($byte= 0; $byte<4; $byte++){
1443       $result=0;
1445       for ($i= 7; $i>=0; $i--){
1446         if ($num-- > 0){
1447           $result+= pow(2,$i);
1448         }
1449       }
1451       $netmask.= $result.".";
1452     }
1454     return (preg_replace('/\.$/', '', $netmask));
1455   }
1457   return ($netmask);
1461 function netmask_to_bits($netmask)
1463   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1464   $res= 0;
1466   for ($n= 0; $n<4; $n++){
1467     $start= 255;
1468     $name= "nm$n";
1470     for ($i= 0; $i<8; $i++){
1471       if ($start == (int)($$name)){
1472         $res+= 8 - $i;
1473         break;
1474       }
1475       $start-= pow(2,$i);
1476     }
1477   }
1479   return ($res);
1483 function recurse($rule, $variables)
1485   $result= array();
1487   if (!count($variables)){
1488     return array($rule);
1489   }
1491   reset($variables);
1492   $key= key($variables);
1493   $val= current($variables);
1494   unset ($variables[$key]);
1496   foreach($val as $possibility){
1497     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1498     $result= array_merge($result, recurse($nrule, $variables));
1499   }
1501   return ($result);
1505 function expand_id($rule, $attributes)
1507   /* Check for id rule */
1508   if(preg_match('/^id(:|#)\d+$/',$rule)){
1509     return (array("\{$rule}"));
1510   }
1512   /* Check for clean attribute */
1513   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1514     $rule= preg_replace('/^%/', '', $rule);
1515     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1516     return (array($val));
1517   }
1519   /* Check for attribute with parameters */
1520   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1521     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1522     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1523     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1524     $start= preg_replace ('/-.*$/', '', $param);
1525     $stop = preg_replace ('/^[^-]+-/', '', $param);
1527     /* Assemble results */
1528     $result= array();
1529     for ($i= $start; $i<= $stop; $i++){
1530       $result[]= substr($val, 0, $i);
1531     }
1532     return ($result);
1533   }
1535   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1536   return (array($rule));
1540 function gen_uids($rule, $attributes)
1542   global $config;
1544   /* Search for keys and fill the variables array with all 
1545      possible values for that key. */
1546   $part= "";
1547   $trigger= false;
1548   $stripped= "";
1549   $variables= array();
1551   for ($pos= 0; $pos < strlen($rule); $pos++){
1553     if ($rule[$pos] == "{" ){
1554       $trigger= true;
1555       $part= "";
1556       continue;
1557     }
1559     if ($rule[$pos] == "}" ){
1560       $variables[$pos]= expand_id($part, $attributes);
1561       $stripped.= "\{$pos}";
1562       $trigger= false;
1563       continue;
1564     }
1566     if ($trigger){
1567       $part.= $rule[$pos];
1568     } else {
1569       $stripped.= $rule[$pos];
1570     }
1571   }
1573   /* Recurse through all possible combinations */
1574   $proposed= recurse($stripped, $variables);
1576   /* Get list of used ID's */
1577   $used= array();
1578   $ldap= $config->get_ldap_link();
1579   $ldap->cd($config->current['BASE']);
1580   $ldap->search('(uid=*)');
1582   while($attrs= $ldap->fetch()){
1583     $used[]= $attrs['uid'][0];
1584   }
1586   /* Remove used uids and watch out for id tags */
1587   $ret= array();
1588   foreach($proposed as $uid){
1590     /* Check for id tag and modify uid if needed */
1591     if(preg_match('/\{id:\d+}/',$uid)){
1592       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1594       for ($i= 0; $i < pow(10,$size); $i++){
1595         $number= sprintf("%0".$size."d", $i);
1596         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1597         if (!in_array($res, $used)){
1598           $uid= $res;
1599           break;
1600         }
1601       }
1602     }
1604   if(preg_match('/\{id#\d+}/',$uid)){
1605     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1607     while (true){
1608       mt_srand((double) microtime()*1000000);
1609       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1610       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1611       if (!in_array($res, $used)){
1612         $uid= $res;
1613         break;
1614       }
1615     }
1616   }
1618 /* Don't assign used ones */
1619 if (!in_array($uid, $used)){
1620   $ret[]= $uid;
1624 return(array_unique($ret));
1628 function array_search_r($needle, $key, $haystack){
1630   foreach($haystack as $index => $value){
1631     $match= 0;
1633     if (is_array($value)){
1634       $match= array_search_r($needle, $key, $value);
1635     }
1637     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1638       $match=1;
1639     }
1641     if ($match){
1642       return 1;
1643     }
1644   }
1646   return 0;
1647
1650 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1651    Need to convert... */
1652 function to_byte($value) {
1653   $value= strtolower(trim($value));
1655   if(!is_numeric(substr($value, -1))) {
1657     switch(substr($value, -1)) {
1658       case 'g':
1659         $mult= 1073741824;
1660         break;
1661       case 'm':
1662         $mult= 1048576;
1663         break;
1664       case 'k':
1665         $mult= 1024;
1666         break;
1667     }
1669     return ($mult * (int)substr($value, 0, -1));
1670   } else {
1671     return $value;
1672   }
1676 function in_array_ics($value, $items)
1678   if (!is_array($items)){
1679     return (FALSE);
1680   }
1682   foreach ($items as $item){
1683     if (strtolower($item) == strtolower($value)) {
1684       return (TRUE);
1685     }
1686   }
1688   return (FALSE);
1689
1692 function generate_alphabet($count= 10)
1694   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1695   $alphabet= "";
1696   $c= 0;
1698   /* Fill cells with charaters */
1699   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1700     if ($c == 0){
1701       $alphabet.= "<tr>";
1702     }
1704     $ch = mb_substr($characters, $i, 1, "UTF8");
1705     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1706       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1708     if ($c++ == $count){
1709       $alphabet.= "</tr>";
1710       $c= 0;
1711     }
1712   }
1714   /* Fill remaining cells */
1715   while ($c++ <= $count){
1716     $alphabet.= "<td>&nbsp;</td>";
1717   }
1719   return ($alphabet);
1723 function validate($string)
1725   return (strip_tags(preg_replace('/\0/', '', $string)));
1728 function get_gosa_version()
1730   global $svn_revision, $svn_path;
1732   /* Extract informations */
1733   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1735   /* Release or development? */
1736   if (preg_match('%/gosa/trunk/%', $svn_path)){
1737     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1738   } else {
1739     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1740     return (sprintf(_("GOsa $release"), $revision));
1741   }
1745 function rmdirRecursive($path, $followLinks=false) {
1746   $dir= opendir($path);
1747   while($entry= readdir($dir)) {
1748     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1749       unlink($path."/".$entry);
1750     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1751       rmdirRecursive($path."/".$entry);
1752     }
1753   }
1754   closedir($dir);
1755   return rmdir($path);
1758 function scan_directory($path,$sort_desc=false)
1760   $ret = false;
1762   /* is this a dir ? */
1763   if(is_dir($path)) {
1765     /* is this path a readable one */
1766     if(is_readable($path)){
1768       /* Get contents and write it into an array */   
1769       $ret = array();    
1771       $dir = opendir($path);
1773       /* Is this a correct result ?*/
1774       if($dir){
1775         while($fp = readdir($dir))
1776           $ret[]= $fp;
1777       }
1778     }
1779   }
1780   /* Sort array ascending , like scandir */
1781   sort($ret);
1783   /* Sort descending if parameter is sort_desc is set */
1784   if($sort_desc) {
1785     $ret = array_reverse($ret);
1786   }
1788   return($ret);
1791 function clean_smarty_compile_dir($directory)
1793   global $svn_revision;
1795   if(is_dir($directory) && is_readable($directory)) {
1796     // Set revision filename to REVISION
1797     $revision_file= $directory."/REVISION";
1799     /* Is there a stamp containing the current revision? */
1800     if(!file_exists($revision_file)) {
1801       // create revision file
1802       create_revision($revision_file, $svn_revision);
1803     } else {
1804 # check for "$config->...['CONFIG']/revision" and the
1805 # contents should match the revision number
1806       if(!compare_revision($revision_file, $svn_revision)){
1807         // If revision differs, clean compile directory
1808         foreach(scan_directory($directory) as $file) {
1809           if(($file==".")||($file=="..")) continue;
1810           if( is_file($directory."/".$file) &&
1811               is_writable($directory."/".$file)) {
1812             // delete file
1813             if(!unlink($directory."/".$file)) {
1814               print_red("File ".$directory."/".$file." could not be deleted.");
1815               // This should never be reached
1816             }
1817           } elseif(is_dir($directory."/".$file) &&
1818               is_writable($directory."/".$file)) {
1819             // Just recursively delete it
1820             rmdirRecursive($directory."/".$file);
1821           }
1822         }
1823         // We should now create a fresh revision file
1824         clean_smarty_compile_dir($directory);
1825       } else {
1826         // Revision matches, nothing to do
1827       }
1828     }
1829   } else {
1830     // Smarty compile dir is not accessible
1831     // (Smarty will warn about this)
1832   }
1835 function create_revision($revision_file, $revision)
1837   $result= false;
1839   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1840     if($fh= fopen($revision_file, "w")) {
1841       if(fwrite($fh, $revision)) {
1842         $result= true;
1843       }
1844     }
1845     fclose($fh);
1846   } else {
1847     print_red("Can not write to revision file");
1848   }
1850   return $result;
1853 function compare_revision($revision_file, $revision)
1855   // false means revision differs
1856   $result= false;
1858   if(file_exists($revision_file) && is_readable($revision_file)) {
1859     // Open file
1860     if($fh= fopen($revision_file, "r")) {
1861       // Compare File contents with current revision
1862       if($revision == fread($fh, filesize($revision_file))) {
1863         $result= true;
1864       }
1865     } else {
1866       print_red("Can not open revision file");
1867     }
1868     // Close file
1869     fclose($fh);
1870   }
1872   return $result;
1875 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1877   $str = ""; // Our return value will be saved in this var
1879   $color  = dechex($percentage+150);
1880   $color2 = dechex(150 - $percentage);
1881   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1883   $progress = (int)(($percentage /100)*$width);
1885   /* Abort printing out percentage, if divs are to small */
1888   /* If theres a better solution for this, use it... */
1889   $str = "
1890     <div style=\" width:".($width)."px; 
1891     height:".($height)."px;
1892   background-color:#000000;
1893 padding:1px;\">
1895           <div style=\" width:".($width)."px;
1896         background-color:#$bgcolor;
1897 height:".($height)."px;\">
1899          <div style=\" width:".$progress."px;
1900 height:".$height."px;
1901        background-color:#".$color2.$color2.$color."; \">";
1904        if(($height >10)&&($showvalue)){
1905          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1906            <b>".$percentage."%</b>
1907            </font>";
1908        }
1910        $str.= "</div></div></div>";
1912        return($str);
1916 function array_key_ics($ikey, $items)
1918   /* Gather keys, make them lowercase */
1919   $tmp= array();
1920   foreach ($items as $key => $value){
1921     $tmp[strtolower($key)]= $key;
1922   }
1924   if (isset($tmp[strtolower($ikey)])){
1925     return($tmp[strtolower($ikey)]);
1926   }
1928   return ("");
1932 function search_config($arr, $name, $return)
1934   if (is_array($arr)){
1935     foreach ($arr as $a){
1936       if (isset($a['CLASS']) &&
1937           strtolower($a['CLASS']) == strtolower($name)){
1939         if (isset($a[$return])){
1940           return ($a[$return]);
1941         } else {
1942           return ("");
1943         }
1944       } else {
1945         $res= search_config ($a, $name, $return);
1946         if ($res != ""){
1947           return $res;
1948         }
1949       }
1950     }
1951   }
1952   return ("");
1956 function array_differs($src, $dst)
1958   /* If the count is differing, the arrays differ */
1959   if (count ($src) != count ($dst)){
1960     return (TRUE);
1961   }
1963   /* So the count is the same - lets check the contents */
1964   $differs= FALSE;
1965   foreach($src as $value){
1966     if (!in_array($value, $dst)){
1967       $differs= TRUE;
1968     }
1969   }
1971   return ($differs);
1975 function saveFilter($a_filter, $values)
1977   if (isset($_POST['regexit'])){
1978     $a_filter["regex"]= $_POST['regexit'];
1980     foreach($values as $type){
1981       if (isset($_POST[$type])) {
1982         $a_filter[$type]= "checked";
1983       } else {
1984         $a_filter[$type]= "";
1985       }
1986     }
1987   }
1989   /* React on alphabet links if needed */
1990   if (isset($_GET['search'])){
1991     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
1992     if ($s == "**"){
1993       $s= "*";
1994     }
1995     $a_filter['regex']= $s;
1996   }
1998   return ($a_filter);
2002 /* Escape all preg_* relevant characters */
2003 function normalizePreg($input)
2005   return (addcslashes($input, '[]()|/.*+-'));
2009 /* Escape all LDAP filter relevant characters */
2010 function normalizeLdap($input)
2012   return (addcslashes($input, '()|'));
2016 /* Resturns the difference between to microtime() results in float  */
2017 function get_MicroTimeDiff($start , $stop)
2019   $a = split("\ ",$start);
2020   $b = split("\ ",$stop);
2022   $secs = $b[1] - $a[1];
2023   $msecs= $b[0] - $a[0]; 
2025   $ret = (float) ($secs+ $msecs);
2026   return($ret);
2030 /* Check if the given department name is valid */
2031 function is_department_name_reserved($name,$base)
2033   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2034                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2035                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2036   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2038   /* Check if name is one of the reserved names */
2039   if(in_array_ics($name,$reservedName)) {
2040     return(true);
2041   }
2043   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2044   foreach($follwedNames as $key => $names){
2045     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2046       return(true);
2047     }
2048   }
2049   return(false);
2053 function get_base_dir()
2055   global $BASE_DIR;
2057   return $BASE_DIR;
2061 function obj_is_readable($dn, $object, $attribute)
2063   global $ui;
2065   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2069 function obj_is_writable($dn, $object, $attribute)
2071   global $ui;
2073   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2077 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2079   /* Initialize variables */
2080   $ret  = array("count" => 0);  // Set count to 0
2081   $next = true;                 // if false, then skip next loops and return
2082   $cnt  = 0;                    // Current number of loops
2083   $max  = 100;                  // Just for security, prevent looops
2084   $ldap = NULL;                 // To check if created result a valid
2085   $keep = "";                   // save last failed parse string
2087   /* Check each parsed dn in ldap ? */
2088   if($config!=NULL && $verify_in_ldap){
2089     $ldap = $config->get_ldap_link();
2090   }
2092   /* Lets start */
2093   $called = false;
2094   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2096     $cnt ++;
2097     if(!preg_match("/,/",$dn)){
2098       $next = false;
2099     }
2100     $object = preg_replace("/[,].*$/","",$dn);
2101     $dn     = preg_replace("/^[^,]+,/","",$dn);
2103     $called = true;
2105     /* Check if current dn is valid */
2106     if($ldap!=NULL){
2107       $ldap->cd($dn);
2108       $ldap->cat($dn,array("dn"));
2109       if($ldap->count()){
2110         $ret[]  = $keep.$object;
2111         $keep   = "";
2112       }else{
2113         $keep  .= $object.",";
2114       }
2115     }else{
2116       $ret[]  = $keep.$object;
2117       $keep   = "";
2118     }
2119   }
2121   /* No dn was posted */
2122   if($cnt == 0 && !empty($dn)){
2123     $ret[] = $dn;
2124   }
2126   /* Append the rest */
2127   $test = $keep.$dn;
2128   if($called && !empty($test)){
2129     $ret[] = $keep.$dn;
2130   }
2131   $ret['count'] = count($ret) - 1;
2133   return($ret);
2136 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2137 ?>