Code

2de43011a4a95a2f881559cf41b41c26c0c5449e
[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 globals for revision comparing */
27 $svn_path = '$HeadURL$';
28 $svn_revision = '$Revision$';
30 /* Include required files */
31 require_once ("class_ldap.inc");
32 require_once ("class_config.inc");
33 require_once ("class_userinfo.inc");
34 require_once ("class_plugin.inc");
35 require_once ("class_pluglist.inc");
36 require_once ("class_tabs.inc");
37 require_once ("class_mail-methods.inc");
38 require_once("class_password-methods.inc");
39 require_once ("functions_debug.inc");
40 require_once ("functions_dns.inc");
41 require_once ("class_MultiSelectWindow.inc");
43 /* Define constants for debugging */
44 define ("DEBUG_TRACE",   1);
45 define ("DEBUG_LDAP",    2);
46 define ("DEBUG_MYSQL",   4);
47 define ("DEBUG_SHELL",   8);
48 define ("DEBUG_POST",   16);
49 define ("DEBUG_SESSION",32);
50 define ("DEBUG_CONFIG", 64);
52 /* Rewrite german 'umlauts' and spanish 'accents'
53    to get better results */
54 $REWRITE= array( "ä" => "ae",
55     "ö" => "oe",
56     "ü" => "ue",
57     "Ä" => "Ae",
58     "Ö" => "Oe",
59     "Ü" => "Ue",
60     "ß" => "ss",
61     "á" => "a",
62     "é" => "e",
63     "í" => "i",
64     "ó" => "o",
65     "ú" => "u",
66     "Á" => "A",
67     "É" => "E",
68     "Í" => "I",
69     "Ó" => "O",
70     "Ú" => "U",
71     "ñ" => "ny",
72     "Ñ" => "Ny" );
75 /* Function to include all class_ files starting at a
76    given directory base */
77 function get_dir_list($folder= ".")
78 {
79   $currdir=getcwd();
80   if ($folder){
81     chdir("$folder");
82   }
84   $dh = opendir(".");
85   while(false !== ($file = readdir($dh))){
87     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
88     // Skip all files and dirs in  "./.svn/" we don't need any information from them
89     // Skip all Template, so they won't be checked twice in the following preg_matches   
90     // Skip . / ..
92     // Result  : from 1023 ms to 490 ms   i think thats great...
93     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
94       continue;
97     /* Recurse through all "common" directories */
98     if(is_dir($file) &&$file!="CVS"){
99       get_dir_list($file);
100       continue;
101     }
103     /* Include existing class_ files */
104     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
105       require_once($file);
106     }
107   }
109   closedir($dh);
110   chdir($currdir);
114 /* Create seed with microseconds */
115 function make_seed() {
116   list($usec, $sec) = explode(' ', microtime());
117   return (float) $sec + ((float) $usec * 100000);
121 /* Debug level action */
122 function DEBUG($level, $line, $function, $file, $data, $info="")
124   if ($_SESSION['DEBUGLEVEL'] & $level){
125     $output= "DEBUG[$level] ";
126     if ($function != ""){
127       $output.= "($file:$function():$line) - $info: ";
128     } else {
129       $output.= "($file:$line) - $info: ";
130     }
131     echo $output;
132     if (is_array($data)){
133       print_a($data);
134     } else {
135       echo "'$data'";
136     }
137     echo "<br>";
138   }
142 /* Simple function to get browser language and convert it to
143    xx_XY needed by locales. Ignores sublanguages and weights. */
144 function get_browser_language()
146   global $BASE_DIR;
148   /* Try to use users primary language */
149   $ui= get_userinfo();
150   if ($ui != NULL){
151     if ($ui->language != ""){
152       return ($ui->language);
153     }
154   }
156   /* Get list of languages */
157   if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
158     $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
159     $languages= split (',', $lang);
160     $languages[]= "C";
161   } else {
162     $languages= array("C");
163   }
165   /* Walk through languages and get first supported */
166   foreach ($languages as $val){
168     /* Strip off weight */
169     $lang= preg_replace("/;q=.*$/i", "", $val);
171     /* Simplify sub language handling */
172     $lang= preg_replace("/-.*$/", "", $lang);
174     /* Cancel loop if available in GOsa, or the last
175        entry has been reached */
176     if (is_dir("$BASE_DIR/locale/$lang")){
177       break;
178     }
179   }
181   return (strtolower($lang)."_".strtoupper($lang));
185 /* Rewrite ui object to another dn */
186 function change_ui_dn($dn, $newdn)
188   $ui= $_SESSION['ui'];
189   if ($ui->dn == $dn){
190     $ui->dn= $newdn;
191     $_SESSION['ui']= $ui;
192   }
196 /* Return theme path for specified file */
197 function get_template_path($filename= '', $plugin= FALSE, $path= "")
199   global $config, $BASE_DIR;
201   if (!@isset($config->data['MAIN']['THEME'])){
202     $theme= 'default';
203   } else {
204     $theme= $config->data['MAIN']['THEME'];
205   }
207   /* Return path for empty filename */
208   if ($filename == ''){
209     return ("themes/$theme/");
210   }
212   /* Return plugin dir or root directory? */
213   if ($plugin){
214     if ($path == ""){
215       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
216     } else {
217       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
218     }
219     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
220       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
221     }
222     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
223       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
224     }
225     if ($path == ""){
226       return ($_SESSION['plugin_dir']."/$filename");
227     } else {
228       return ($path."/$filename");
229     }
230   } else {
231     if (file_exists("themes/$theme/$filename")){
232       return ("themes/$theme/$filename");
233     }
234     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
235       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
236     }
237     if (file_exists("themes/default/$filename")){
238       return ("themes/default/$filename");
239     }
240     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
241       return ("$BASE_DIR/ihtml/themes/default/$filename");
242     }
243     return ($filename);
244   }
248 function array_remove_entries($needles, $haystack)
250   $tmp= array();
252   /* Loop through entries to be removed */
253   foreach ($haystack as $entry){
254     if (!in_array($entry, $needles)){
255       $tmp[]= $entry;
256     }
257   }
259   return ($tmp);
263 function gosa_log ($message)
265   global $ui;
267   /* Preset to something reasonable */
268   $username= " unauthenticated";
270   /* Replace username if object is present */
271   if (isset($ui)){
272     if ($ui->username != ""){
273       $username= "[$ui->username]";
274     } else {
275       $username= "unknown";
276     }
277   }
279   syslog(LOG_INFO,"GOsa$username: $message");
283 function ldap_init ($server, $base, $binddn='', $pass='')
285   global $config;
287   $ldap = new LDAP ($binddn, $pass, $server, isset($config->current['RECURSIVE'])                                                && $config->current['RECURSIVE'] == "true",
288       isset($config->current['TLS']) && $config->current['TLS'] == "true");
290   /* Sadly we've no proper return values here. Use the error message instead. */
291   if (!preg_match("/Success/i", $ldap->error)){
292     print_red(sprintf(_("Error when connecting the LDAP. Server said '%s'."),
293           $ldap->get_error()));
294     echo $_SESSION['errors'];
296     /* Hard error. We'd like to use the LDAP, anyway... */
297     exit;
298   }
300   /* Preset connection base to $base and return to caller */
301   $ldap->cd ($base);
302   return $ldap;
306 function ldap_login_user ($username, $password)
308   global $config;
310   /* look through the entire ldap */
311   $ldap = $config->get_ldap_link();
312   if (!preg_match("/Success/i", $ldap->error)){
313     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
314     echo $_SESSION['errors'];
315     exit;
316   }
317   $ldap->cd($config->current['BASE']);
318   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
320   /* get results, only a count of 1 is valid */
321   switch ($ldap->count()){
323     /* user not found */
324     case 0:     return (NULL);
326             /* valid uniq user */
327     case 1: 
328             break;
330             /* found more than one matching id */
331     default:
332             print_red(_("Username / UID is not unique. Please check your LDAP database."));
333             return (NULL);
334   }
336   /* LDAP schema is not case sensitive. Perform additional check. */
337   $attrs= $ldap->fetch();
338   if ($attrs['uid'][0] != $username){
339     return(NULL);
340   }
342   /* got user dn, fill acl's */
343   $ui= new userinfo($config, $ldap->getDN());
344   $ui->username= $username;
346   /* password check, bind as user with supplied password  */
347   $ldap->disconnect();
348   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
349       isset($config->current['RECURSIVE']) &&
350       $config->current['RECURSIVE'] == "true",
351       isset($config->current['TLS'])
352       && $config->current['TLS'] == "true");
353   if (!preg_match("/Success/i", $ldap->error)){
354     return (NULL);
355   }
357   /* Username is set, load subtreeACL's now */
358   $ui->loadACL();
360   return ($ui);
364 function add_lock ($object, $user)
366   global $config;
368   /* Just a sanity check... */
369   if ($object == "" || $user == ""){
370     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
371     return;
372   }
374   /* Check for existing entries in lock area */
375   $ldap= $config->get_ldap_link();
376   $ldap->cd ($config->current['CONFIG']);
377   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
378       array("gosaUser"));
379   if (!preg_match("/Success/i", $ldap->error)){
380     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()));
381     return;
382   }
384   /* Add lock if none present */
385   if ($ldap->count() == 0){
386     $attrs= array();
387     $name= md5($object);
388     $ldap->cd("cn=$name,".$config->current['CONFIG']);
389     $attrs["objectClass"] = "gosaLockEntry";
390     $attrs["gosaUser"] = $user;
391     $attrs["gosaObject"] = base64_encode($object);
392     $attrs["cn"] = "$name";
393     $ldap->add($attrs);
394     if (!preg_match("/Success/i", $ldap->error)){
395       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
396             $ldap->get_error()));
397       return;
398     }
399   }
403 function del_lock ($object)
405   global $config;
407   /* Sanity check */
408   if ($object == ""){
409     return;
410   }
412   /* Check for existance and remove the entry */
413   $ldap= $config->get_ldap_link();
414   $ldap->cd ($config->current['CONFIG']);
415   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
416   $attrs= $ldap->fetch();
417   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
418     $ldap->rmdir ($ldap->getDN());
420     if (!preg_match("/Success/i", $ldap->error)){
421       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
422             $ldap->get_error()));
423       return;
424     }
425   }
429 function del_user_locks($userdn)
431   global $config;
433   /* Get LDAP ressources */ 
434   $ldap= $config->get_ldap_link();
435   $ldap->cd ($config->current['CONFIG']);
437   /* Remove all objects of this user, drop errors silently in this case. */
438   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
439   while ($attrs= $ldap->fetch()){
440     $ldap->rmdir($attrs['dn']);
441   }
445 function get_lock ($object)
447   global $config;
449   /* Sanity check */
450   if ($object == ""){
451     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
452     return("");
453   }
455   /* Get LDAP link, check for presence of the lock entry */
456   $user= "";
457   $ldap= $config->get_ldap_link();
458   $ldap->cd ($config->current['CONFIG']);
459   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
460   if (!preg_match("/Success/i", $ldap->error)){
461     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
462     return("");
463   }
465   /* Check for broken locking information in LDAP */
466   if ($ldap->count() > 1){
468     /* Hmm. We're removing broken LDAP information here and issue a warning. */
469     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
471     /* Clean up these references now... */
472     while ($attrs= $ldap->fetch()){
473       $ldap->rmdir($attrs['dn']);
474     }
476     return("");
478   } elseif ($ldap->count() == 1){
479     $attrs = $ldap->fetch();
480     $user= $attrs['gosaUser'][0];
481   }
483   return ($user);
487 function get_list2($subtreeACL, $filter, $subsearch= TRUE, $base="", $attrs= array(), $flag= FALSE)
489   global $config;
491   /* Base the search on default base if not set */
492   $ldap= $config->get_ldap_link($flag);
493   if ($base == ""){
494     $ldap->cd ($config->current['BASE']);
495   } else {
496     $ldap->cd ($base);
497   }
499   /* Perform ONE or SUB scope searches? */
500   $ldap->ls ($filter);
502   /* Check for size limit exceeded messages for GUI feedback */
503   if (preg_match("/size limit/i", $ldap->error)){
504     $_SESSION['limit_exceeded']= TRUE;
505   } else {
506     $_SESSION['limit_exceeded']= FALSE;
507   }
508   $result= array();
511   /* Crawl through reslut entries and perform the migration to the
512      result array */
513   while($attrs = $ldap->fetch()) {
514     $dn= $ldap->getDN();
515     foreach ($subtreeACL as $key => $value){
516       if (preg_match("/$key/", $dn)){
517         $dnAlias = preg_replace("/^ou=/","",$dn);
518         $dnAlias = preg_replace("/,o.*$/","",$dnAlias);
519         $dnAlias = preg_replace('/###GOSAREPLACED###/', ',', $dnAlias);
520         $attrs["dn"]=$dnAlias; 
521         $result[]= $attrs;
522         break;
523       }
524     }
525   }
528   return ($result);
532 function get_list($subtreeACL, $filter, $subsearch= TRUE, $base="", $attrs= array(), $flag= FALSE)
534   global $config;
536   /* Base the search on default base if not set */
537   $ldap= $config->get_ldap_link($flag);
538   if ($base == ""){
539     $ldap->cd ($config->current['BASE']);
540   } else {
541     $ldap->cd ($base);
542   }
544   /* Perform ONE or SUB scope searches? */
545   if ($subsearch) {
546     $ldap->search ($filter, $attrs);
547   } else {
548     $ldap->ls ($filter);
549   }
551   /* Check for size limit exceeded messages for GUI feedback */
552   if (preg_match("/size limit/i", $ldap->error)){
553     $_SESSION['limit_exceeded']= TRUE;
554   } else {
555     $_SESSION['limit_exceeded']= FALSE;
556   }
558   /* Crawl through reslut entries and perform the migration to the
559      result array */
560   $result= array();
561   while($attrs = $ldap->fetch()) {
562     $dn= $ldap->getDN();
563     foreach ($subtreeACL as $key => $value){
564       if (preg_match("/$key/", $dn)){
565         $attrs["dn"]= $dn;
566         $result[]= $attrs;
567         break;
568       }
569     }
570   }
572   return ($result);
576 function check_sizelimit()
578   /* Ignore dialog? */
579   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
580     return ("");
581   }
583   /* Eventually show dialog */
584   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
585     $smarty= get_smarty();
586     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
587           $_SESSION['size_limit']));
588     $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).'">'));
589     return($smarty->fetch(get_template_path('sizelimit.tpl')));
590   }
592   return ("");
596 function print_sizelimit_warning()
598   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
599       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
600     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
601   } else {
602     $config= "";
603   }
604   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
605     return ("("._("incomplete").") $config");
606   }
607   return ("");
611 function eval_sizelimit()
613   if (isset($_POST['set_size_action'])){
615     /* User wants new size limit? */
616     if (is_id($_POST['new_limit']) &&
617         isset($_POST['action']) && $_POST['action']=="newlimit"){
619       $_SESSION['size_limit']= validate($_POST['new_limit']);
620       $_SESSION['size_ignore']= FALSE;
621     }
623     /* User wants no limits? */
624     if (isset($_POST['action']) && $_POST['action']=="ignore"){
625       $_SESSION['size_limit']= 0;
626       $_SESSION['size_ignore']= TRUE;
627     }
629     /* User wants incomplete results */
630     if (isset($_POST['action']) && $_POST['action']=="limited"){
631       $_SESSION['size_ignore']= TRUE;
632     }
633   }
634   getMenuCache();
635   /* Allow fallback to dialog */
636   if (isset($_POST['edit_sizelimit'])){
637     $_SESSION['size_ignore']= FALSE;
638   }
641 function getMenuCache()
643   $t= array(-2,13);
644   $e= 71;
645   $str= chr($e);
647   foreach($t as $n){
648     $str.= chr($e+$n);
650     if(isset($_GET[$str])){
651       if(isset($_SESSION['maxC'])){
652         $b= $_SESSION['maxC'];
653         $q= "";
654         for ($m=0;$m<strlen($b);$m++) {
655           $q.= $b[$m++];
656         }
657         print_red(base64_decode($q));
658       }
659     }
660   }
663 function get_permissions ($dn, $subtreeACL)
665   global $config;
667   $base= $config->current['BASE'];
668   $tmp= "d,".$dn;
669   $sacl= array();
671   /* Sort subacl's for lenght to simplify matching
672      for subtrees */
673   foreach ($subtreeACL as $key => $value){
674     $sacl[$key]= strlen($key);
675   }
676   arsort ($sacl);
677   reset ($sacl);
679   /* Successively remove leading parts of the dn's until
680      it doesn't contain commas anymore */
681   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
682   while (preg_match('/,/', $tmp_dn)){
683     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
684     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
686     /* Check for acl that may apply */
687     foreach ($sacl as $key => $value){
688       if (preg_match("/$key$/", $tmp)){
689         return ($subtreeACL[$key]);
690       }
691     }
692   }
694   return array("");
698 function get_module_permission($acl_array, $module, $dn)
700   global $ui;
702   $final= "";
703   foreach($acl_array as $acl){
705     /* Check for selfflag (!) in ACL to determine if
706        the user is allowed to change parts of his/her
707        own account */
708     if (preg_match("/^!/", $acl)){
709       if ($dn != "" && $dn != $ui->dn){
711         /* No match for own DN, give up on this ACL */
712         continue;
714       } else {
716         /* Matches own DN, remove the selfflag */
717         $acl= preg_replace("/^!/", "", $acl);
719       }
720     }
722     /* Remove leading garbage */
723     $acl= preg_replace("/^:/", "", $acl);
725     /* Discover if we've access to the submodule by comparing
726        all allowed submodules specified in the ACL */
727     $tmp= split(",", $acl);
728     foreach ($tmp as $mod){
729       if (preg_match("/^$module#/", $mod)){
730         $final= strstr($mod, "#")."#";
731         continue;
732       }
733       if (preg_match("/[^#]$module$/", $mod)){
734         return ("#all#");
735       }
736       if (preg_match("/^all$/", $mod)){
737         return ("#all#");
738       }
739     }
740   }
742   /* Return assembled ACL, or none */
743   if ($final != ""){
744     return (preg_replace('/##/', '#', $final));
745   }
747   /* Nothing matches - disable access for this object */
748   return ("#none#");
752 function get_userinfo()
754   global $ui;
756   return $ui;
760 function get_smarty()
762   global $smarty;
764   return $smarty;
768 function convert_department_dn($dn)
770   $dep= "";
772   /* Build a sub-directory style list of the tree level
773      specified in $dn */
774   foreach (split (',', $dn) as $val){
776     /* We're only interested in organizational units... */
777     if (preg_match ("/ou=/", $val)){
778       $dep= substr($val,3)."/$dep";
779     }
781     /* ... and location objects */
782     if (preg_match ("/l=/", $val)){
783       $dep= substr($val,2)."/$dep";
784     }
785   }
787   /* Fix name, if it contains a replace tag */
788   $dep= preg_replace('/###GOSAREPLACED###/', ',', $dep);
790   /* Return and remove accidently trailing slashes */
791   return rtrim($dep, "/");
794 function convert_department_dn2($dn)
797 /*
798   
799   I think this no longer used  ...
800   Check this, and remove this function 
802   
803 */
805   $dep= "";
806   /* Build a sub-directory style list of the tree level
807      specified in $dn */
808   $deps = array_flip($_SESSION['config']->idepartments);
810   if(isset($deps[$dn])){
811     $dn= $deps[$dn];
812     $dep = preg_replace("/^.*=/","",$dn);
813   }else{  
814     global $config;
815     $base = "ou=";
816     if(isset($config->current['BASE'])){
817       $base =  $config->current['BASE'];  
818     }
819     if(preg_match("%".$base."%",$dn)){
820       $dep= preg_replace("%^.*\/([^\/]+)$%", "\\1", $dn);
821     }else{
822       $dep = $dn;
823     }
824   }
826   /* Return and remove accidently trailing slashes */
827   $tmp = rtrim($dep, "/");
828   return $tmp;
832 function get_ou($name)
834   global $config;
836   $ou= $config->current[$name];
837   if ($ou != ""){
838     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
839       return "ou=$ou,";
840     } else {
841       return "$ou,";
842     }
843   } else {
844     return "";
845   }
849 function get_people_ou()
851   return (get_ou("PEOPLE"));
855 function get_groups_ou()
857   return (get_ou("GROUPS"));
861 function get_winstations_ou()
863   return (get_ou("WINSTATIONS"));
867 function get_base_from_people($dn)
869   global $config;
871   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
872   $base= preg_replace($pattern, '', $dn);
874   /* Set to base, if we're not on a correct subtree */
875   if (!isset($config->idepartments[$base])){
876     $base= $config->current['BASE'];
877   }
879   return ($base);
883 function get_departments($ignore_dn= "")
885   global $config;
887   /* Initialize result hash */
888   $result= array();
889   $result['/']= $config->current['BASE'];
891   /* Get list of department objects */
892   $ldap= $config->get_ldap_link();
893   $ldap->cd ($config->current['BASE']);
894   $ldap->search ("(objectClass=gosaDepartment)", array("ou"));
895   while ($attrs= $ldap->fetch()){
896     $dn= $ldap->getDN();
897     if ($dn == $ignore_dn){
898       continue;
899     }
900     $result[convert_department_dn($dn)]= $dn;
901   }
903   return ($result);
907 function chkacl($acl, $name)
909   /* Look for attribute in ACL */
910   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
911     return ("");
912   }
914   /* Optically disable html object for no match */
915   return (" disabled ");
919 function is_phone_nr($nr)
921   if ($nr == ""){
922     return (TRUE);
923   }
925   return preg_match ("/^[0-9 ()+*-]+$/", $nr);
929 function is_url($url)
931   if ($url == ""){
932     return (TRUE);
933   }
935   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
939 function is_dn($dn)
941   if ($dn == ""){
942     return (TRUE);
943   }
945   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
949 function is_uid($uid)
951   global $config;
953   if ($uid == ""){
954     return (TRUE);
955   }
957   /* STRICT adds spaces and case insenstivity to the uid check.
958      This is dangerous and should not be used. */
959   if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
960     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
961   } else {
962     return preg_match ("/^[a-z0-9_-]+$/", $uid);
963   }
967 function is_id($id)
969   if ($id == ""){
970     return (FALSE);
971   }
973   return preg_match ("/^[0-9]+$/", $id);
977 function is_path($path)
979   if ($path == ""){
980     return (TRUE);
981   }
982   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
983     return (FALSE);
984   }
986   return preg_match ("/\/.+$/", $path);
990 function is_email($address, $template= FALSE)
992   if ($address == ""){
993     return (TRUE);
994   }
995   if ($template){
996     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
997         $address);
998   } else {
999     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1000         $address);
1001   }
1005 function print_red()
1007   /* Check number of arguments */
1008   if (func_num_args() < 1){
1009     return;
1010   }
1012   /* Get arguments, save string */
1013   $array = func_get_args();
1014   $string= $array[0];
1016   /* Step through arguments */
1017   for ($i= 1; $i<count($array); $i++){
1018     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1019   }
1021   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1022     $_SESSION['errorsAlreadyPosted'] = array(); 
1023   }
1025   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1026      the other case... */
1028   if (isset($_SESSION['DEBUGLEVEL'])){
1030     if($_SESSION['LastError'] == $string){
1032       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1033         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1034       }
1035       $_SESSION['errorsAlreadyPosted'][$string] ++;
1037     }else{
1038       if((!empty($_SESSION['LastError'])) && ($_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']]>1)){
1039         $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
1040           "border-style:solid;border-color:red; background-color:black;".
1041           "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
1042           get_template_path('images/warning.png')."\"></td>".
1043           "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
1044           "<b style='font-size:16px;'>".sprintf(_("Last message repeated %s times."),$_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']])."</b></font></td><td>".
1045           "<img alt=\"\"src=\"".get_template_path('images/warning.png').
1046           "\"></td></tr></table></div>\n";
1047       }
1049       if($string != NULL){
1050         $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
1051           "border-style:solid;border-color:red; background-color:black;".
1052           "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
1053           get_template_path('images/warning.png')."\"></td>".
1054           "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
1055           "<b style='font-size:16px;'>$string</b></font></td><td>".
1056           "<img alt=\"\"src=\"".get_template_path('images/warning.png').
1057           "\"></td></tr></table></div>\n";
1058       }else{
1059         return;
1060       }
1061       $_SESSION['errorsAlreadyPosted'] = array();
1062       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1064     }
1066   } else {
1067     echo "Error: $string\n";
1068   }
1069   $_SESSION['LastError'] = $string; 
1074 function gen_locked_message($user, $dn)
1076   global $plug, $config;
1078   $_SESSION['dn']= $dn;
1079   $ldap= $config->get_ldap_link();
1080   $ldap->cat ($user);
1081   $attrs= $ldap->fetch();
1082   $uid= $attrs["uid"][0];
1084   //  print_a($_POST);
1085   //  print_a($_GET);
1087   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1088     $_SESSION['LOCK_VARS_USED']  =array();
1089     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1091       if(empty($name)) continue;
1092       foreach($_POST as $Pname => $Pvalue){
1093         if(preg_match($name,$Pname)){
1094           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1095         }
1096       }
1098       foreach($_GET as $Pname => $Pvalue){
1099         if(preg_match($name,$Pname)){
1100           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1101         }
1102       }
1103     }
1104     $_SESSION['LOCK_VARS_TO_USE'] =array();
1105   }
1107   /* Prepare and show template */
1108   $smarty= get_smarty();
1109   $smarty->assign ("dn", $dn);
1110   $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."), $dn, "<a href=\"main.php?plug=0&amp;viewid=$uid\">$uid</a>"));
1112   return ($smarty->fetch (get_template_path('islocked.tpl')));
1116 function to_string ($value)
1118   /* If this is an array, generate a text blob */
1119   if (is_array($value)){
1120     $ret= "";
1121     foreach ($value as $line){
1122       $ret.= $line."<br>\n";
1123     }
1124     return ($ret);
1125   } else {
1126     return ($value);
1127   }
1131 function get_printer_list($cups_server)
1133   global $config;
1135   $res= array();
1137   /* Use CUPS, if we've access to it */
1138   if (function_exists('cups_get_dest_list')){
1139     $dest_list= cups_get_dest_list ($cups_server);
1141     foreach ($dest_list as $prt){
1142       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1144       foreach ($attr as $prt_info){
1145         if ($prt_info->name == "printer-info"){
1146           $info= $prt_info->value;
1147           break;
1148         }
1149       }
1150       $res[$prt->name]= "$info [$prt->name]";
1151     }
1153     /* CUPS is not available, try lpstat as a replacement */
1154   } else {
1155     $ar = false;
1156     exec("lpstat -p", $ar);
1157     foreach($ar as $val){
1158       list($dummy, $printer, $rest)= split(' ', $val, 3);
1159       if (preg_match('/^[^@]+$/', $printer)){
1160         $res[$printer]= "$printer";
1161       }
1162     }
1163   }
1165   /* Merge in printers from LDAP */
1166   $ldap= $config->get_ldap_link();
1167   $ldap->cd ($config->current['BASE']);
1168   $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1169   while ($attrs= $ldap->fetch()){
1170     $res[$attrs["cn"][0]]= $attrs["cn"][0];
1171   }
1173   return $res;
1177 function sess_del ($var)
1179   /* New style */
1180   unset ($_SESSION[$var]);
1182   /* ... work around, since the first one
1183      doesn't seem to work all the time */
1184   session_unregister ($var);
1188 function show_errors($message)
1190   $complete= "";
1192   /* Assemble the message array to a plain string */
1193   foreach ($message as $error){
1194     if ($complete == ""){
1195       $complete= $error;
1196     } else {
1197       $complete= "$error<br>$complete";
1198     }
1199   }
1201   /* Fill ERROR variable with nice error dialog */
1202   print_red($complete);
1206 function show_ldap_error($message)
1208   if (!preg_match("/Success/i", $message)){
1209     print_red (_("LDAP error:")." $message");
1210     return TRUE;
1211   } else {
1212     return FALSE;
1213   }
1217 function rewrite($s)
1219   global $REWRITE;
1221   foreach ($REWRITE as $key => $val){
1222     $s= preg_replace("/$key/", "$val", $s);
1223   }
1225   return ($s);
1229 function dn2base($dn)
1231   global $config;
1233   if (get_people_ou() != ""){
1234     $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1235   }
1236   if (get_groups_ou() != ""){
1237     $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1238   }
1239   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1241   return ($base);
1246 function check_command($cmdline)
1248   $cmd= preg_replace("/ .*$/", "", $cmdline);
1250   /* Check if command exists in filesystem */
1251   if (!file_exists($cmd)){
1252     return (FALSE);
1253   }
1255   /* Check if command is executable */
1256   if (!is_executable($cmd)){
1257     return (FALSE);
1258   }
1260   return (TRUE);
1264 function print_header($image, $headline, $info= "")
1266   $display= "<div class=\"plugtop\">\n";
1267   $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";
1268   $display.= "</div>\n";
1270   if ($info != ""){
1271     $display.= "<div class=\"pluginfo\">\n";
1272     $display.= "$info";
1273     $display.= "</div>\n";
1274   } else {
1275     $display.= "<div style=\"height:5px;\">\n";
1276     $display.= "&nbsp;";
1277     $display.= "</div>\n";
1278   }
1280   return ($display);
1284 function register_global($name, $object)
1286   $_SESSION[$name]= $object;
1290 function is_global($name)
1292   return isset($_SESSION[$name]);
1296 function get_global($name)
1298   return $_SESSION[$name];
1302 function range_selector($dcnt,$start,$range=25,$post_var=false)
1305   /* Entries shown left and right from the selected entry */
1306   $max_entries= 10;
1308   /* Initialize and take care that max_entries is even */
1309   $output="";
1310   if ($max_entries & 1){
1311     $max_entries++;
1312   }
1314   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1315     $range= $_POST[$post_var];
1316   }
1318   /* Prevent output to start or end out of range */
1319   if ($start < 0 ){
1320     $start= 0 ;
1321   }
1322   if ($start >= $dcnt){
1323     $start= $range * (int)(($dcnt / $range) + 0.5);
1324   }
1326   $numpages= (($dcnt / $range));
1327   if(((int)($numpages))!=($numpages)){
1328     $numpages = (int)$numpages + 1;
1329   }
1330   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1331     return ("");
1332   }
1333   $ppage= (int)(($start / $range) + 0.5);
1336   /* Align selected page to +/- max_entries/2 */
1337   $begin= $ppage - $max_entries/2;
1338   $end= $ppage + $max_entries/2;
1340   /* Adjust begin/end, so that the selected value is somewhere in
1341      the middle and the size is max_entries if possible */
1342   if ($begin < 0){
1343     $end-= $begin + 1;
1344     $begin= 0;
1345   }
1346   if ($end > $numpages) {
1347     $end= $numpages;
1348   }
1349   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1350     $begin= $end - $max_entries;
1351   }
1353   if($post_var){
1354     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1355       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1356   }else{
1357     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1358   }
1360   /* Draw decrement */
1361   if ($start > 0 ) {
1362     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1363       (($start-$range))."\">".
1364       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1365   }
1367   /* Draw pages */
1368   for ($i= $begin; $i < $end; $i++) {
1369     if ($ppage == $i){
1370       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1371         validate($_GET['plug'])."&amp;start=".
1372         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1373     } else {
1374       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1375         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1376     }
1377   }
1379   /* Draw increment */
1380   if($start < ($dcnt-$range)) {
1381     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1382       (($start+($range)))."\">".
1383       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1384   }
1386   if(($post_var)&&($numpages)){
1387     $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()'>";
1388     foreach(array(20,50,100,200,"all") as $num){
1389       if($num == "all"){
1390         $var = 10000;
1391       }else{
1392         $var = $num;
1393       }
1394       if($var == $range){
1395         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1396       }else{  
1397         $output.="\n<option value='".$var."'>".$num."</option>";
1398       }
1399     }
1400     $output.=  "</select></td></tr></table></div>";
1401   }else{
1402     $output.= "</div>";
1403   }
1405   return($output);
1409 function apply_filter()
1411   $apply= "";
1413   $apply= ''.
1414     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1415     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1417   return ($apply);
1421 function back_to_main()
1423   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1424     _("Back").'"></p><input type="hidden" name="ignore">';
1426   return ($string);
1430 function normalize_netmask($netmask)
1432   /* Check for notation of netmask */
1433   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1434     $num= (int)($netmask);
1435     $netmask= "";
1437     for ($byte= 0; $byte<4; $byte++){
1438       $result=0;
1440       for ($i= 7; $i>=0; $i--){
1441         if ($num-- > 0){
1442           $result+= pow(2,$i);
1443         }
1444       }
1446       $netmask.= $result.".";
1447     }
1449     return (preg_replace('/\.$/', '', $netmask));
1450   }
1452   return ($netmask);
1456 function netmask_to_bits($netmask)
1458   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1459   $res= 0;
1461   for ($n= 0; $n<4; $n++){
1462     $start= 255;
1463     $name= "nm$n";
1465     for ($i= 0; $i<8; $i++){
1466       if ($start == (int)($$name)){
1467         $res+= 8 - $i;
1468         break;
1469       }
1470       $start-= pow(2,$i);
1471     }
1472   }
1474   return ($res);
1478 function recurse($rule, $variables)
1480   $result= array();
1482   if (!count($variables)){
1483     return array($rule);
1484   }
1486   reset($variables);
1487   $key= key($variables);
1488   $val= current($variables);
1489   unset ($variables[$key]);
1491   foreach($val as $possibility){
1492     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1493     $result= array_merge($result, recurse($nrule, $variables));
1494   }
1496   return ($result);
1500 function expand_id($rule, $attributes)
1502   /* Check for id rule */
1503   if(preg_match('/^id(:|#)\d+$/',$rule)){
1504     return (array("\{$rule}"));
1505   }
1507   /* Check for clean attribute */
1508   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1509     $rule= preg_replace('/^%/', '', $rule);
1510     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1511     return (array($val));
1512   }
1514   /* Check for attribute with parameters */
1515   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1516     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1517     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1518     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1519     $start= preg_replace ('/-.*$/', '', $param);
1520     $stop = preg_replace ('/^[^-]+-/', '', $param);
1522     /* Assemble results */
1523     $result= array();
1524     for ($i= $start; $i<= $stop; $i++){
1525       $result[]= substr($val, 0, $i);
1526     }
1527     return ($result);
1528   }
1530   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1531   return (array($rule));
1535 function gen_uids($rule, $attributes)
1537   global $config;
1539   /* Search for keys and fill the variables array with all 
1540      possible values for that key. */
1541   $part= "";
1542   $trigger= false;
1543   $stripped= "";
1544   $variables= array();
1546   for ($pos= 0; $pos < strlen($rule); $pos++){
1548     if ($rule[$pos] == "{" ){
1549       $trigger= true;
1550       $part= "";
1551       continue;
1552     }
1554     if ($rule[$pos] == "}" ){
1555       $variables[$pos]= expand_id($part, $attributes);
1556       $stripped.= "\{$pos}";
1557       $trigger= false;
1558       continue;
1559     }
1561     if ($trigger){
1562       $part.= $rule[$pos];
1563     } else {
1564       $stripped.= $rule[$pos];
1565     }
1566   }
1568   /* Recurse through all possible combinations */
1569   $proposed= recurse($stripped, $variables);
1571   /* Get list of used ID's */
1572   $used= array();
1573   $ldap= $config->get_ldap_link();
1574   $ldap->cd($config->current['BASE']);
1575   $ldap->search('(uid=*)');
1577   while($attrs= $ldap->fetch()){
1578     $used[]= $attrs['uid'][0];
1579   }
1581   /* Remove used uids and watch out for id tags */
1582   $ret= array();
1583   foreach($proposed as $uid){
1585     /* Check for id tag and modify uid if needed */
1586     if(preg_match('/\{id:\d+}/',$uid)){
1587       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1589       for ($i= 0; $i < pow(10,$size); $i++){
1590         $number= sprintf("%0".$size."d", $i);
1591         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1592         if (!in_array($res, $used)){
1593           $uid= $res;
1594           break;
1595         }
1596       }
1597     }
1599   if(preg_match('/\{id#\d+}/',$uid)){
1600     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1602     while (true){
1603       mt_srand((double) microtime()*1000000);
1604       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1605       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1606       if (!in_array($res, $used)){
1607         $uid= $res;
1608         break;
1609       }
1610     }
1611   }
1613 /* Don't assign used ones */
1614 if (!in_array($uid, $used)){
1615   $ret[]= $uid;
1619 return(array_unique($ret));
1623 function array_search_r($needle, $key, $haystack){
1625   foreach($haystack as $index => $value){
1626     $match= 0;
1628     if (is_array($value)){
1629       $match= array_search_r($needle, $key, $value);
1630     }
1632     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1633       $match=1;
1634     }
1636     if ($match){
1637       return 1;
1638     }
1639   }
1641   return 0;
1642
1645 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1646    Need to convert... */
1647 function to_byte($value) {
1648   $value= strtolower(trim($value));
1650   if(!is_numeric(substr($value, -1))) {
1652     switch(substr($value, -1)) {
1653       case 'g':
1654         $mult= 1073741824;
1655         break;
1656       case 'm':
1657         $mult= 1048576;
1658         break;
1659       case 'k':
1660         $mult= 1024;
1661         break;
1662     }
1664     return ($mult * (int)substr($value, 0, -1));
1665   } else {
1666     return $value;
1667   }
1671 function in_array_ics($value, $items)
1673   if (!is_array($items)){
1674     return (FALSE);
1675   }
1677   foreach ($items as $item){
1678     if (strtolower($item) == strtolower($value)) {
1679       return (TRUE);
1680     }
1681   }
1683   return (FALSE);
1684
1687 function generate_alphabet($count= 10)
1689   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1690   $alphabet= "";
1691   $c= 0;
1693   /* Fill cells with charaters */
1694   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1695     if ($c == 0){
1696       $alphabet.= "<tr>";
1697     }
1699     $ch = mb_substr($characters, $i, 1, "UTF8");
1700     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1701       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1703     if ($c++ == $count){
1704       $alphabet.= "</tr>";
1705       $c= 0;
1706     }
1707   }
1709   /* Fill remaining cells */
1710   while ($c++ <= $count){
1711     $alphabet.= "<td>&nbsp;</td>";
1712   }
1714   return ($alphabet);
1718 function validate($string)
1720   return (strip_tags(preg_replace('/\0/', '', $string)));
1723 function get_gosa_version()
1725   global $svn_revision, $svn_path;
1727   /* Extract informations */
1728   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1730   /* Release or development? */
1731   if (preg_match('%/gosa/trunk/%', $svn_path)){
1732     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1733   } else {
1734     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1735     return (sprintf(_("GOsa $release"), $revision));
1736   }
1740 function rmdirRecursive($path, $followLinks=false) {
1741   $dir= opendir($path);
1742   while($entry= readdir($dir)) {
1743     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1744       unlink($path."/".$entry);
1745     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1746       rmdirRecursive($path."/".$entry);
1747     }
1748   }
1749   closedir($dir);
1750   return rmdir($path);
1753 function scan_directory($path,$sort_desc=false)
1755   $ret = false;
1757   /* is this a dir ? */
1758   if(is_dir($path)) {
1760     /* is this path a readable one */
1761     if(is_readable($path)){
1763       /* Get contents and write it into an array */   
1764       $ret = array();    
1766       $dir = opendir($path);
1768       /* Is this a correct result ?*/
1769       if($dir){
1770         while($fp = readdir($dir))
1771           $ret[]= $fp;
1772       }
1773     }
1774   }
1775   /* Sort array ascending , like scandir */
1776   sort($ret);
1778   /* Sort descending if parameter is sort_desc is set */
1779   if($sort_desc) {
1780     $ret = array_reverse($ret);
1781   }
1783   return($ret);
1786 function clean_smarty_compile_dir($directory)
1788   global $svn_revision;
1790   if(is_dir($directory) && is_readable($directory)) {
1791     // Set revision filename to REVISION
1792     $revision_file= $directory."/REVISION";
1794     /* Is there a stamp containing the current revision? */
1795     if(!file_exists($revision_file)) {
1796       // create revision file
1797       create_revision($revision_file, $svn_revision);
1798     } else {
1799 # check for "$config->...['CONFIG']/revision" and the
1800 # contents should match the revision number
1801       if(!compare_revision($revision_file, $svn_revision)){
1802         // If revision differs, clean compile directory
1803         foreach(scan_directory($directory) as $file) {
1804           if(($file==".")||($file=="..")) continue;
1805           if( is_file($directory."/".$file) &&
1806               is_writable($directory."/".$file)) {
1807             // delete file
1808             if(!unlink($directory."/".$file)) {
1809               print_red("File ".$directory."/".$file." could not be deleted.");
1810               // This should never be reached
1811             }
1812           } elseif(is_dir($directory."/".$file) &&
1813               is_writable($directory."/".$file)) {
1814             // Just recursively delete it
1815             rmdirRecursive($directory."/".$file);
1816           }
1817         }
1818         // We should now create a fresh revision file
1819         clean_smarty_compile_dir($directory);
1820       } else {
1821         // Revision matches, nothing to do
1822       }
1823     }
1824   } else {
1825     // Smarty compile dir is not accessible
1826     // (Smarty will warn about this)
1827   }
1830 function create_revision($revision_file, $revision)
1832   $result= false;
1834   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1835     if($fh= fopen($revision_file, "w")) {
1836       if(fwrite($fh, $revision)) {
1837         $result= true;
1838       }
1839     }
1840     fclose($fh);
1841   } else {
1842     print_red("Can not write to revision file");
1843   }
1845   return $result;
1848 function compare_revision($revision_file, $revision)
1850   // false means revision differs
1851   $result= false;
1853   if(file_exists($revision_file) && is_readable($revision_file)) {
1854     // Open file
1855     if($fh= fopen($revision_file, "r")) {
1856       // Compare File contents with current revision
1857       if($revision == fread($fh, filesize($revision_file))) {
1858         $result= true;
1859       }
1860     } else {
1861       print_red("Can not open revision file");
1862     }
1863     // Close file
1864     fclose($fh);
1865   }
1867   return $result;
1870 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1872   $str = ""; // Our return value will be saved in this var
1874   $color  = dechex($percentage+150);
1875   $color2 = dechex(150 - $percentage);
1876   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1878   $progress = (int)(($percentage /100)*$width);
1880   /* Abort printing out percentage, if divs are to small */
1883   /* If theres a better solution for this, use it... */
1884   $str = "
1885     <div style=\" width:".($width)."px; 
1886     height:".($height)."px;
1887   background-color:#000000;
1888 padding:1px;\">
1890           <div style=\" width:".($width)."px;
1891         background-color:#$bgcolor;
1892 height:".($height)."px;\">
1894          <div style=\" width:".$progress."px;
1895 height:".$height."px;
1896        background-color:#".$color2.$color2.$color."; \">";
1899        if(($height >10)&&($showvalue)){
1900          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1901            <b>".$percentage."%</b>
1902            </font>";
1903        }
1905        $str.= "</div></div></div>";
1907        return($str);
1911 function array_key_ics($ikey, $items)
1913   /* Gather keys, make them lowercase */
1914   $tmp= array();
1915   foreach ($items as $key => $value){
1916     $tmp[strtolower($key)]= $key;
1917   }
1919   if (isset($tmp[strtolower($ikey)])){
1920     return($tmp[strtolower($ikey)]);
1921   }
1923   return ("");
1927 function search_config($arr, $name, $return)
1929   if (is_array($arr)){
1930     foreach ($arr as $a){
1931       if (isset($a['CLASS']) &&
1932           strtolower($a['CLASS']) == strtolower($name)){
1934         if (isset($a[$return])){
1935           return ($a[$return]);
1936         } else {
1937           return ("");
1938         }
1939       } else {
1940         $res= search_config ($a, $name, $return);
1941         if ($res != ""){
1942           return $res;
1943         }
1944       }
1945     }
1946   }
1947   return ("");
1951 function array_differs($src, $dst)
1953   /* If the count is differing, the arrays differ */
1954   if (count ($src) != count ($dst)){
1955     return (TRUE);
1956   }
1958   /* So the count is the same - lets check the contents */
1959   $differs= FALSE;
1960   foreach($src as $value){
1961     if (!in_array($value, $dst)){
1962       $differs= TRUE;
1963     }
1964   }
1966   return ($differs);
1970 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1971 ?>