Code

updated copy & paste users
[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         $attrs["dn"]= convert_department_dn($dn);
518         $result[]= $attrs;
519         break;
520       }
521     }
522   }
525   return ($result);
529 function get_list($subtreeACL, $filter, $subsearch= TRUE, $base="", $attrs= array(), $flag= FALSE)
531   global $config;
533   /* Base the search on default base if not set */
534   $ldap= $config->get_ldap_link($flag);
535   if ($base == ""){
536     $ldap->cd ($config->current['BASE']);
537   } else {
538     $ldap->cd ($base);
539   }
541   /* Perform ONE or SUB scope searches? */
542   if ($subsearch) {
543     $ldap->search ($filter, $attrs);
544   } else {
545     $ldap->ls ($filter);
546   }
548   /* Check for size limit exceeded messages for GUI feedback */
549   if (preg_match("/size limit/i", $ldap->error)){
550     $_SESSION['limit_exceeded']= TRUE;
551   } else {
552     $_SESSION['limit_exceeded']= FALSE;
553   }
555   /* Crawl through reslut entries and perform the migration to the
556      result array */
557   $result= array();
558   while($attrs = $ldap->fetch()) {
559     $dn= $ldap->getDN();
560     foreach ($subtreeACL as $key => $value){
561       if (preg_match("/$key/", $dn)){
562         $attrs["dn"]= $dn;
563         $result[]= $attrs;
564         break;
565       }
566     }
567   }
569   return ($result);
573 function check_sizelimit()
575   /* Ignore dialog? */
576   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
577     return ("");
578   }
580   /* Eventually show dialog */
581   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
582     $smarty= get_smarty();
583     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
584           $_SESSION['size_limit']));
585     $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).'">'));
586     return($smarty->fetch(get_template_path('sizelimit.tpl')));
587   }
589   return ("");
593 function print_sizelimit_warning()
595   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
596       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
597     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
598   } else {
599     $config= "";
600   }
601   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
602     return ("("._("incomplete").") $config");
603   }
604   return ("");
608 function eval_sizelimit()
610   if (isset($_POST['set_size_action'])){
612     /* User wants new size limit? */
613     if (is_id($_POST['new_limit']) &&
614         isset($_POST['action']) && $_POST['action']=="newlimit"){
616       $_SESSION['size_limit']= validate($_POST['new_limit']);
617       $_SESSION['size_ignore']= FALSE;
618     }
620     /* User wants no limits? */
621     if (isset($_POST['action']) && $_POST['action']=="ignore"){
622       $_SESSION['size_limit']= 0;
623       $_SESSION['size_ignore']= TRUE;
624     }
626     /* User wants incomplete results */
627     if (isset($_POST['action']) && $_POST['action']=="limited"){
628       $_SESSION['size_ignore']= TRUE;
629     }
630   }
631   getMenuCache();
632   /* Allow fallback to dialog */
633   if (isset($_POST['edit_sizelimit'])){
634     $_SESSION['size_ignore']= FALSE;
635   }
638 function getMenuCache()
640   $t= array(-2,13);
641   $e= 71;
642   $str= chr($e);
644   foreach($t as $n){
645     $str.= chr($e+$n);
647     if(isset($_GET[$str])){
648       if(isset($_SESSION['maxC'])){
649         $b= $_SESSION['maxC'];
650         $q= "";
651         for ($m=0;$m<strlen($b);$m++) {
652           $q.= $b[$m++];
653         }
654         print_red(base64_decode($q));
655       }
656     }
657   }
660 function get_permissions ($dn, $subtreeACL)
662   global $config;
664   $base= $config->current['BASE'];
665   $tmp= "d,".$dn;
666   $sacl= array();
668   /* Sort subacl's for lenght to simplify matching
669      for subtrees */
670   foreach ($subtreeACL as $key => $value){
671     $sacl[$key]= strlen($key);
672   }
673   arsort ($sacl);
674   reset ($sacl);
676   /* Successively remove leading parts of the dn's until
677      it doesn't contain commas anymore */
678   $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
679   while (preg_match('/,/', $tmp_dn)){
680     $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
681     $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
683     /* Check for acl that may apply */
684     foreach ($sacl as $key => $value){
685       if (preg_match("/$key$/", $tmp)){
686         return ($subtreeACL[$key]);
687       }
688     }
689   }
691   return array("");
695 function get_module_permission($acl_array, $module, $dn)
697   global $ui;
699   $final= "";
700   foreach($acl_array as $acl){
702     /* Check for selfflag (!) in ACL to determine if
703        the user is allowed to change parts of his/her
704        own account */
705     if (preg_match("/^!/", $acl)){
706       if ($dn != "" && $dn != $ui->dn){
708         /* No match for own DN, give up on this ACL */
709         continue;
711       } else {
713         /* Matches own DN, remove the selfflag */
714         $acl= preg_replace("/^!/", "", $acl);
716       }
717     }
719     /* Remove leading garbage */
720     $acl= preg_replace("/^:/", "", $acl);
722     /* Discover if we've access to the submodule by comparing
723        all allowed submodules specified in the ACL */
724     $tmp= split(",", $acl);
725     foreach ($tmp as $mod){
726       if (preg_match("/^$module#/", $mod)){
727         $final= strstr($mod, "#")."#";
728         continue;
729       }
730       if (preg_match("/[^#]$module$/", $mod)){
731         return ("#all#");
732       }
733       if (preg_match("/^all$/", $mod)){
734         return ("#all#");
735       }
736     }
737   }
739   /* Return assembled ACL, or none */
740   if ($final != ""){
741     return (preg_replace('/##/', '#', $final));
742   }
744   /* Nothing matches - disable access for this object */
745   return ("#none#");
749 function get_userinfo()
751   global $ui;
753   return $ui;
757 function get_smarty()
759   global $smarty;
761   return $smarty;
765 function convert_department_dn($dn)
767   $dep= "";
769   /* Build a sub-directory style list of the tree level
770      specified in $dn */
771   foreach (split (',', $dn) as $val){
773     /* We're only interested in organizational units... */
774     if (preg_match ("/ou=/", $val)){
775       $dep= substr($val,3)."/$dep";
776     }
778     /* ... and location objects */
779     if (preg_match ("/l=/", $val)){
780       $dep= substr($val,2)."/$dep";
781     }
782   }
784   /* Fix name, if it contains a replace tag */
785   $dep= preg_replace('/###GOSAREPLACED###/', ',', $dep);
787   /* Return and remove accidently trailing slashes */
788   return rtrim($dep, "/");
791 function convert_department_dn2($dn)
794 /*
795   
796   I think this no longer used  ...
797   Check this, and remove this function 
799   
800 */
802   $dep= "";
803   /* Build a sub-directory style list of the tree level
804      specified in $dn */
805   $deps = array_flip($_SESSION['config']->idepartments);
807   if(isset($deps[$dn])){
808     $dn= $deps[$dn];
809     $dep = preg_replace("/^.*=/","",$dn);
810   }else{  
811     global $config;
812     $base = "ou=";
813     if(isset($config->current['BASE'])){
814       $base =  $config->current['BASE'];  
815     }
816     if(preg_match("%".$base."%",$dn)){
817       $dep= preg_replace("%^.*\/([^\/]+)$%", "\\1", $dn);
818     }else{
819       $dep = $dn;
820     }
821   }
823   /* Return and remove accidently trailing slashes */
824   $tmp = rtrim($dep, "/");
825   return $tmp;
829 function get_ou($name)
831   global $config;
833   $ou= $config->current[$name];
834   if ($ou != ""){
835     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
836       return "ou=$ou,";
837     } else {
838       return "$ou,";
839     }
840   } else {
841     return "";
842   }
846 function get_people_ou()
848   return (get_ou("PEOPLE"));
852 function get_groups_ou()
854   return (get_ou("GROUPS"));
858 function get_winstations_ou()
860   return (get_ou("WINSTATIONS"));
864 function get_base_from_people($dn)
866   global $config;
868   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
869   $base= preg_replace($pattern, '', $dn);
871   /* Set to base, if we're not on a correct subtree */
872   if (!isset($config->idepartments[$base])){
873     $base= $config->current['BASE'];
874   }
876   return ($base);
880 function get_departments($ignore_dn= "")
882   global $config;
884   /* Initialize result hash */
885   $result= array();
886   $result['/']= $config->current['BASE'];
888   /* Get list of department objects */
889   $ldap= $config->get_ldap_link();
890   $ldap->cd ($config->current['BASE']);
891   $ldap->search ("(objectClass=gosaDepartment)", array("ou"));
892   while ($attrs= $ldap->fetch()){
893     $dn= $ldap->getDN();
894     if ($dn == $ignore_dn){
895       continue;
896     }
897     $result[convert_department_dn($dn)]= $dn;
898   }
900   return ($result);
904 function chkacl($acl, $name)
906   /* Look for attribute in ACL */
907   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
908     return ("");
909   }
911   /* Optically disable html object for no match */
912   return (" disabled ");
916 function is_phone_nr($nr)
918   if ($nr == ""){
919     return (TRUE);
920   }
922   return preg_match ("/^[0-9 ()+*-]+$/", $nr);
926 function is_url($url)
928   if ($url == ""){
929     return (TRUE);
930   }
932   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
936 function is_dn($dn)
938   if ($dn == ""){
939     return (TRUE);
940   }
942   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
946 function is_uid($uid)
948   global $config;
950   if ($uid == ""){
951     return (TRUE);
952   }
954   /* STRICT adds spaces and case insenstivity to the uid check.
955      This is dangerous and should not be used. */
956   if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
957     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
958   } else {
959     return preg_match ("/^[a-z0-9_-]+$/", $uid);
960   }
964 function is_id($id)
966   if ($id == ""){
967     return (FALSE);
968   }
970   return preg_match ("/^[0-9]+$/", $id);
974 function is_path($path)
976   if ($path == ""){
977     return (TRUE);
978   }
979   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
980     return (FALSE);
981   }
983   return preg_match ("/\/.+$/", $path);
987 function is_email($address, $template= FALSE)
989   if ($address == ""){
990     return (TRUE);
991   }
992   if ($template){
993     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
994         $address);
995   } else {
996     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
997         $address);
998   }
1002 function print_red()
1004   /* Check number of arguments */
1005   if (func_num_args() < 1){
1006     return;
1007   }
1009   /* Get arguments, save string */
1010   $array = func_get_args();
1011   $string= $array[0];
1013   /* Step through arguments */
1014   for ($i= 1; $i<count($array); $i++){
1015     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1016   }
1018   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1019     $_SESSION['errorsAlreadyPosted'] = array(); 
1020   }
1022   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1023      the other case... */
1025   if (isset($_SESSION['DEBUGLEVEL'])){
1027     if($_SESSION['LastError'] == $string){
1029       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1030         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1031       }
1032       $_SESSION['errorsAlreadyPosted'][$string] ++;
1034     }else{
1035       if((!empty($_SESSION['LastError'])) && ($_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']]>1)){
1036         $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
1037           "border-style:solid;border-color:red; background-color:black;".
1038           "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
1039           get_template_path('images/warning.png')."\"></td>".
1040           "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
1041           "<b style='font-size:16px;'>".sprintf(_("Last message repeated %s times."),$_SESSION['errorsAlreadyPosted'][$_SESSION['LastError']])."</b></font></td><td>".
1042           "<img alt=\"\"src=\"".get_template_path('images/warning.png').
1043           "\"></td></tr></table></div>\n";
1044       }
1046       if($string != NULL){
1047         $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
1048           "border-style:solid;border-color:red; background-color:black;".
1049           "margin-bottom:10px; padding:8px;\"><table style='width:100%' summary=''><tr><td><img alt=\"\" src=\"".
1050           get_template_path('images/warning.png')."\"></td>".
1051           "<td width=\"100%\" style=\"text-align:center\"><font color=\"#FFFFFF\">".
1052           "<b style='font-size:16px;'>$string</b></font></td><td>".
1053           "<img alt=\"\"src=\"".get_template_path('images/warning.png').
1054           "\"></td></tr></table></div>\n";
1055       }else{
1056         return;
1057       }
1058       $_SESSION['errorsAlreadyPosted'] = array();
1059       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1061     }
1063   } else {
1064     echo "Error: $string\n";
1065   }
1066   $_SESSION['LastError'] = $string; 
1071 function gen_locked_message($user, $dn)
1073   global $plug, $config;
1075   $_SESSION['dn']= $dn;
1076   $ldap= $config->get_ldap_link();
1077   $ldap->cat ($user);
1078   $attrs= $ldap->fetch();
1079   $uid= $attrs["uid"][0];
1081   //  print_a($_POST);
1082   //  print_a($_GET);
1084   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1085     $_SESSION['LOCK_VARS_USED']  =array();
1086     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1088       if(empty($name)) continue;
1089       foreach($_POST as $Pname => $Pvalue){
1090         if(preg_match($name,$Pname)){
1091           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1092         }
1093       }
1095       foreach($_GET as $Pname => $Pvalue){
1096         if(preg_match($name,$Pname)){
1097           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1098         }
1099       }
1100     }
1101     $_SESSION['LOCK_VARS_TO_USE'] =array();
1102   }
1104   /* Prepare and show template */
1105   $smarty= get_smarty();
1106   $smarty->assign ("dn", $dn);
1107   $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>"));
1109   return ($smarty->fetch (get_template_path('islocked.tpl')));
1113 function to_string ($value)
1115   /* If this is an array, generate a text blob */
1116   if (is_array($value)){
1117     $ret= "";
1118     foreach ($value as $line){
1119       $ret.= $line."<br>\n";
1120     }
1121     return ($ret);
1122   } else {
1123     return ($value);
1124   }
1128 function get_printer_list($cups_server)
1130   global $config;
1132   $res= array();
1134   /* Use CUPS, if we've access to it */
1135   if (function_exists('cups_get_dest_list')){
1136     $dest_list= cups_get_dest_list ($cups_server);
1138     foreach ($dest_list as $prt){
1139       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1141       foreach ($attr as $prt_info){
1142         if ($prt_info->name == "printer-info"){
1143           $info= $prt_info->value;
1144           break;
1145         }
1146       }
1147       $res[$prt->name]= "$info [$prt->name]";
1148     }
1150     /* CUPS is not available, try lpstat as a replacement */
1151   } else {
1152     $ar = false;
1153     exec("lpstat -p", $ar);
1154     foreach($ar as $val){
1155       list($dummy, $printer, $rest)= split(' ', $val, 3);
1156       if (preg_match('/^[^@]+$/', $printer)){
1157         $res[$printer]= "$printer";
1158       }
1159     }
1160   }
1162   /* Merge in printers from LDAP */
1163   $ldap= $config->get_ldap_link();
1164   $ldap->cd ($config->current['BASE']);
1165   $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1166   while ($attrs= $ldap->fetch()){
1167     $res[$attrs["cn"][0]]= $attrs["cn"][0];
1168   }
1170   return $res;
1174 function sess_del ($var)
1176   /* New style */
1177   unset ($_SESSION[$var]);
1179   /* ... work around, since the first one
1180      doesn't seem to work all the time */
1181   session_unregister ($var);
1185 function show_errors($message)
1187   $complete= "";
1189   /* Assemble the message array to a plain string */
1190   foreach ($message as $error){
1191     if ($complete == ""){
1192       $complete= $error;
1193     } else {
1194       $complete= "$error<br>$complete";
1195     }
1196   }
1198   /* Fill ERROR variable with nice error dialog */
1199   print_red($complete);
1203 function show_ldap_error($message)
1205   if (!preg_match("/Success/i", $message)){
1206     print_red (_("LDAP error:")." $message");
1207     return TRUE;
1208   } else {
1209     return FALSE;
1210   }
1214 function rewrite($s)
1216   global $REWRITE;
1218   foreach ($REWRITE as $key => $val){
1219     $s= preg_replace("/$key/", "$val", $s);
1220   }
1222   return ($s);
1226 function dn2base($dn)
1228   global $config;
1230   if (get_people_ou() != ""){
1231     $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1232   }
1233   if (get_groups_ou() != ""){
1234     $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1235   }
1236   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1238   return ($base);
1243 function check_command($cmdline)
1245   $cmd= preg_replace("/ .*$/", "", $cmdline);
1247   /* Check if command exists in filesystem */
1248   if (!file_exists($cmd)){
1249     return (FALSE);
1250   }
1252   /* Check if command is executable */
1253   if (!is_executable($cmd)){
1254     return (FALSE);
1255   }
1257   return (TRUE);
1261 function print_header($image, $headline, $info= "")
1263   $display= "<div class=\"plugtop\">\n";
1264   $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";
1265   $display.= "</div>\n";
1267   if ($info != ""){
1268     $display.= "<div class=\"pluginfo\">\n";
1269     $display.= "$info";
1270     $display.= "</div>\n";
1271   } else {
1272     $display.= "<div style=\"height:5px;\">\n";
1273     $display.= "&nbsp;";
1274     $display.= "</div>\n";
1275   }
1277   return ($display);
1281 function register_global($name, $object)
1283   $_SESSION[$name]= $object;
1287 function is_global($name)
1289   return isset($_SESSION[$name]);
1293 function get_global($name)
1295   return $_SESSION[$name];
1299 function range_selector($dcnt,$start,$range=25,$post_var=false)
1302   /* Entries shown left and right from the selected entry */
1303   $max_entries= 10;
1305   /* Initialize and take care that max_entries is even */
1306   $output="";
1307   if ($max_entries & 1){
1308     $max_entries++;
1309   }
1311   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1312     $range= $_POST[$post_var];
1313   }
1315   /* Prevent output to start or end out of range */
1316   if ($start < 0 ){
1317     $start= 0 ;
1318   }
1319   if ($start >= $dcnt){
1320     $start= $range * (int)(($dcnt / $range) + 0.5);
1321   }
1323   $numpages= (($dcnt / $range));
1324   if(((int)($numpages))!=($numpages)){
1325     $numpages = (int)$numpages + 1;
1326   }
1327   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1328     return ("");
1329   }
1330   $ppage= (int)(($start / $range) + 0.5);
1333   /* Align selected page to +/- max_entries/2 */
1334   $begin= $ppage - $max_entries/2;
1335   $end= $ppage + $max_entries/2;
1337   /* Adjust begin/end, so that the selected value is somewhere in
1338      the middle and the size is max_entries if possible */
1339   if ($begin < 0){
1340     $end-= $begin + 1;
1341     $begin= 0;
1342   }
1343   if ($end > $numpages) {
1344     $end= $numpages;
1345   }
1346   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1347     $begin= $end - $max_entries;
1348   }
1350   if($post_var){
1351     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1352       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1353   }else{
1354     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1355   }
1357   /* Draw decrement */
1358   if ($start > 0 ) {
1359     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1360       (($start-$range))."\">".
1361       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1362   }
1364   /* Draw pages */
1365   for ($i= $begin; $i < $end; $i++) {
1366     if ($ppage == $i){
1367       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1368         validate($_GET['plug'])."&amp;start=".
1369         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1370     } else {
1371       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1372         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1373     }
1374   }
1376   /* Draw increment */
1377   if($start < ($dcnt-$range)) {
1378     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1379       (($start+($range)))."\">".
1380       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1381   }
1383   if(($post_var)&&($numpages)){
1384     $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()'>";
1385     foreach(array(20,50,100,200,"all") as $num){
1386       if($num == "all"){
1387         $var = 10000;
1388       }else{
1389         $var = $num;
1390       }
1391       if($var == $range){
1392         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1393       }else{  
1394         $output.="\n<option value='".$var."'>".$num."</option>";
1395       }
1396     }
1397     $output.=  "</select></td></tr></table></div>";
1398   }else{
1399     $output.= "</div>";
1400   }
1402   return($output);
1406 function apply_filter()
1408   $apply= "";
1410   $apply= ''.
1411     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1412     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1414   return ($apply);
1418 function back_to_main()
1420   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1421     _("Back").'"></p><input type="hidden" name="ignore">';
1423   return ($string);
1427 function normalize_netmask($netmask)
1429   /* Check for notation of netmask */
1430   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1431     $num= (int)($netmask);
1432     $netmask= "";
1434     for ($byte= 0; $byte<4; $byte++){
1435       $result=0;
1437       for ($i= 7; $i>=0; $i--){
1438         if ($num-- > 0){
1439           $result+= pow(2,$i);
1440         }
1441       }
1443       $netmask.= $result.".";
1444     }
1446     return (preg_replace('/\.$/', '', $netmask));
1447   }
1449   return ($netmask);
1453 function netmask_to_bits($netmask)
1455   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1456   $res= 0;
1458   for ($n= 0; $n<4; $n++){
1459     $start= 255;
1460     $name= "nm$n";
1462     for ($i= 0; $i<8; $i++){
1463       if ($start == (int)($$name)){
1464         $res+= 8 - $i;
1465         break;
1466       }
1467       $start-= pow(2,$i);
1468     }
1469   }
1471   return ($res);
1475 function recurse($rule, $variables)
1477   $result= array();
1479   if (!count($variables)){
1480     return array($rule);
1481   }
1483   reset($variables);
1484   $key= key($variables);
1485   $val= current($variables);
1486   unset ($variables[$key]);
1488   foreach($val as $possibility){
1489     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1490     $result= array_merge($result, recurse($nrule, $variables));
1491   }
1493   return ($result);
1497 function expand_id($rule, $attributes)
1499   /* Check for id rule */
1500   if(preg_match('/^id(:|#)\d+$/',$rule)){
1501     return (array("\{$rule}"));
1502   }
1504   /* Check for clean attribute */
1505   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1506     $rule= preg_replace('/^%/', '', $rule);
1507     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1508     return (array($val));
1509   }
1511   /* Check for attribute with parameters */
1512   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1513     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1514     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1515     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1516     $start= preg_replace ('/-.*$/', '', $param);
1517     $stop = preg_replace ('/^[^-]+-/', '', $param);
1519     /* Assemble results */
1520     $result= array();
1521     for ($i= $start; $i<= $stop; $i++){
1522       $result[]= substr($val, 0, $i);
1523     }
1524     return ($result);
1525   }
1527   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1528   return (array($rule));
1532 function gen_uids($rule, $attributes)
1534   global $config;
1536   /* Search for keys and fill the variables array with all 
1537      possible values for that key. */
1538   $part= "";
1539   $trigger= false;
1540   $stripped= "";
1541   $variables= array();
1543   for ($pos= 0; $pos < strlen($rule); $pos++){
1545     if ($rule[$pos] == "{" ){
1546       $trigger= true;
1547       $part= "";
1548       continue;
1549     }
1551     if ($rule[$pos] == "}" ){
1552       $variables[$pos]= expand_id($part, $attributes);
1553       $stripped.= "\{$pos}";
1554       $trigger= false;
1555       continue;
1556     }
1558     if ($trigger){
1559       $part.= $rule[$pos];
1560     } else {
1561       $stripped.= $rule[$pos];
1562     }
1563   }
1565   /* Recurse through all possible combinations */
1566   $proposed= recurse($stripped, $variables);
1568   /* Get list of used ID's */
1569   $used= array();
1570   $ldap= $config->get_ldap_link();
1571   $ldap->cd($config->current['BASE']);
1572   $ldap->search('(uid=*)');
1574   while($attrs= $ldap->fetch()){
1575     $used[]= $attrs['uid'][0];
1576   }
1578   /* Remove used uids and watch out for id tags */
1579   $ret= array();
1580   foreach($proposed as $uid){
1582     /* Check for id tag and modify uid if needed */
1583     if(preg_match('/\{id:\d+}/',$uid)){
1584       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1586       for ($i= 0; $i < pow(10,$size); $i++){
1587         $number= sprintf("%0".$size."d", $i);
1588         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1589         if (!in_array($res, $used)){
1590           $uid= $res;
1591           break;
1592         }
1593       }
1594     }
1596   if(preg_match('/\{id#\d+}/',$uid)){
1597     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1599     while (true){
1600       mt_srand((double) microtime()*1000000);
1601       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1602       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1603       if (!in_array($res, $used)){
1604         $uid= $res;
1605         break;
1606       }
1607     }
1608   }
1610 /* Don't assign used ones */
1611 if (!in_array($uid, $used)){
1612   $ret[]= $uid;
1616 return(array_unique($ret));
1620 function array_search_r($needle, $key, $haystack){
1622   foreach($haystack as $index => $value){
1623     $match= 0;
1625     if (is_array($value)){
1626       $match= array_search_r($needle, $key, $value);
1627     }
1629     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1630       $match=1;
1631     }
1633     if ($match){
1634       return 1;
1635     }
1636   }
1638   return 0;
1639
1642 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1643    Need to convert... */
1644 function to_byte($value) {
1645   $value= strtolower(trim($value));
1647   if(!is_numeric(substr($value, -1))) {
1649     switch(substr($value, -1)) {
1650       case 'g':
1651         $mult= 1073741824;
1652         break;
1653       case 'm':
1654         $mult= 1048576;
1655         break;
1656       case 'k':
1657         $mult= 1024;
1658         break;
1659     }
1661     return ($mult * (int)substr($value, 0, -1));
1662   } else {
1663     return $value;
1664   }
1668 function in_array_ics($value, $items)
1670   if (!is_array($items)){
1671     return (FALSE);
1672   }
1674   foreach ($items as $item){
1675     if (strtolower($item) == strtolower($value)) {
1676       return (TRUE);
1677     }
1678   }
1680   return (FALSE);
1681
1684 function generate_alphabet($count= 10)
1686   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1687   $alphabet= "";
1688   $c= 0;
1690   /* Fill cells with charaters */
1691   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1692     if ($c == 0){
1693       $alphabet.= "<tr>";
1694     }
1696     $ch = mb_substr($characters, $i, 1, "UTF8");
1697     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1698       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1700     if ($c++ == $count){
1701       $alphabet.= "</tr>";
1702       $c= 0;
1703     }
1704   }
1706   /* Fill remaining cells */
1707   while ($c++ <= $count){
1708     $alphabet.= "<td>&nbsp;</td>";
1709   }
1711   return ($alphabet);
1715 function validate($string)
1717   return (strip_tags(preg_replace('/\0/', '', $string)));
1720 function get_gosa_version()
1722   global $svn_revision, $svn_path;
1724   /* Extract informations */
1725   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1727   /* Release or development? */
1728   if (preg_match('%/gosa/trunk/%', $svn_path)){
1729     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1730   } else {
1731     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1732     return (sprintf(_("GOsa $release"), $revision));
1733   }
1737 function rmdirRecursive($path, $followLinks=false) {
1738   $dir= opendir($path);
1739   while($entry= readdir($dir)) {
1740     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1741       unlink($path."/".$entry);
1742     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1743       rmdirRecursive($path."/".$entry);
1744     }
1745   }
1746   closedir($dir);
1747   return rmdir($path);
1750 function scan_directory($path,$sort_desc=false)
1752   $ret = false;
1754   /* is this a dir ? */
1755   if(is_dir($path)) {
1757     /* is this path a readable one */
1758     if(is_readable($path)){
1760       /* Get contents and write it into an array */   
1761       $ret = array();    
1763       $dir = opendir($path);
1765       /* Is this a correct result ?*/
1766       if($dir){
1767         while($fp = readdir($dir))
1768           $ret[]= $fp;
1769       }
1770     }
1771   }
1772   /* Sort array ascending , like scandir */
1773   sort($ret);
1775   /* Sort descending if parameter is sort_desc is set */
1776   if($sort_desc) {
1777     $ret = array_reverse($ret);
1778   }
1780   return($ret);
1783 function clean_smarty_compile_dir($directory)
1785   global $svn_revision;
1787   if(is_dir($directory) && is_readable($directory)) {
1788     // Set revision filename to REVISION
1789     $revision_file= $directory."/REVISION";
1791     /* Is there a stamp containing the current revision? */
1792     if(!file_exists($revision_file)) {
1793       // create revision file
1794       create_revision($revision_file, $svn_revision);
1795     } else {
1796 # check for "$config->...['CONFIG']/revision" and the
1797 # contents should match the revision number
1798       if(!compare_revision($revision_file, $svn_revision)){
1799         // If revision differs, clean compile directory
1800         foreach(scan_directory($directory) as $file) {
1801           if(($file==".")||($file=="..")) continue;
1802           if( is_file($directory."/".$file) &&
1803               is_writable($directory."/".$file)) {
1804             // delete file
1805             if(!unlink($directory."/".$file)) {
1806               print_red("File ".$directory."/".$file." could not be deleted.");
1807               // This should never be reached
1808             }
1809           } elseif(is_dir($directory."/".$file) &&
1810               is_writable($directory."/".$file)) {
1811             // Just recursively delete it
1812             rmdirRecursive($directory."/".$file);
1813           }
1814         }
1815         // We should now create a fresh revision file
1816         clean_smarty_compile_dir($directory);
1817       } else {
1818         // Revision matches, nothing to do
1819       }
1820     }
1821   } else {
1822     // Smarty compile dir is not accessible
1823     // (Smarty will warn about this)
1824   }
1827 function create_revision($revision_file, $revision)
1829   $result= false;
1831   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1832     if($fh= fopen($revision_file, "w")) {
1833       if(fwrite($fh, $revision)) {
1834         $result= true;
1835       }
1836     }
1837     fclose($fh);
1838   } else {
1839     print_red("Can not write to revision file");
1840   }
1842   return $result;
1845 function compare_revision($revision_file, $revision)
1847   // false means revision differs
1848   $result= false;
1850   if(file_exists($revision_file) && is_readable($revision_file)) {
1851     // Open file
1852     if($fh= fopen($revision_file, "r")) {
1853       // Compare File contents with current revision
1854       if($revision == fread($fh, filesize($revision_file))) {
1855         $result= true;
1856       }
1857     } else {
1858       print_red("Can not open revision file");
1859     }
1860     // Close file
1861     fclose($fh);
1862   }
1864   return $result;
1867 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1869   $str = ""; // Our return value will be saved in this var
1871   $color  = dechex($percentage+150);
1872   $color2 = dechex(150 - $percentage);
1873   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1875   $progress = (int)(($percentage /100)*$width);
1877   /* Abort printing out percentage, if divs are to small */
1880   /* If theres a better solution for this, use it... */
1881   $str = "
1882     <div style=\" width:".($width)."px; 
1883     height:".($height)."px;
1884   background-color:#000000;
1885 padding:1px;\">
1887           <div style=\" width:".($width)."px;
1888         background-color:#$bgcolor;
1889 height:".($height)."px;\">
1891          <div style=\" width:".$progress."px;
1892 height:".$height."px;
1893        background-color:#".$color2.$color2.$color."; \">";
1896        if(($height >10)&&($showvalue)){
1897          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1898            <b>".$percentage."%</b>
1899            </font>";
1900        }
1902        $str.= "</div></div></div>";
1904        return($str);
1908 function array_key_ics($ikey, $items)
1910   /* Gather keys, make them lowercase */
1911   $tmp= array();
1912   foreach ($items as $key => $value){
1913     $tmp[strtolower($key)]= $key;
1914   }
1916   if (isset($tmp[strtolower($ikey)])){
1917     return($tmp[strtolower($ikey)]);
1918   }
1920   return ("");
1924 function search_config($arr, $name, $return)
1926   if (is_array($arr)){
1927     foreach ($arr as $a){
1928       if (isset($a['CLASS']) &&
1929           strtolower($a['CLASS']) == strtolower($name)){
1931         if (isset($a[$return])){
1932           return ($a[$return]);
1933         } else {
1934           return ("");
1935         }
1936       } else {
1937         $res= search_config ($a, $name, $return);
1938         if ($res != ""){
1939           return $res;
1940         }
1941       }
1942     }
1943   }
1944   return ("");
1948 function array_differs($src, $dst)
1950   /* If the count is differing, the arrays differ */
1951   if (count ($src) != count ($dst)){
1952     return (TRUE);
1953   }
1955   /* So the count is the same - lets check the contents */
1956   $differs= FALSE;
1957   foreach($src as $value){
1958     if (!in_array($value, $dst)){
1959       $differs= TRUE;
1960     }
1961   }
1963   return ($differs);
1967 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1968 ?>