Code

fixed some errors
[gosa.git] / include / functions.inc
1 <?php
2 /*
3  * This code is part of GOsa (https://gosa.gonicus.de)
4  * Copyright (C) 2003 Cajus Pollmeier
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
21 /* Configuration file location */
22 define ("CONFIG_DIR", "/etc/gosa");
23 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
24 define ("HELP_BASEDIR", "/var/www/doc/");
26 /* Define get_list flags */
27 define("GL_NONE",      0);
28 define("GL_SUBSEARCH", 1);
29 define("GL_SIZELIMIT", 2);
30 define("GL_CONVERT"  , 4);
32 /* Define globals for revision comparing */
33 $svn_path = '$HeadURL$';
34 $svn_revision = '$Revision$';
36 /* Include required files */
37 require_once ("class_ldap.inc");
38 require_once ("class_config.inc");
39 require_once ("class_userinfo.inc");
40 require_once ("class_plugin.inc");
41 require_once ("class_pluglist.inc");
42 require_once ("class_tabs.inc");
43 require_once ("class_mail-methods.inc");
44 require_once("class_password-methods.inc");
45 require_once ("functions_debug.inc");
46 require_once ("functions_dns.inc");
47 require_once ("class_MultiSelectWindow.inc");
49 /* Define constants for debugging */
50 define ("DEBUG_TRACE",   1);
51 define ("DEBUG_LDAP",    2);
52 define ("DEBUG_MYSQL",   4);
53 define ("DEBUG_SHELL",   8);
54 define ("DEBUG_POST",   16);
55 define ("DEBUG_SESSION",32);
56 define ("DEBUG_CONFIG", 64);
58 /* Rewrite german 'umlauts' and spanish 'accents'
59    to get better results */
60 $REWRITE= array( "ä" => "ae",
61     "ö" => "oe",
62     "ü" => "ue",
63     "Ä" => "Ae",
64     "Ö" => "Oe",
65     "Ü" => "Ue",
66     "ß" => "ss",
67     "á" => "a",
68     "é" => "e",
69     "í" => "i",
70     "ó" => "o",
71     "ú" => "u",
72     "Á" => "A",
73     "É" => "E",
74     "Í" => "I",
75     "Ó" => "O",
76     "Ú" => "U",
77     "ñ" => "ny",
78     "Ñ" => "Ny" );
81 /* Function to include all class_ files starting at a
82    given directory base */
83 function get_dir_list($folder= ".")
84 {
85   $currdir=getcwd();
86   if ($folder){
87     chdir("$folder");
88   }
90   $dh = opendir(".");
91   while(false !== ($file = readdir($dh))){
93     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
94     // Skip all files and dirs in  "./.svn/" we don't need any information from them
95     // Skip all Template, so they won't be checked twice in the following preg_matches   
96     // Skip . / ..
98     // Result  : from 1023 ms to 490 ms   i think thats great...
99     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
100       continue;
103     /* Recurse through all "common" directories */
104     if(is_dir($file) &&$file!="CVS"){
105       get_dir_list($file);
106       continue;
107     }
109     /* Include existing class_ files */
110     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
111       require_once($file);
112     }
113   }
115   closedir($dh);
116   chdir($currdir);
120 /* Create seed with microseconds */
121 function make_seed() {
122   list($usec, $sec) = explode(' ', microtime());
123   return (float) $sec + ((float) $usec * 100000);
127 /* Debug level action */
128 function DEBUG($level, $line, $function, $file, $data, $info="")
130   if ($_SESSION['DEBUGLEVEL'] & $level){
131     $output= "DEBUG[$level] ";
132     if ($function != ""){
133       $output.= "($file:$function():$line) - $info: ";
134     } else {
135       $output.= "($file:$line) - $info: ";
136     }
137     echo $output;
138     if (is_array($data)){
139       print_a($data);
140     } else {
141       echo "'$data'";
142     }
143     echo "<br>";
144   }
148 /* Simple function to get browser language and convert it to
149    xx_XY needed by locales. Ignores sublanguages and weights. */
150 function get_browser_language()
152   global $BASE_DIR;
154   /* Try to use users primary language */
155   $ui= get_userinfo();
156   if ($ui != NULL){
157     if ($ui->language != ""){
158       return ($ui->language);
159     }
160   }
162   /* Get list of languages */
163   if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
164     $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
165     $languages= split (',', $lang);
166     $languages[]= "C";
167   } else {
168     $languages= array("C");
169   }
171   /* Walk through languages and get first supported */
172   foreach ($languages as $val){
174     /* Strip off weight */
175     $lang= preg_replace("/;q=.*$/i", "", $val);
177     /* Simplify sub language handling */
178     $lang= preg_replace("/-.*$/", "", $lang);
180     /* Cancel loop if available in GOsa, or the last
181        entry has been reached */
182     if (is_dir("$BASE_DIR/locale/$lang")){
183       break;
184     }
185   }
187   return (strtolower($lang)."_".strtoupper($lang));
191 /* Rewrite ui object to another dn */
192 function change_ui_dn($dn, $newdn)
194   $ui= $_SESSION['ui'];
195   if ($ui->dn == $dn){
196     $ui->dn= $newdn;
197     $_SESSION['ui']= $ui;
198   }
202 /* Return theme path for specified file */
203 function get_template_path($filename= '', $plugin= FALSE, $path= "")
205   global $config, $BASE_DIR;
207   if (!@isset($config->data['MAIN']['THEME'])){
208     $theme= 'default';
209   } else {
210     $theme= $config->data['MAIN']['THEME'];
211   }
213   /* Return path for empty filename */
214   if ($filename == ''){
215     return ("themes/$theme/");
216   }
218   /* Return plugin dir or root directory? */
219   if ($plugin){
220     if ($path == ""){
221       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
222     } else {
223       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
224     }
225     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
226       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
227     }
228     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
229       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
230     }
231     if ($path == ""){
232       return ($_SESSION['plugin_dir']."/$filename");
233     } else {
234       return ($path."/$filename");
235     }
236   } else {
237     if (file_exists("themes/$theme/$filename")){
238       return ("themes/$theme/$filename");
239     }
240     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
241       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
242     }
243     if (file_exists("themes/default/$filename")){
244       return ("themes/default/$filename");
245     }
246     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
247       return ("$BASE_DIR/ihtml/themes/default/$filename");
248     }
249     return ($filename);
250   }
254 function array_remove_entries($needles, $haystack)
256   $tmp= array();
258   /* Loop through entries to be removed */
259   foreach ($haystack as $entry){
260     if (!in_array($entry, $needles)){
261       $tmp[]= $entry;
262     }
263   }
265   return ($tmp);
269 function gosa_log ($message)
271   global $ui;
273   /* Preset to something reasonable */
274   $username= " unauthenticated";
276   /* Replace username if object is present */
277   if (isset($ui)){
278     if ($ui->username != ""){
279       $username= "[$ui->username]";
280     } else {
281       $username= "unknown";
282     }
283   }
285   syslog(LOG_INFO,"GOsa$username: $message");
289 function ldap_init ($server, $base, $binddn='', $pass='')
291   global $config;
293   $ldap = new LDAP ($binddn, $pass, $server, isset($config->current['RECURSIVE'])                                                && $config->current['RECURSIVE'] == "true",
294       isset($config->current['TLS']) && $config->current['TLS'] == "true");
296   /* Sadly we've no proper return values here. Use the error message instead. */
297   if (!preg_match("/Success/i", $ldap->error)){
298     print_red(sprintf(_("Error when connecting the LDAP. Server said '%s'."),
299           $ldap->get_error()));
300     echo $_SESSION['errors'];
302     /* Hard error. We'd like to use the LDAP, anyway... */
303     exit;
304   }
306   /* Preset connection base to $base and return to caller */
307   $ldap->cd ($base);
308   return $ldap;
312 function ldap_login_user ($username, $password)
314   global $config;
316   /* look through the entire ldap */
317   $ldap = $config->get_ldap_link();
318   if (!preg_match("/Success/i", $ldap->error)){
319     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
320     echo $_SESSION['errors'];
321     exit;
322   }
323   $ldap->cd($config->current['BASE']);
324   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
326   /* get results, only a count of 1 is valid */
327   switch ($ldap->count()){
329     /* user not found */
330     case 0:     return (NULL);
332             /* valid uniq user */
333     case 1: 
334             break;
336             /* found more than one matching id */
337     default:
338             print_red(_("Username / UID is not unique. Please check your LDAP database."));
339             return (NULL);
340   }
342   /* LDAP schema is not case sensitive. Perform additional check. */
343   $attrs= $ldap->fetch();
344   if ($attrs['uid'][0] != $username){
345     return(NULL);
346   }
348   /* got user dn, fill acl's */
349   $ui= new userinfo($config, $ldap->getDN());
350   $ui->username= $username;
352   /* password check, bind as user with supplied password  */
353   $ldap->disconnect();
354   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
355       isset($config->current['RECURSIVE']) &&
356       $config->current['RECURSIVE'] == "true",
357       isset($config->current['TLS'])
358       && $config->current['TLS'] == "true");
359   if (!preg_match("/Success/i", $ldap->error)){
360     return (NULL);
361   }
363   /* Username is set, load subtreeACL's now */
364   $ui->loadACL();
366   return ($ui);
370 function ldap_expired_account($config, $userdn, $username)
372     $this->config= $config;
373     $ldap= $this->config->get_ldap_link();
374     $ldap->cat($userdn);
375     $attrs= $ldap->fetch();
376     
377     /* default value no errors */
378     $expired = 0;
379     
380     $sExpire = 0;
381     $sLastChange = 0;
382     $sMax = 0;
383     $sMin = 0;
384     $sInactive = 0;
385     $sWarning = 0;
386     
387     $current= date("U");
388     
389     $current= floor($current /60 /60 /24);
390     
391     /* special case of the admin, should never been locked */
392     /* FIXME should allow any name as user admin */
393     if($username != "admin")
394     {
396       if(isset($attrs['shadowExpire'][0])){
397         $sExpire= $attrs['shadowExpire'][0];
398       } else {
399         $sExpire = 0;
400       }
401       
402       if(isset($attrs['shadowLastChange'][0])){
403         $sLastChange= $attrs['shadowLastChange'][0];
404       } else {
405         $sLastChange = 0;
406       }
407       
408       if(isset($attrs['shadowMax'][0])){
409         $sMax= $attrs['shadowMax'][0];
410       } else {
411         $smax = 0;
412       }
414       if(isset($attrs['shadowMin'][0])){
415         $sMin= $attrs['shadowMin'][0];
416       } else {
417         $sMin = 0;
418       }
419       
420       if(isset($attrs['shadowInactive'][0])){
421         $sInactive= $attrs['shadowInactive'][0];
422       } else {
423         $sInactive = 0;
424       }
425       
426       if(isset($attrs['shadowWarning'][0])){
427         $sWarning= $attrs['shadowWarning'][0];
428       } else {
429         $sWarning = 0;
430       }
431       
432       /* is the account locked */
433       /* shadowExpire + shadowInactive (option) */
434       if($sExpire >0){
435         if($current >= ($sExpire+$sInactive)){
436           return(1);
437         }
438       }
439     
440       /* the user should be warned to change is password */
441       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
442         if (($sExpire - $current) < $sWarning){
443           return(2);
444         }
445       }
446       
447       /* force user to change password */
448       if(($sLastChange >0) && ($sMax) >0){
449         if($current >= ($sLastChange+$sMax)){
450           return(3);
451         }
452       }
453       
454       /* the user should not be able to change is password */
455       if(($sLastChange >0) && ($sMin >0)){
456         if (($sLastChange + $sMin) >= $current){
457           return(4);
458         }
459       }
460     }
461    return($expired);
464 function add_lock ($object, $user)
466   global $config;
468   /* Just a sanity check... */
469   if ($object == "" || $user == ""){
470     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
471     return;
472   }
474   /* Check for existing entries in lock area */
475   $ldap= $config->get_ldap_link();
476   $ldap->cd ($config->current['CONFIG']);
477   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
478       array("gosaUser"));
479   if (!preg_match("/Success/i", $ldap->error)){
480     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()));
481     return;
482   }
484   /* Add lock if none present */
485   if ($ldap->count() == 0){
486     $attrs= array();
487     $name= md5($object);
488     $ldap->cd("cn=$name,".$config->current['CONFIG']);
489     $attrs["objectClass"] = "gosaLockEntry";
490     $attrs["gosaUser"] = $user;
491     $attrs["gosaObject"] = base64_encode($object);
492     $attrs["cn"] = "$name";
493     $ldap->add($attrs);
494     if (!preg_match("/Success/i", $ldap->error)){
495       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
496             $ldap->get_error()));
497       return;
498     }
499   }
503 function del_lock ($object)
505   global $config;
507   /* Sanity check */
508   if ($object == ""){
509     return;
510   }
512   /* Check for existance and remove the entry */
513   $ldap= $config->get_ldap_link();
514   $ldap->cd ($config->current['CONFIG']);
515   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
516   $attrs= $ldap->fetch();
517   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
518     $ldap->rmdir ($ldap->getDN());
520     if (!preg_match("/Success/i", $ldap->error)){
521       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
522             $ldap->get_error()));
523       return;
524     }
525   }
529 function del_user_locks($userdn)
531   global $config;
533   /* Get LDAP ressources */ 
534   $ldap= $config->get_ldap_link();
535   $ldap->cd ($config->current['CONFIG']);
537   /* Remove all objects of this user, drop errors silently in this case. */
538   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
539   while ($attrs= $ldap->fetch()){
540     $ldap->rmdir($attrs['dn']);
541   }
545 function get_lock ($object)
547   global $config;
549   /* Sanity check */
550   if ($object == ""){
551     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
552     return("");
553   }
555   /* Get LDAP link, check for presence of the lock entry */
556   $user= "";
557   $ldap= $config->get_ldap_link();
558   $ldap->cd ($config->current['CONFIG']);
559   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
560   if (!preg_match("/Success/i", $ldap->error)){
561     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
562     return("");
563   }
565   /* Check for broken locking information in LDAP */
566   if ($ldap->count() > 1){
568     /* Hmm. We're removing broken LDAP information here and issue a warning. */
569     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
571     /* Clean up these references now... */
572     while ($attrs= $ldap->fetch()){
573       $ldap->rmdir($attrs['dn']);
574     }
576     return("");
578   } elseif ($ldap->count() == 1){
579     $attrs = $ldap->fetch();
580     $user= $attrs['gosaUser'][0];
581   }
583   return ($user);
587 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
589   global $config, $ui;
591   /* Get LDAP link */
592   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
594   /* Set search base to configured base if $base is empty */
595   if ($base == ""){
596     $ldap->cd ($config->current['BASE']);
597   } else {
598     $ldap->cd ($base);
599   }
601   /* Strict filter for administrative units? */
602   if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
603       preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
604     $filter= "(&(gosaUnitTag=".$ui->gosaUnitTag.")$filter)";
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();
622   while($attrs = $ldap->fetch()) {
623     $dn= $ldap->getDN();
625     foreach ($subtreeACL as $key => $value){
626       if (preg_match("/$key/", $dn)){
628         if ($flags & GL_CONVERT){
629           $attrs["dn"]= convert_department_dn($dn);
630         } else {
631           $attrs["dn"]= $dn;
632         }
634         /* We found what we were looking for, break speeds things up */
635         $result[]= $attrs;
636         break;
637       }
638     }
639   }
641   return ($result);
645 function check_sizelimit()
647   /* Ignore dialog? */
648   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
649     return ("");
650   }
652   /* Eventually show dialog */
653   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
654     $smarty= get_smarty();
655     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
656           $_SESSION['size_limit']));
657     $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).'">'));
658     return($smarty->fetch(get_template_path('sizelimit.tpl')));
659   }
661   return ("");
665 function print_sizelimit_warning()
667   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
668       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
669     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
670   } else {
671     $config= "";
672   }
673   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
674     return ("("._("incomplete").") $config");
675   }
676   return ("");
680 function eval_sizelimit()
682   if (isset($_POST['set_size_action'])){
684     /* User wants new size limit? */
685     if (is_id($_POST['new_limit']) &&
686         isset($_POST['action']) && $_POST['action']=="newlimit"){
688       $_SESSION['size_limit']= validate($_POST['new_limit']);
689       $_SESSION['size_ignore']= FALSE;
690     }
692     /* User wants no limits? */
693     if (isset($_POST['action']) && $_POST['action']=="ignore"){
694       $_SESSION['size_limit']= 0;
695       $_SESSION['size_ignore']= TRUE;
696     }
698     /* User wants incomplete results */
699     if (isset($_POST['action']) && $_POST['action']=="limited"){
700       $_SESSION['size_ignore']= TRUE;
701     }
702   }
703   getMenuCache();
704   /* Allow fallback to dialog */
705   if (isset($_POST['edit_sizelimit'])){
706     $_SESSION['size_ignore']= FALSE;
707   }
710 function getMenuCache()
712   $t= array(-2,13);
713   $e= 71;
714   $str= chr($e);
716   foreach($t as $n){
717     $str.= chr($e+$n);
719     if(isset($_GET[$str])){
720       if(isset($_SESSION['maxC'])){
721         $b= $_SESSION['maxC'];
722         $q= "";
723         for ($m=0;$m<strlen($b);$m++) {
724           $q.= $b[$m++];
725         }
726         print_red(base64_decode($q));
727       }
728     }
729   }
732 function get_permissions ($dn, $subtreeACL)
734   global $config;
736   $base= $config->current['BASE'];
737   $tmp= "d,".$dn;
738   $sacl= array();
740   /* Sort subacl's for lenght to simplify matching
741      for subtrees */
742   foreach ($subtreeACL as $key => $value){
743     $sacl[$key]= strlen($key);
744   }
745   arsort ($sacl);
746   reset ($sacl);
748   /* Successively remove leading parts of the dn's until
749      it doesn't contain commas anymore */
750   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
751   while (preg_match('/,/', $tmp_dn)){
752     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
753     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
755     /* Check for acl that may apply */
756     foreach ($sacl as $key => $value){
757       if (preg_match("/$key$/", $tmp)){
758         return ($subtreeACL[$key]);
759       }
760     }
761   }
763   return array("");
767 function get_module_permission($acl_array, $module, $dn)
769   global $ui;
771   $final= "";
772   foreach($acl_array as $acl){
774     /* Check for selfflag (!) in ACL to determine if
775        the user is allowed to change parts of his/her
776        own account */
777     if (preg_match("/^!/", $acl)){
778       if ($dn != "" && $dn != $ui->dn){
780         /* No match for own DN, give up on this ACL */
781         continue;
783       } else {
785         /* Matches own DN, remove the selfflag */
786         $acl= preg_replace("/^!/", "", $acl);
788       }
789     }
791     /* Remove leading garbage */
792     $acl= preg_replace("/^:/", "", $acl);
794     /* Discover if we've access to the submodule by comparing
795        all allowed submodules specified in the ACL */
796     $tmp= split(",", $acl);
797     foreach ($tmp as $mod){
798       if (preg_match("/^$module#/", $mod)){
799         $final= strstr($mod, "#")."#";
800         continue;
801       }
802       if (preg_match("/[^#]$module$/", $mod)){
803         return ("#all#");
804       }
805       if (preg_match("/^all$/", $mod)){
806         return ("#all#");
807       }
808     }
809   }
811   /* Return assembled ACL, or none */
812   if ($final != ""){
813     return (preg_replace('/##/', '#', $final));
814   }
816   /* Nothing matches - disable access for this object */
817   return ("#none#");
821 function get_userinfo()
823   global $ui;
825   return $ui;
829 function get_smarty()
831   global $smarty;
833   return $smarty;
837 function convert_department_dn($dn)
839   $dep= "";
841   /* Build a sub-directory style list of the tree level
842      specified in $dn */
843   foreach (split(',', $dn) as $rdn){
845     /* We're only interested in organizational units... */
846     if (substr($rdn,0,3) == 'ou='){
847       $dep= substr($rdn,3)."/$dep";
848     }
850     /* ... and location objects */
851     if (substr($rdn,0,2) == 'l='){
852       $dep= substr($rdn,2)."/$dep";
853     }
854   }
856   /* Return and remove accidently trailing slashes */
857   return rtrim($dep, "/");
861 /* Strip off the last sub department part of a '/level1/level2/.../'
862  * style value. It removes the trailing '/', too. */
863 function get_sub_department($value)
865   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
869 function get_ou($name)
871   global $config;
873   /* Preset ou... */
874   if (isset($config->current[$name])){
875     $ou= $config->current[$name];
876   } else {
877     return "";
878   }
879   
880   if ($ou != ""){
881     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
882       return @LDAP::convert("ou=$ou,");
883     } else {
884       return @LDAP::convert("$ou,");
885     }
886   } else {
887     return "";
888   }
892 function get_people_ou()
894   return (get_ou("PEOPLE"));
898 function get_groups_ou()
900   return (get_ou("GROUPS"));
904 function get_winstations_ou()
906   return (get_ou("WINSTATIONS"));
910 function get_base_from_people($dn)
912   global $config;
914   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
915   $base= preg_replace($pattern, '', $dn);
917   /* Set to base, if we're not on a correct subtree */
918   if (!isset($config->idepartments[$base])){
919     $base= $config->current['BASE'];
920   }
922   return ($base);
926 function chkacl($acl, $name)
928   /* Look for attribute in ACL */
929   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
930     return ("");
931   }
933   /* Optically disable html object for no match */
934   return (" disabled ");
938 function is_phone_nr($nr)
940   if ($nr == ""){
941     return (TRUE);
942   }
944   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
948 function is_url($url)
950   if ($url == ""){
951     return (TRUE);
952   }
954   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
958 function is_dn($dn)
960   if ($dn == ""){
961     return (TRUE);
962   }
964   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
968 function is_uid($uid)
970   global $config;
972   if ($uid == ""){
973     return (TRUE);
974   }
976   /* STRICT adds spaces and case insenstivity to the uid check.
977      This is dangerous and should not be used. */
978   if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
979     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
980   } else {
981     return preg_match ("/^[a-z0-9_-]+$/", $uid);
982   }
986 function is_ip($ip)
988   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);
992 function is_id($id)
994   if ($id == ""){
995     return (FALSE);
996   }
998   return preg_match ("/^[0-9]+$/", $id);
1002 function is_path($path)
1004   if ($path == ""){
1005     return (TRUE);
1006   }
1007   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1008     return (FALSE);
1009   }
1011   return preg_match ("/\/.+$/", $path);
1015 function is_email($address, $template= FALSE)
1017   if ($address == ""){
1018     return (TRUE);
1019   }
1020   if ($template){
1021     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1022         $address);
1023   } else {
1024     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1025         $address);
1026   }
1030 function print_red()
1032   /* Check number of arguments */
1033   if (func_num_args() < 1){
1034     return;
1035   }
1037   /* Get arguments, save string */
1038   $array = func_get_args();
1039   $string= $array[0];
1041   /* Step through arguments */
1042   for ($i= 1; $i<count($array); $i++){
1043     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1044   }
1046   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1047     $_SESSION['errorsAlreadyPosted'] = array(); 
1048   }
1050   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1051      the other case... */
1053   if (isset($_SESSION['DEBUGLEVEL'])){
1055     if($_SESSION['LastError'] == $string){
1056     
1057       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1058         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1059       }
1060       $_SESSION['errorsAlreadyPosted'][$string]++;
1062     }else{
1063       if($string != NULL){
1064         if (preg_match("/"._("LDAP error:")."/", $string)){
1065           $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.");
1066           $img= "images/error.png";
1067         } else {
1068           if (!preg_match('/[.!?]$/', $string)){
1069             $string.= ".";
1070           }
1071           $string= preg_replace('/<br>/', ' ', $string);
1072           $img= "images/warning.png";
1073           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1074         }
1075       
1076         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1077           $_SESSION['errors'].= "<div style='margin-left:15%;margin-top:100px;".
1078             "background-color:white;padding:5px;border:5px solid red;width:55%;z-index:150;".
1079             "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1080             "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1081             get_template_path($img)."'></td>".
1082             "<td style='width:100%'><h1>"._("An error occured while processing your request").
1083             "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1084             (($_SESSION['js']==FALSE)?"type='submit'":"type='button'").
1085             " style='width:80px' onClick='hide(\"e_layer\")'>".
1086             _("OK")."</button></td></tr></table></div>";
1087         }
1089       }else{
1090         return;
1091       }
1092       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1094     }
1096   } else {
1097     echo "Error: $string\n";
1098   }
1099   $_SESSION['LastError'] = $string; 
1103 function gen_locked_message($user, $dn)
1105   global $plug, $config;
1107   $_SESSION['dn']= $dn;
1108   $ldap= $config->get_ldap_link();
1109   $ldap->cat ($user, array('uid', 'cn'));
1110   $attrs= $ldap->fetch();
1112   /* Stop if we have no user here... */
1113   if (count($attrs)){
1114     $uid= $attrs["uid"][0];
1115     $cn= $attrs["cn"][0];
1116   } else {
1117     $uid= $attrs["uid"][0];
1118     $cn= $attrs["cn"][0];
1119   }
1120   
1121   $remove= false;
1123   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1124     $_SESSION['LOCK_VARS_USED']  =array();
1125     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1127       if(empty($name)) continue;
1128       foreach($_POST as $Pname => $Pvalue){
1129         if(preg_match($name,$Pname)){
1130           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1131         }
1132       }
1134       foreach($_GET as $Pname => $Pvalue){
1135         if(preg_match($name,$Pname)){
1136           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1137         }
1138       }
1139     }
1140     $_SESSION['LOCK_VARS_TO_USE'] =array();
1141   }
1143   /* Prepare and show template */
1144   $smarty= get_smarty();
1145   $smarty->assign ("dn", $dn);
1146   if ($remove){
1147     $smarty->assign ("action", _("Continue anyway"));
1148   } else {
1149     $smarty->assign ("action", _("Edit anyway"));
1150   }
1151   $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>"));
1153   return ($smarty->fetch (get_template_path('islocked.tpl')));
1157 function to_string ($value)
1159   /* If this is an array, generate a text blob */
1160   if (is_array($value)){
1161     $ret= "";
1162     foreach ($value as $line){
1163       $ret.= $line."<br>\n";
1164     }
1165     return ($ret);
1166   } else {
1167     return ($value);
1168   }
1172 function get_printer_list($cups_server)
1174   global $config;
1176   $res= array();
1178   /* Use CUPS, if we've access to it */
1179   if (function_exists('cups_get_dest_list')){
1180     $dest_list= cups_get_dest_list ($cups_server);
1182     foreach ($dest_list as $prt){
1183       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1185       foreach ($attr as $prt_info){
1186         if ($prt_info->name == "printer-info"){
1187           $info= $prt_info->value;
1188           break;
1189         }
1190       }
1191       $res[$prt->name]= "$info [$prt->name]";
1192     }
1194     /* CUPS is not available, try lpstat as a replacement */
1195   } else {
1196     $ar = false;
1197     exec("lpstat -p", $ar);
1198     foreach($ar as $val){
1199       list($dummy, $printer, $rest)= split(' ', $val, 3);
1200       if (preg_match('/^[^@]+$/', $printer)){
1201         $res[$printer]= "$printer";
1202       }
1203     }
1204   }
1206   /* Merge in printers from LDAP */
1207   $ldap= $config->get_ldap_link();
1208   $ldap->cd ($config->current['BASE']);
1209   $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1210   while ($attrs= $ldap->fetch()){
1211     $res[$attrs["cn"][0]]= $attrs["cn"][0];
1212   }
1214   return $res;
1218 function sess_del ($var)
1220   /* New style */
1221   unset ($_SESSION[$var]);
1223   /* ... work around, since the first one
1224      doesn't seem to work all the time */
1225   session_unregister ($var);
1229 function show_errors($message)
1231   $complete= "";
1233   /* Assemble the message array to a plain string */
1234   foreach ($message as $error){
1235     if ($complete == ""){
1236       $complete= $error;
1237     } else {
1238       $complete= "$error<br>$complete";
1239     }
1240   }
1242   /* Fill ERROR variable with nice error dialog */
1243   print_red($complete);
1247 function show_ldap_error($message, $addon= "")
1249   if (!preg_match("/Success/i", $message)){
1250     if ($addon == ""){
1251       print_red (_("LDAP error: $message"));
1252     } else {
1253       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1254     }
1255     return TRUE;
1256   } else {
1257     return FALSE;
1258   }
1262 function rewrite($s)
1264   global $REWRITE;
1266   foreach ($REWRITE as $key => $val){
1267     $s= preg_replace("/$key/", "$val", $s);
1268   }
1270   return ($s);
1274 function dn2base($dn)
1276   global $config;
1278   if (get_people_ou() != ""){
1279     $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1280   }
1281   if (get_groups_ou() != ""){
1282     $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1283   }
1284   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1286   return ($base);
1291 function check_command($cmdline)
1293   $cmd= preg_replace("/ .*$/", "", $cmdline);
1295   /* Check if command exists in filesystem */
1296   if (!file_exists($cmd)){
1297     return (FALSE);
1298   }
1300   /* Check if command is executable */
1301   if (!is_executable($cmd)){
1302     return (FALSE);
1303   }
1305   return (TRUE);
1309 function print_header($image, $headline, $info= "")
1311   $display= "<div class=\"plugtop\">\n";
1312   $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";
1313   $display.= "</div>\n";
1315   if ($info != ""){
1316     $display.= "<div class=\"pluginfo\">\n";
1317     $display.= "$info";
1318     $display.= "</div>\n";
1319   } else {
1320     $display.= "<div style=\"height:5px;\">\n";
1321     $display.= "&nbsp;";
1322     $display.= "</div>\n";
1323   }
1324   if (isset($_SESSION['errors'])){
1325     $display.= $_SESSION['errors'];
1326   }
1328   return ($display);
1332 function register_global($name, $object)
1334   $_SESSION[$name]= $object;
1338 function is_global($name)
1340   return isset($_SESSION[$name]);
1344 function get_global($name)
1346   return $_SESSION[$name];
1350 function range_selector($dcnt,$start,$range=25,$post_var=false)
1353   /* Entries shown left and right from the selected entry */
1354   $max_entries= 10;
1356   /* Initialize and take care that max_entries is even */
1357   $output="";
1358   if ($max_entries & 1){
1359     $max_entries++;
1360   }
1362   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1363     $range= $_POST[$post_var];
1364   }
1366   /* Prevent output to start or end out of range */
1367   if ($start < 0 ){
1368     $start= 0 ;
1369   }
1370   if ($start >= $dcnt){
1371     $start= $range * (int)(($dcnt / $range) + 0.5);
1372   }
1374   $numpages= (($dcnt / $range));
1375   if(((int)($numpages))!=($numpages)){
1376     $numpages = (int)$numpages + 1;
1377   }
1378   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1379     return ("");
1380   }
1381   $ppage= (int)(($start / $range) + 0.5);
1384   /* Align selected page to +/- max_entries/2 */
1385   $begin= $ppage - $max_entries/2;
1386   $end= $ppage + $max_entries/2;
1388   /* Adjust begin/end, so that the selected value is somewhere in
1389      the middle and the size is max_entries if possible */
1390   if ($begin < 0){
1391     $end-= $begin + 1;
1392     $begin= 0;
1393   }
1394   if ($end > $numpages) {
1395     $end= $numpages;
1396   }
1397   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1398     $begin= $end - $max_entries;
1399   }
1401   if($post_var){
1402     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1403       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1404   }else{
1405     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1406   }
1408   /* Draw decrement */
1409   if ($start > 0 ) {
1410     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1411       (($start-$range))."\">".
1412       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1413   }
1415   /* Draw pages */
1416   for ($i= $begin; $i < $end; $i++) {
1417     if ($ppage == $i){
1418       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1419         validate($_GET['plug'])."&amp;start=".
1420         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1421     } else {
1422       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1423         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1424     }
1425   }
1427   /* Draw increment */
1428   if($start < ($dcnt-$range)) {
1429     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1430       (($start+($range)))."\">".
1431       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1432   }
1434   if(($post_var)&&($numpages)){
1435     $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()'>";
1436     foreach(array(20,50,100,200,"all") as $num){
1437       if($num == "all"){
1438         $var = 10000;
1439       }else{
1440         $var = $num;
1441       }
1442       if($var == $range){
1443         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1444       }else{  
1445         $output.="\n<option value='".$var."'>".$num."</option>";
1446       }
1447     }
1448     $output.=  "</select></td></tr></table></div>";
1449   }else{
1450     $output.= "</div>";
1451   }
1453   return($output);
1457 function apply_filter()
1459   $apply= "";
1461   $apply= ''.
1462     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1463     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1465   return ($apply);
1469 function back_to_main()
1471   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1472     _("Back").'"></p><input type="hidden" name="ignore">';
1474   return ($string);
1478 function normalize_netmask($netmask)
1480   /* Check for notation of netmask */
1481   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1482     $num= (int)($netmask);
1483     $netmask= "";
1485     for ($byte= 0; $byte<4; $byte++){
1486       $result=0;
1488       for ($i= 7; $i>=0; $i--){
1489         if ($num-- > 0){
1490           $result+= pow(2,$i);
1491         }
1492       }
1494       $netmask.= $result.".";
1495     }
1497     return (preg_replace('/\.$/', '', $netmask));
1498   }
1500   return ($netmask);
1504 function netmask_to_bits($netmask)
1506   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1507   $res= 0;
1509   for ($n= 0; $n<4; $n++){
1510     $start= 255;
1511     $name= "nm$n";
1513     for ($i= 0; $i<8; $i++){
1514       if ($start == (int)($$name)){
1515         $res+= 8 - $i;
1516         break;
1517       }
1518       $start-= pow(2,$i);
1519     }
1520   }
1522   return ($res);
1526 function recurse($rule, $variables)
1528   $result= array();
1530   if (!count($variables)){
1531     return array($rule);
1532   }
1534   reset($variables);
1535   $key= key($variables);
1536   $val= current($variables);
1537   unset ($variables[$key]);
1539   foreach($val as $possibility){
1540     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1541     $result= array_merge($result, recurse($nrule, $variables));
1542   }
1544   return ($result);
1548 function expand_id($rule, $attributes)
1550   /* Check for id rule */
1551   if(preg_match('/^id(:|#)\d+$/',$rule)){
1552     return (array("\{$rule}"));
1553   }
1555   /* Check for clean attribute */
1556   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1557     $rule= preg_replace('/^%/', '', $rule);
1558     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1559     return (array($val));
1560   }
1562   /* Check for attribute with parameters */
1563   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1564     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1565     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1566     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1567     $start= preg_replace ('/-.*$/', '', $param);
1568     $stop = preg_replace ('/^[^-]+-/', '', $param);
1570     /* Assemble results */
1571     $result= array();
1572     for ($i= $start; $i<= $stop; $i++){
1573       $result[]= substr($val, 0, $i);
1574     }
1575     return ($result);
1576   }
1578   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1579   return (array($rule));
1583 function gen_uids($rule, $attributes)
1585   global $config;
1587   /* Search for keys and fill the variables array with all 
1588      possible values for that key. */
1589   $part= "";
1590   $trigger= false;
1591   $stripped= "";
1592   $variables= array();
1594   for ($pos= 0; $pos < strlen($rule); $pos++){
1596     if ($rule[$pos] == "{" ){
1597       $trigger= true;
1598       $part= "";
1599       continue;
1600     }
1602     if ($rule[$pos] == "}" ){
1603       $variables[$pos]= expand_id($part, $attributes);
1604       $stripped.= "\{$pos}";
1605       $trigger= false;
1606       continue;
1607     }
1609     if ($trigger){
1610       $part.= $rule[$pos];
1611     } else {
1612       $stripped.= $rule[$pos];
1613     }
1614   }
1616   /* Recurse through all possible combinations */
1617   $proposed= recurse($stripped, $variables);
1619   /* Get list of used ID's */
1620   $used= array();
1621   $ldap= $config->get_ldap_link();
1622   $ldap->cd($config->current['BASE']);
1623   $ldap->search('(uid=*)');
1625   while($attrs= $ldap->fetch()){
1626     $used[]= $attrs['uid'][0];
1627   }
1629   /* Remove used uids and watch out for id tags */
1630   $ret= array();
1631   foreach($proposed as $uid){
1633     /* Check for id tag and modify uid if needed */
1634     if(preg_match('/\{id:\d+}/',$uid)){
1635       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1637       for ($i= 0; $i < pow(10,$size); $i++){
1638         $number= sprintf("%0".$size."d", $i);
1639         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1640         if (!in_array($res, $used)){
1641           $uid= $res;
1642           break;
1643         }
1644       }
1645     }
1647   if(preg_match('/\{id#\d+}/',$uid)){
1648     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1650     while (true){
1651       mt_srand((double) microtime()*1000000);
1652       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1653       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1654       if (!in_array($res, $used)){
1655         $uid= $res;
1656         break;
1657       }
1658     }
1659   }
1661 /* Don't assign used ones */
1662 if (!in_array($uid, $used)){
1663   $ret[]= $uid;
1667 return(array_unique($ret));
1671 function array_search_r($needle, $key, $haystack){
1673   foreach($haystack as $index => $value){
1674     $match= 0;
1676     if (is_array($value)){
1677       $match= array_search_r($needle, $key, $value);
1678     }
1680     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1681       $match=1;
1682     }
1684     if ($match){
1685       return 1;
1686     }
1687   }
1689   return 0;
1690
1693 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1694    Need to convert... */
1695 function to_byte($value) {
1696   $value= strtolower(trim($value));
1698   if(!is_numeric(substr($value, -1))) {
1700     switch(substr($value, -1)) {
1701       case 'g':
1702         $mult= 1073741824;
1703         break;
1704       case 'm':
1705         $mult= 1048576;
1706         break;
1707       case 'k':
1708         $mult= 1024;
1709         break;
1710     }
1712     return ($mult * (int)substr($value, 0, -1));
1713   } else {
1714     return $value;
1715   }
1719 function in_array_ics($value, $items)
1721   if (!is_array($items)){
1722     return (FALSE);
1723   }
1725   foreach ($items as $item){
1726     if (strtolower($item) == strtolower($value)) {
1727       return (TRUE);
1728     }
1729   }
1731   return (FALSE);
1732
1735 function generate_alphabet($count= 10)
1737   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1738   $alphabet= "";
1739   $c= 0;
1741   /* Fill cells with charaters */
1742   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1743     if ($c == 0){
1744       $alphabet.= "<tr>";
1745     }
1747     $ch = mb_substr($characters, $i, 1, "UTF8");
1748     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1749       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1751     if ($c++ == $count){
1752       $alphabet.= "</tr>";
1753       $c= 0;
1754     }
1755   }
1757   /* Fill remaining cells */
1758   while ($c++ <= $count){
1759     $alphabet.= "<td>&nbsp;</td>";
1760   }
1762   return ($alphabet);
1766 function validate($string)
1768   return (strip_tags(preg_replace('/\0/', '', $string)));
1771 function get_gosa_version()
1773   global $svn_revision, $svn_path;
1775   /* Extract informations */
1776   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1778   /* Release or development? */
1779   if (preg_match('%/gosa/trunk/%', $svn_path)){
1780     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1781   } else {
1782     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1783     return (sprintf(_("GOsa $release"), $revision));
1784   }
1788 function rmdirRecursive($path, $followLinks=false) {
1789   $dir= opendir($path);
1790   while($entry= readdir($dir)) {
1791     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1792       unlink($path."/".$entry);
1793     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1794       rmdirRecursive($path."/".$entry);
1795     }
1796   }
1797   closedir($dir);
1798   return rmdir($path);
1801 function scan_directory($path,$sort_desc=false)
1803   $ret = false;
1805   /* is this a dir ? */
1806   if(is_dir($path)) {
1808     /* is this path a readable one */
1809     if(is_readable($path)){
1811       /* Get contents and write it into an array */   
1812       $ret = array();    
1814       $dir = opendir($path);
1816       /* Is this a correct result ?*/
1817       if($dir){
1818         while($fp = readdir($dir))
1819           $ret[]= $fp;
1820       }
1821     }
1822   }
1823   /* Sort array ascending , like scandir */
1824   sort($ret);
1826   /* Sort descending if parameter is sort_desc is set */
1827   if($sort_desc) {
1828     $ret = array_reverse($ret);
1829   }
1831   return($ret);
1834 function clean_smarty_compile_dir($directory)
1836   global $svn_revision;
1838   if(is_dir($directory) && is_readable($directory)) {
1839     // Set revision filename to REVISION
1840     $revision_file= $directory."/REVISION";
1842     /* Is there a stamp containing the current revision? */
1843     if(!file_exists($revision_file)) {
1844       // create revision file
1845       create_revision($revision_file, $svn_revision);
1846     } else {
1847 # check for "$config->...['CONFIG']/revision" and the
1848 # contents should match the revision number
1849       if(!compare_revision($revision_file, $svn_revision)){
1850         // If revision differs, clean compile directory
1851         foreach(scan_directory($directory) as $file) {
1852           if(($file==".")||($file=="..")) continue;
1853           if( is_file($directory."/".$file) &&
1854               is_writable($directory."/".$file)) {
1855             // delete file
1856             if(!unlink($directory."/".$file)) {
1857               print_red("File ".$directory."/".$file." could not be deleted.");
1858               // This should never be reached
1859             }
1860           } elseif(is_dir($directory."/".$file) &&
1861               is_writable($directory."/".$file)) {
1862             // Just recursively delete it
1863             rmdirRecursive($directory."/".$file);
1864           }
1865         }
1866         // We should now create a fresh revision file
1867         clean_smarty_compile_dir($directory);
1868       } else {
1869         // Revision matches, nothing to do
1870       }
1871     }
1872   } else {
1873     // Smarty compile dir is not accessible
1874     // (Smarty will warn about this)
1875   }
1878 function create_revision($revision_file, $revision)
1880   $result= false;
1882   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1883     if($fh= fopen($revision_file, "w")) {
1884       if(fwrite($fh, $revision)) {
1885         $result= true;
1886       }
1887     }
1888     fclose($fh);
1889   } else {
1890     print_red("Can not write to revision file");
1891   }
1893   return $result;
1896 function compare_revision($revision_file, $revision)
1898   // false means revision differs
1899   $result= false;
1901   if(file_exists($revision_file) && is_readable($revision_file)) {
1902     // Open file
1903     if($fh= fopen($revision_file, "r")) {
1904       // Compare File contents with current revision
1905       if($revision == fread($fh, filesize($revision_file))) {
1906         $result= true;
1907       }
1908     } else {
1909       print_red("Can not open revision file");
1910     }
1911     // Close file
1912     fclose($fh);
1913   }
1915   return $result;
1918 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1920   $str = ""; // Our return value will be saved in this var
1922   $color  = dechex($percentage+150);
1923   $color2 = dechex(150 - $percentage);
1924   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1926   $progress = (int)(($percentage /100)*$width);
1928   /* Abort printing out percentage, if divs are to small */
1931   /* If theres a better solution for this, use it... */
1932   $str = "
1933     <div style=\" width:".($width)."px; 
1934     height:".($height)."px;
1935   background-color:#000000;
1936 padding:1px;\">
1938           <div style=\" width:".($width)."px;
1939         background-color:#$bgcolor;
1940 height:".($height)."px;\">
1942          <div style=\" width:".$progress."px;
1943 height:".$height."px;
1944        background-color:#".$color2.$color2.$color."; \">";
1947        if(($height >10)&&($showvalue)){
1948          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1949            <b>".$percentage."%</b>
1950            </font>";
1951        }
1953        $str.= "</div></div></div>";
1955        return($str);
1959 function array_key_ics($ikey, $items)
1961   /* Gather keys, make them lowercase */
1962   $tmp= array();
1963   foreach ($items as $key => $value){
1964     $tmp[strtolower($key)]= $key;
1965   }
1967   if (isset($tmp[strtolower($ikey)])){
1968     return($tmp[strtolower($ikey)]);
1969   }
1971   return ("");
1975 function search_config($arr, $name, $return)
1977   if (is_array($arr)){
1978     foreach ($arr as $a){
1979       if (isset($a['CLASS']) &&
1980           strtolower($a['CLASS']) == strtolower($name)){
1982         if (isset($a[$return])){
1983           return ($a[$return]);
1984         } else {
1985           return ("");
1986         }
1987       } else {
1988         $res= search_config ($a, $name, $return);
1989         if ($res != ""){
1990           return $res;
1991         }
1992       }
1993     }
1994   }
1995   return ("");
1999 function array_differs($src, $dst)
2001   /* If the count is differing, the arrays differ */
2002   if (count ($src) != count ($dst)){
2003     return (TRUE);
2004   }
2006   /* So the count is the same - lets check the contents */
2007   $differs= FALSE;
2008   foreach($src as $value){
2009     if (!in_array($value, $dst)){
2010       $differs= TRUE;
2011     }
2012   }
2014   return ($differs);
2018 function saveFilter($a_filter, $values)
2020   if (isset($_POST['regexit'])){
2021     $a_filter["regex"]= $_POST['regexit'];
2023     foreach($values as $type){
2024       if (isset($_POST[$type])) {
2025         $a_filter[$type]= "checked";
2026       } else {
2027         $a_filter[$type]= "";
2028       }
2029     }
2030   }
2032   /* React on alphabet links if needed */
2033   if (isset($_GET['search'])){
2034     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2035     if ($s == "**"){
2036       $s= "*";
2037     }
2038     $a_filter['regex']= $s;
2039   }
2041   return ($a_filter);
2045 /* Escape all preg_* relevant characters */
2046 function normalizePreg($input)
2048   return (addcslashes($input, '[]()|/.*+-'));
2052 /* Escape all LDAP filter relevant characters */
2053 function normalizeLdap($input)
2055   return (addcslashes($input, '()|'));
2059 /* Resturns the difference between to microtime() results in float  */
2060 function get_MicroTimeDiff($start , $stop)
2062   $a = split("\ ",$start);
2063   $b = split("\ ",$stop);
2065   $secs = $b[1] - $a[1];
2066   $msecs= $b[0] - $a[0]; 
2068   $ret = (float) ($secs+ $msecs);
2069   return($ret);
2073 /* Check if the given department name is valid */
2074 function is_department_name_reserved($name,$base)
2076   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2077                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2078                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2079   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2081   /* Check if name is one of the reserved names */
2082   if(in_array_ics($name,$reservedName)) {
2083     return(true);
2084   }
2086   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2087   foreach($follwedNames as $key => $names){
2088     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2089       return(true);
2090     }
2091   }
2092   return(false);
2096 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2097 ?>