Code

Added warnings.
[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/");
25 /* Define globals for revision comparing */
26 $svn_path = '$HeadURL$';
27 $svn_revision = '$Revision$';
29 /* Include required files */
30 require_once ("class_ldap.inc");
31 require_once ("class_config.inc");
32 require_once ("class_userinfo.inc");
33 require_once ("class_plugin.inc");
34 require_once ("class_pluglist.inc");
35 require_once ("class_tabs.inc");
36 require_once ("class_mail-methods.inc");
37 require_once("class_password-methods.inc");
38 require_once ("debuglib.inc");
40 /* Define constants for debugging */
41 define ("DEBUG_TRACE",   1);
42 define ("DEBUG_LDAP",    2);
43 define ("DEBUG_MYSQL",   4);
44 define ("DEBUG_SHELL",   8);
45 define ("DEBUG_POST",   16);
46 define ("DEBUG_SESSION",32);
47 define ("DEBUG_CONFIG", 64);
49 /* Rewrite german 'umlauts' and spanish 'accents'
50    to get better results */
51 $REWRITE= array( "ä" => "ae",
52     "ö" => "oe",
53     "ü" => "ue",
54     "Ä" => "Ae",
55     "Ö" => "Oe",
56     "Ü" => "Ue",
57     "ß" => "ss",
58     "á" => "a",
59     "é" => "e",
60     "í" => "i",
61     "ó" => "o",
62     "ú" => "u",
63     "Á" => "A",
64     "É" => "E",
65     "Í" => "I",
66     "Ó" => "O",
67     "Ú" => "U",
68     "ñ" => "ny",
69     "Ñ" => "Ny" );
72 /* Function to include all class_ files starting at a
73    given directory base */
74 function get_dir_list($folder= ".")
75 {
76   $currdir=getcwd();
77   if ($folder){
78     chdir("$folder");
79   }
81   $dh = opendir(".");
82   while(false !== ($file = readdir($dh))){
84     /* Recurse through all "common" directories */
85     if(is_dir($file) && $file!="." && $file!=".." && $file!="CVS"){
86       get_dir_list($file);
87       continue;
88     }
90     /* Include existing class_ files */
91     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
92       require_once($file);
93     }
94   }
96   closedir($dh);
97   chdir($currdir);
98 }
101 /* Create seed with microseconds */
102 function make_seed() {
103   list($usec, $sec) = explode(' ', microtime());
104   return (float) $sec + ((float) $usec * 100000);
108 /* Debug level action */
109 function DEBUG($level, $line, $function, $file, $data, $info="")
111   if ($_SESSION['DEBUGLEVEL'] & $level){
112     $output= "DEBUG[$level] ";
113     if ($function != ""){
114       $output.= "($file:$function():$line) - $info: ";
115     } else {
116       $output.= "($file:$line) - $info: ";
117     }
118     echo $output;
119     if (is_array($data)){
120       print_a($data);
121     } else {
122       echo "'$data'";
123     }
124     echo "<br>";
125   }
129 /* Simple function to get browser language and convert it to
130    xx_XY needed by locales. Ignores sublanguages and weights. */
131 function get_browser_language()
133   global $BASE_DIR;
135   /* Get list of languages */
136   if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
137     $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
138     $languages= split (',', $lang);
139     $languages[]= "C";
140   } else {
141     $languages= array("C");
142   }
144   /* Walk through languages and get first supported */
145   foreach ($languages as $val){
147     /* Strip off weight */
148     $lang= preg_replace("/;q=.*$/i", "", $val);
150     /* Simplify sub language handling */
151     $lang= preg_replace("/-.*$/", "", $lang);
153     /* Cancel loop if available in GOsa, or the last
154        entry has been reached */
155     if (is_dir("$BASE_DIR/locale/$lang")){
156       break;
157     }
158   }
160   return (strtolower($lang)."_".strtoupper($lang));
164 /* Rewrite ui object to another dn */
165 function change_ui_dn($dn, $newdn)
167   $ui= $_SESSION['ui'];
168   if ($ui->dn == $dn){
169     $ui->dn= $newdn;
170     $_SESSION['ui']= $ui;
171   }
175 /* Return theme path for specified file */
176 function get_template_path($filename= '', $plugin= FALSE, $path= "")
178   global $config, $BASE_DIR;
180   if (!isset($config->data['MAIN']['THEME'])){
181     $theme= 'default';
182   } else {
183     $theme= $config->data['MAIN']['THEME'];
184   }
186   /* Return path for empty filename */
187   if ($filename == ''){
188     return ("themes/$theme/");
189   }
191   /* Return plugin dir or root directory? */
192   if ($plugin){
193     if ($path == ""){
194       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
195     } else {
196       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
197     }
198     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
199       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
200     }
201     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
202       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
203     }
204     if ($path == ""){
205       return ($_SESSION['plugin_dir']."/$filename");
206     } else {
207       return ($path."/$filename");
208     }
209   } else {
210     if (file_exists("themes/$theme/$filename")){
211       return ("themes/$theme/$filename");
212     }
213     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
214       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
215     }
216     if (file_exists("themes/default/$filename")){
217       return ("themes/default/$filename");
218     }
219     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
220       return ("$BASE_DIR/ihtml/themes/default/$filename");
221     }
222     return ($filename);
223   }
227 function array_remove_entries($needles, $haystack)
229   $tmp= array();
231   /* Loop through entries to be removed */
232   foreach ($haystack as $entry){
233     if (!in_array($entry, $needles)){
234       $tmp[]= $entry;
235     }
236   }
238   return ($tmp);
242 function gosa_log ($message)
244   global $ui;
246   /* Preset to something reasonable */
247   $username= " unauthenticated";
249   /* Replace username if object is present */
250   if (isset($ui)){
251     if ($ui->username != ""){
252       $username= "[$ui->username]";
253     } else {
254       $username= "unknown";
255     }
256   }
258   syslog(LOG_INFO,"GOsa$username: $message");
262 function ldap_init ($server, $base, $binddn='', $pass='')
264   global $config;
266   $ldap = new LDAP ($binddn, $pass, $server, isset($config->current['RECURSIVE'])                                                && $config->current['RECURSIVE'] == "true",
267       isset($config->current['TLS']) && $config->current['TLS'] == "true");
269   /* Sadly we've no proper return values here. Use the error message instead. */
270   if (!preg_match("/Success/i", $ldap->error)){
271     print_red(sprintf(_("Error when connecting the LDAP. Server said '%s'."),
272           $ldap->get_error()));
273     echo $_SESSION['errors'];
275     /* Hard error. We'd like to use the LDAP, anyway... */
276     exit;
277   }
279   /* Preset connection base to $base and return to caller */
280   $ldap->cd ($base);
281   return $ldap;
285 function ldap_login_user ($username, $password)
287   global $config;
289   /* look through the entire ldap */
290   $ldap = $config->get_ldap_link();
291   if (!preg_match("/Success/i", $ldap->error)){
292     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
293     echo $_SESSION['errors'];
294     exit;
295   }
296   $ldap->cd($config->current['BASE']);
297   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
299   /* get results, only a count of 1 is valid */
300   switch ($ldap->count()){
302     /* user not found */
303     case 0:     return (NULL);
304             break;
306             /* valid uniq user */
307     case 1: 
308             break;
310             /* found more than one matching id */
311     default:
312             print_red(_("Username / UID is not unique. Please check your LDAP database."));
313             return (NULL);
314   }
316   /* LDAP schema is not case sensitive. Perform additional check. */
317   $attrs= $ldap->fetch();
318   if ($attrs['uid'][0] != $username){
319     return(NULL);
320   }
322   /* got user dn, fill acl's */
323   $ui= new userinfo($config, $ldap->getDN());
324   $ui->username= $username;
326   /* password check, bind as user with supplied password  */
327   $ldap->disconnect();
328   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
329       isset($config->current['RECURSIVE']) &&
330       $config->current['RECURSIVE'] == "true",
331       isset($config->current['TLS'])
332       && $config->current['TLS'] == "true");
333   if (!preg_match("/Success/i", $ldap->error)){
334     return (NULL);
335   }
337   /* Username is set, load subtreeACL's now */
338   $ui->loadACL();
340   return ($ui);
344 function add_lock ($object, $user)
346   global $config;
348   /* Just a sanity check... */
349   if ($object == "" || $user == ""){
350     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
351     return;
352   }
354   /* Check for existing entries in lock area */
355   $ldap= $config->get_ldap_link();
356   $ldap->cd ($config->current['CONFIG']);
357   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=$object))",
358       array("gosaUser"));
359   if (!preg_match("/Success/i", $ldap->error)){
360     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()));
361     return;
362   }
364   /* Add lock if none present */
365   if ($ldap->count() == 0){
366     $attrs= array();
367     $name= md5($object);
368     $ldap->cd("cn=$name,".$config->current['CONFIG']);
369     $attrs["objectClass"] = "gosaLockEntry";
370     $attrs["gosaUser"] = $user;
371     $attrs["gosaObject"] = $object;
372     $attrs["cn"] = "$name";
373     $ldap->add($attrs);
374     if (!preg_match("/Success/i", $ldap->error)){
375       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
376             $ldap->get_error()));
377       return;
378     }
379   }
383 function del_lock ($object)
385   global $config;
387   /* Sanity check */
388   if ($object == ""){
389     return;
390   }
392   /* Check for existance and remove the entry */
393   $ldap= $config->get_ldap_link();
394   $ldap->cd ($config->current['CONFIG']);
395   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=$object))", array("gosaObject"));
396   $attrs= $ldap->fetch();
397   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
398     $ldap->rmdir ($ldap->getDN());
400     if (!preg_match("/Success/i", $ldap->error)){
401       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
402             $ldap->get_error()));
403       return;
404     }
405   }
409 function del_user_locks($userdn)
411   global $config;
413   /* Get LDAP ressources */ 
414   $ldap= $config->get_ldap_link();
415   $ldap->cd ($config->current['CONFIG']);
417   /* Remove all objects of this user, drop errors silently in this case. */
418   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
419   while ($attrs= $ldap->fetch()){
420     $ldap->rmdir($attrs['dn']);
421   }
425 function get_lock ($object)
427   global $config;
429   /* Sanity check */
430   if ($object == ""){
431     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
432     return("");
433   }
435   /* Get LDAP link, check for presence of the lock entry */
436   $user= "";
437   $ldap= $config->get_ldap_link();
438   $ldap->cd ($config->current['CONFIG']);
439   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=$object))", array("gosaUser"));
440   if (!preg_match("/Success/i", $ldap->error)){
441     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
442     return("");
443   }
445   /* Check for broken locking information in LDAP */
446   if ($ldap->count() > 1){
448     /* Hmm. We're removing broken LDAP information here and issue a warning. */
449     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
451     /* Clean up these references now... */
452     while ($attrs= $ldap->fetch()){
453       $ldap->rmdir($attrs['dn']);
454     }
456     return("");
458   } elseif ($ldap->count() == 1){
459     $attrs = $ldap->fetch();
460     $user= $attrs['gosaUser'][0];
461   }
463   return ($user);
467 function get_list($subtreeACL, $filter, $subsearch= TRUE, $base="", $attrs= array(), $flag= FALSE)
469   global $config;
471   /* Base the search on default base if not set */
472   $ldap= $config->get_ldap_link($flag);
473   if ($base == ""){
474     $ldap->cd ($config->current['BASE']);
475   } else {
476     $ldap->cd ($base);
477   }
479   /* Perform ONE or SUB scope searches? */
480   if ($subsearch) {
481     $ldap->search ($filter, $attrs);
482   } else {
483     $ldap->ls ($filter);
484   }
486   /* Check for size limit exceeded messages for GUI feedback */
487   if (preg_match("/size limit/i", $ldap->error)){
488     $_SESSION['limit_exceeded']= TRUE;
489   } else {
490     $_SESSION['limit_exceeded']= FALSE;
491   }
493   /* Crawl through reslut entries and perform the migration to the
494      result array */
495   $result= array();
496   while($attrs = $ldap->fetch()) {
497     $dn= preg_replace("/[ ]*,[ ]*/", ",", $ldap->getDN());
498     foreach ($subtreeACL as $key => $value){
499       if (preg_match("/$key/", $dn)){
500         $attrs["dn"]= $dn;
501         $result[]= $attrs;
502         break;
503       }
504     }
505   }
507   return ($result);
511 function check_sizelimit()
513   /* Ignore dialog? */
514   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
515     return ("");
516   }
518   /* Eventually show dialog */
519   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
520     $smarty= get_smarty();
521     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
522           $_SESSION['size_limit']));
523     $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).'">'));
524     return($smarty->fetch(get_template_path('sizelimit.tpl')));
525   }
527   return ("");
531 function print_sizelimit_warning()
533   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
534       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
535     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
536   } else {
537     $config= "";
538   }
539   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
540     return ("("._("incomplete").") $config");
541   }
542   return ("");
546 function eval_sizelimit()
548   if (isset($_POST['set_size_action'])){
550     /* User wants new size limit? */
551     if (is_id($_POST['new_limit']) &&
552         isset($_POST['action']) && $_POST['action']=="newlimit"){
554       $_SESSION['size_limit']= validate($_POST['new_limit']);
555       $_SESSION['size_ignore']= FALSE;
556     }
558     /* User wants no limits? */
559     if (isset($_POST['action']) && $_POST['action']=="ignore"){
560       $_SESSION['size_limit']= 0;
561       $_SESSION['size_ignore']= TRUE;
562     }
564     /* User wants incomplete results */
565     if (isset($_POST['action']) && $_POST['action']=="limited"){
566       $_SESSION['size_ignore']= TRUE;
567     }
568   }
570   /* Allow fallback to dialog */
571   if (isset($_POST['edit_sizelimit'])){
572     $_SESSION['size_ignore']= FALSE;
573   }
577 function get_permissions ($dn, $subtreeACL)
579   global $config;
581   $base= $config->current['BASE'];
582   $tmp= "d,".$dn;
583   $sacl= array();
585   /* Sort subacl's for lenght to simplify matching
586      for subtrees */
587   foreach ($subtreeACL as $key => $value){
588     $sacl[$key]= strlen($key);
589   }
590   arsort ($sacl);
591   reset ($sacl);
593   /* Successively remove leading parts of the dn's until
594      it doesn't contain commas anymore */
595   while (preg_match('/,/', $tmp)){
596     $tmp= ltrim(strstr($tmp, ","), ",");
598     /* Check for acl that may apply */
599     foreach ($sacl as $key => $value){
600       if (preg_match("/$key$/", $tmp)){
601         return ($subtreeACL[$key]);
602       }
603     }
604   }
606   return array("");
610 function get_module_permission($acl_array, $module, $dn)
612   global $ui;
614   $final= "";
615   foreach($acl_array as $acl){
617     /* Check for selfflag (!) in ACL to determine if
618        the user is allowed to change parts of his/her
619        own account */
620     if (preg_match("/^!/", $acl)){
621       if ($dn != "" && $dn != $ui->dn){
623         /* No match for own DN, give up on this ACL */
624         continue;
626       } else {
628         /* Matches own DN, remove the selfflag */
629         $acl= preg_replace("/^!/", "", $acl);
631       }
632     }
634     /* Remove leading garbage */
635     $acl= preg_replace("/^:/", "", $acl);
637     /* Discover if we've access to the submodule by comparing
638        all allowed submodules specified in the ACL */
639     $tmp= split(",", $acl);
640     foreach ($tmp as $mod){
641       if (preg_match("/$module#/", $mod)){
642         $final= strstr($mod, "#")."#";
643         continue;
644       }
645       if (preg_match("/[^#]$module$/", $mod)){
646         return ("#all#");
647       }
648       if (preg_match("/^all$/", $mod)){
649         return ("#all#");
650       }
651     }
652   }
654   /* Return assembled ACL, or none */
655   if ($final != ""){
656     return (preg_replace('/##/', '#', $final));
657   }
659   /* Nothing matches - disable access for this object */
660   return ("#none#");
664 function get_userinfo()
666   global $ui;
668   return $ui;
672 function get_smarty()
674   global $smarty;
676   return $smarty;
680 function convert_department_dn($dn)
682   $dep= "";
684   /* Build a sub-directory style list of the tree level
685      specified in $dn */
686   foreach (split (",", $dn) as $val){
688     /* We're only interested in organizational units... */
689     if (preg_match ("/ou=/", $val)){
690       $dep= preg_replace("/ou=([^,]+)/", "\\1", $val)."/$dep";
691     }
693     /* ... and location objects */
694     if (preg_match ("/l=/", $val)){
695       $dep= preg_replace("/l=([^,]+)/", "\\1", $val)."/$dep";
696     }
697   }
699   /* Return and remove accidently trailing slashes */
700   return rtrim($dep, "/");
704 function get_ou($name)
706   global $config;
708   $ou= $config->current[$name];
709   if ($ou != ""){
710     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
711       return "ou=$ou,";
712     } else {
713       return "$ou,";
714     }
715   } else {
716     return "";
717   }
721 function get_people_ou()
723   return (get_ou("PEOPLE"));
727 function get_groups_ou()
729   return (get_ou("GROUPS"));
733 function get_winstations_ou()
735   return (get_ou("WINSTATIONS"));
739 function get_base_from_people($dn)
741   global $config;
743   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
744   $base= preg_replace($pattern, '', $dn);
746   /* Set to base, if we're not on a correct subtree */
747   if (!isset($config->idepartments[$base])){
748     $base= $config->current['BASE'];
749   }
751   return ($base);
755 function get_departments($ignore_dn= "")
757   global $config;
759   /* Initialize result hash */
760   $result= array();
761   $result['/']= $config->current['BASE'];
763   /* Get list of department objects */
764   $ldap= $config->get_ldap_link();
765   $ldap->cd ($config->current['BASE']);
766   $ldap->search ("(objectClass=gosaDepartment)", array("ou"));
767   while ($attrs= $ldap->fetch()){
768     $dn= $ldap->getDN();
769     if ($dn == $ignore_dn){
770       continue;
771     }
772     $result[convert_department_dn($dn)]= $dn;
773   }
775   return ($result);
779 function chkacl($acl, $name)
781   /* Look for attribute in ACL */
782   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
783     return ("");
784   }
786   /* Optically disable html object for no match */
787   return (" disabled ");
791 function is_phone_nr($nr)
793   if ($nr == ""){
794     return (TRUE);
795   }
797   return preg_match ("/^[0-9 ()+*-]+$/", $nr);
801 function is_url($url)
803   if ($url == ""){
804     return (TRUE);
805   }
807   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
811 function is_dn($dn)
813   if ($dn == ""){
814     return (TRUE);
815   }
817   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
821 function is_uid($uid)
823   global $config;
825   if ($uid == ""){
826     return (TRUE);
827   }
829   /* STRICT adds spaces and case insenstivity to the uid check.
830      This is dangerous and should not be used. */
831   if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
832     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
833   } else {
834     return preg_match ("/^[a-z0-9_-]+$/", $uid);
835   }
839 function is_id($id)
841   if ($id == ""){
842     return (FALSE);
843   }
845   return preg_match ("/^[0-9]+$/", $id);
849 function is_path($path)
851   if ($path == ""){
852     return (TRUE);
853   }
854   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
855     return (FALSE);
856   }
858   return preg_match ("/\/.+$/", $path);
862 function is_email($address, $template= FALSE)
864   if ($address == ""){
865     return (TRUE);
866   }
867   if ($template){
868     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
869         $address);
870   } else {
871     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
872         $address);
873   }
877 function print_red()
879   /* Check number of arguments */
880   if (func_num_args() < 1){
881     return;
882   }
884   /* Get arguments, save string */
885   $array = func_get_args();
886   $string= $array[0];
888   /* Step through arguments */
889   for ($i= 1; $i<count($array); $i++){
890     $string= preg_replace ("/%s/", $array[$i], $string, 1);
891   }
893   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
894      the other case... */
895   if (isset($_SESSION['DEBUGLEVEL'])){
896     $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
897       "border-style:solid;border-color:red; background-color:black;".
898       "margin-bottom:10px; padding:8px;\"><table><tr><td><img alt=\"\" src=\"".
899       get_template_path('images/warning.png')."\"></td>".
900       "<td width=\"100%\" align=\"center\"><font color=\"#FFFFFF\">".
901       "<b style='font-size:16px;'>$string</b></font></td><td>".
902       "<img alt=\"\"src=\"".get_template_path('images/warning.png').
903       "\"></td></tr></table></div>\n";
904   } else {
905     echo "Error: $string\n";
906   }
910 function gen_locked_message($user, $dn)
912   global $plug, $config;
914   $_SESSION['dn']= $dn;
915   $ldap= $config->get_ldap_link();
916   $ldap->cat ($user);
917   $attrs= $ldap->fetch();
918   $uid= $attrs["uid"][0];
920   /* Prepare and show template */
921   $smarty= get_smarty();
922   $smarty->assign ("dn", $dn);
923   $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>"));
925   return ($smarty->fetch (get_template_path('islocked.tpl')));
929 function to_string ($value)
931   /* If this is an array, generate a text blob */
932   if (is_array($value)){
933     $ret= "";
934     foreach ($value as $line){
935       $ret.= $line."<br>\n";
936     }
937     return ($ret);
938   } else {
939     return ($value);
940   }
944 function get_printer_list($cups_server)
946   global $config;
948   $res= array();
950   /* Use CUPS, if we've access to it */
951   if (function_exists('cups_get_dest_list')){
952     $dest_list= cups_get_dest_list ($cups_server);
954     foreach ($dest_list as $prt){
955       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
957       foreach ($attr as $prt_info){
958         if ($prt_info->name == "printer-info"){
959           $info= $prt_info->value;
960           break;
961         }
962       }
963       $res[$prt->name]= "$info [$prt->name]";
964     }
966     /* CUPS is not available, try lpstat as a replacement */
967   } else {
968     unset ($ar);
969     exec("lpstat -p", $ar);
970     foreach($ar as $val){
971       list($dummy, $printer, $rest)= split(' ', $val, 3);
972       if (preg_match('/^[^@]+$/', $printer)){
973         $res[$printer]= "$printer";
974       }
975     }
976   }
978   /* Merge in printers from LDAP */
979   $ldap= $config->get_ldap_link();
980   $ldap->cd ($config->current['BASE']);
981   $ldap->search('(objectClass=gotoPrinter)', array('cn'));
982   while ($attrs= $ldap->fetch()){
983     $res[$attrs["cn"][0]]= $attrs["cn"][0];
984   }
986   return $res;
990 function sess_del ($var)
992   /* New style */
993   unset ($_SESSION[$var]);
995   /* ... work around, since the first one
996      doesn't seem to work all the time */
997   session_unregister ($var);
1001 function show_errors($message)
1003   $complete= "";
1005   /* Assemble the message array to a plain string */
1006   foreach ($message as $error){
1007     if ($complete == ""){
1008       $complete= $error;
1009     } else {
1010       $complete= "$error<br>$complete";
1011     }
1012   }
1014   /* Fill ERROR variable with nice error dialog */
1015   print_red($complete);
1019 function show_ldap_error($message)
1021   if (!preg_match("/Success/i", $message)){
1022     print_red (_("LDAP error:")." $message");
1023     return TRUE;
1024   } else {
1025     return FALSE;
1026   }
1030 function rewrite($s)
1032   global $REWRITE;
1034   foreach ($REWRITE as $key => $val){
1035     $s= preg_replace("/$key/", "$val", $s);
1036   }
1038   return ($s);
1042 function dn2base($dn)
1044   global $config;
1046   if (get_people_ou() != ""){
1047     $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1048   }
1049   if (get_groups_ou() != ""){
1050     $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1051   }
1052   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1054   return ($base);
1059 function check_command($cmdline)
1061   $cmd= preg_replace("/ .*$/", "", $cmdline);
1063   /* Check if command exists in filesystem */
1064   if (!file_exists($cmd)){
1065     return (FALSE);
1066   }
1068   /* Check if command is executable */
1069   if (!is_executable($cmd)){
1070     return (FALSE);
1071   }
1073   return (TRUE);
1077 function print_header($image, $headline, $info= "")
1079   $display= "<div class=\"plugtop\">\n";
1080   $display.= "  <img src=\"$image\" align=\"middle\" alt=\"*\">&nbsp;$headline\n";
1081   $display.= "</div>\n";
1083   if ($info != ""){
1084     $display.= "<div class=\"pluginfo\">\n";
1085     $display.= "$info";
1086     $display.= "</div>\n";
1087   } else {
1088     $display.= "<div style=\"height:5px;\">\n";
1089     $display.= "&nbsp;";
1090     $display.= "</div>\n";
1091   }
1093   return ($display);
1097 function register_global($name, $object)
1099   $_SESSION[$name]= $object;
1103 function is_global($name)
1105   return isset($_SESSION[$name]);
1109 function get_global($name)
1111   return $_SESSION[$name];
1115 function range_selector($dcnt,$start,$range=25)
1118   /* Entries shown left and right from the selected entry */
1119   $max_entries= 10;
1121   /* Initialize and take care that max_entries is even */
1122   $output="";
1123   if ($max_entries & 1){
1124     $max_entries++;
1125   }
1127   /* Prevent output to start or end out of range */
1128   if ($start < 0 ){
1129     $start= 0 ;
1130   }
1131   if ($start >= $dcnt){
1132     $start= $range * (int)(($dcnt / $range) + 0.5);
1133   }
1135   $numpages= (($dcnt / $range));
1136   if(((int)($numpages))!=($numpages))
1137     $numpages = (int)$numpages + 1;
1138   $ppage= (int)(($start / $range) + 0.5);
1141   /* Align selected page to +/- max_entries/2 */
1142   $begin= $ppage - $max_entries/2;
1143   $end= $ppage + $max_entries/2;
1145   /* Adjust begin/end, so that the selected value is somewhere in
1146      the middle and the size is max_entries if possible */
1147   if ($begin < 0){
1148     $end-= $begin + 1;
1149     $begin= 0;
1150   }
1151   if ($end > $numpages) {
1152     $end= $numpages;
1153   }
1154   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1155     $begin= $end - $max_entries;
1156   }
1158   /* Draw decrement */
1159   if ($start > 0 ) {
1160     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1161       (($start-$range))."\">".
1162       "<img alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1163   }
1165   /* Draw pages */
1166   for ($i= $begin; $i < $end; $i++) {
1167     if ($ppage == $i){
1168       $output.= "<a style=\"background-color:#D0D0D0;\" href=\"main.php?plug=".
1169         validate($_GET['plug'])."&amp;start=".
1170         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1171     } else {
1172       $output.= "<a href=\"main.php?plug=".validate($_GET['plug']).
1173         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1174     }
1175   }
1177   /* Draw increment */
1178   if($start < ($dcnt-$range)) {
1179     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1180       (($start+($range)))."\">".
1181       "<img alt=\"\" src=\"images/forward.png\" border=0 align=\"middle\"></a>";
1182   }
1184   return($output);
1188 function apply_filter()
1190   $apply= "";
1192   $apply= ''.
1193     '<table width="100%"  style="border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1194     '<input type="submit" name="apply" value="'._("Apply").'"></td></tr></table>';
1196   return ($apply);
1200 function back_to_main()
1202   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1203     _("Back").'"></p><input type="hidden" name="ignore">';
1205   return ($string);
1209 function normalize_netmask($netmask)
1211   /* Check for notation of netmask */
1212   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1213     $num= (int)($netmask);
1214     $netmask= "";
1216     for ($byte= 0; $byte<4; $byte++){
1217       $result=0;
1219       for ($i= 7; $i>=0; $i--){
1220         if ($num-- > 0){
1221           $result+= pow(2,$i);
1222         }
1223       }
1225       $netmask.= $result.".";
1226     }
1228     return (preg_replace('/\.$/', '', $netmask));
1229   }
1231   return ($netmask);
1235 function netmask_to_bits($netmask)
1237   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1238   $res= 0;
1240   for ($n= 0; $n<4; $n++){
1241     $start= 255;
1242     $name= "nm$n";
1244     for ($i= 0; $i<8; $i++){
1245       if ($start == (int)($$name)){
1246         $res+= 8 - $i;
1247         break;
1248       }
1249       $start-= pow(2,$i);
1250     }
1251   }
1253   return ($res);
1257 function recurse($rule, $variables)
1259   $result= array();
1261   if (!count($variables)){
1262     return array($rule);
1263   }
1265   reset($variables);
1266   $key= key($variables);
1267   $val= current($variables);
1268   unset ($variables[$key]);
1270   foreach($val as $possibility){
1271     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1272     $result= array_merge($result, recurse($nrule, $variables));
1273   }
1275   return ($result);
1279 function expand_id($rule, $attributes)
1281   /* Check for id rule */
1282   if(preg_match('/^id(:|#)\d+$/',$rule)){
1283     return (array("\{$rule}"));
1284   }
1286   /* Check for clean attribute */
1287   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1288     $rule= preg_replace('/^%/', '', $rule);
1289     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1290     return (array($val));
1291   }
1293   /* Check for attribute with parameters */
1294   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1295     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1296     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1297     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1298     $start= preg_replace ('/-.*$/', '', $param);
1299     $stop = preg_replace ('/^[^-]+-/', '', $param);
1301     /* Assemble results */
1302     $result= array();
1303     for ($i= $start; $i<= $stop; $i++){
1304       $result[]= substr($val, 0, $i);
1305     }
1306     return ($result);
1307   }
1309   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1310   return (array($rule));
1314 function gen_uids($rule, $attributes)
1316   global $config;
1318   /* Search for keys and fill the variables array with all 
1319      possible values for that key. */
1320   $part= "";
1321   $trigger= false;
1322   $stripped= "";
1323   $variables= array();
1325   for ($pos= 0; $pos < strlen($rule); $pos++){
1327     if ($rule[$pos] == "{" ){
1328       $trigger= true;
1329       $part= "";
1330       continue;
1331     }
1333     if ($rule[$pos] == "}" ){
1334       $variables[$pos]= expand_id($part, $attributes);
1335       $stripped.= "\{$pos}";
1336       $trigger= false;
1337       continue;
1338     }
1340     if ($trigger){
1341       $part.= $rule[$pos];
1342     } else {
1343       $stripped.= $rule[$pos];
1344     }
1345   }
1347   /* Recurse through all possible combinations */
1348   $proposed= recurse($stripped, $variables);
1350   /* Get list of used ID's */
1351   $used= array();
1352   $ldap= $config->get_ldap_link();
1353   $ldap->cd($config->current['BASE']);
1354   $ldap->search('(uid=*)');
1356   while($attrs= $ldap->fetch()){
1357     $used[]= $attrs['uid'][0];
1358   }
1360   /* Remove used uids and watch out for id tags */
1361   $ret= array();
1362   foreach($proposed as $uid){
1364     /* Check for id tag and modify uid if needed */
1365     if(preg_match('/\{id:\d+}/',$uid)){
1366       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1368       for ($i= 0; $i < pow(10,$size); $i++){
1369         $number= sprintf("%0".$size."d", $i);
1370         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1371         if (!in_array($res, $used)){
1372           $uid= $res;
1373           break;
1374         }
1375       }
1376     }
1378     if(preg_match('/\{id#\d+}/',$uid)){
1379       $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1381       while (true){
1382         mt_srand((double) microtime()*1000000);
1383         $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1384         $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1385         if (!in_array($res, $used)){
1386           $uid= $res;
1387           break;
1388         }
1389       }
1390     }
1392     /* Don't assign used ones */
1393     if (!in_array($uid, $used)){
1394       $ret[]= $uid;
1395     }
1396   }
1398   return(array_unique($ret));
1402 function array_search_r($needle, $key, $haystack){
1404   foreach($haystack as $index => $value){
1405     $match= 0;
1407     if (is_array($value)){
1408       $match= array_search_r($needle, $key, $value);
1409     }
1411     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1412       $match=1;
1413     }
1415     if ($match){
1416       return 1;
1417     }
1418   }
1420   return 0;
1421
1424 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1425    Need to convert... */
1426 function to_byte($value) {
1427   $value= strtolower(trim($value));
1429   if(!is_numeric(substr($value, -1))) {
1431     switch(substr($value, -1)) {
1432       case 'g':
1433         $mult= 1073741824;
1434         break;
1435       case 'm':
1436         $mult= 1048576;
1437         break;
1438       case 'k':
1439         $mult= 1024;
1440         break;
1441     }
1443     return ($mult * (int)substr($value, 0, -1));
1444   } else {
1445     return $value;
1446   }
1450 function in_array_ics($value, $items)
1452   if (!is_array($items)){
1453     return (FALSE);
1454   }
1455   
1456   foreach ($items as $item){
1457     if (strtolower($item) == strtolower($value)) {
1458       return (TRUE);
1459     }
1460   }
1462   return (FALSE);
1463
1466 function generate_alphabet($count= 10)
1468   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1469   $alphabet= "";
1470   $c= 0;
1472   /* Fill cells with charaters */
1473   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1474     if ($c == 0){
1475       $alphabet.= "<tr>";
1476     }
1478     $ch = mb_substr($characters, $i, 1, "UTF8");
1479     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1480       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1482     if ($c++ == $count){
1483       $alphabet.= "</tr>";
1484       $c= 0;
1485     }
1486   }
1488   /* Fill remaining cells */
1489   while ($c++ <= $count){
1490     $alphabet.= "<td>&nbsp;</td>";
1491   }
1493   return ($alphabet);
1497 function validate($string)
1499   return (strip_tags(preg_replace('/\0/', '', $string)));
1502 function get_gosa_version()
1504   global $svn_revision, $svn_path;
1506   /* Extract informations */
1507   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1509   /* Release or development? */
1510   if (preg_match('%/gosa/trunk/%', $svn_path)){
1511     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1512   } else {
1513     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1514     return (sprintf(_("GOsa $release"), $revision));
1515   }
1518 function gosaRaiseError($errno, $errstr, $errfile, $errline)
1520   global $error_collector;
1522   /* Return if error reporting is set to zero */
1523   if (error_reporting() == 0){
1524     return;
1525   }
1527   /* Workaround for buggy imap_open error outputs */
1528   if (preg_match('/imap_open/', $errstr)){
1529     return;
1530   }
1532   /* FIXME: Workaround for PHP5 error message flooding. The new OOM
1533      code want's us to use public/protected/private instead of flat
1534      var declarations. For now I can't workaround this - let's ignore
1535      the messages till the next major release which may drop support
1536      for PHP4. */
1537   if (preg_match('/var: Deprecated./', $errstr)){
1538     return;
1539   }
1541   /* FIXME: Same as above. Compatibility does error flooding.*/
1542   if (preg_match('/zend.ze1_compatibility_mode/', $errstr)){
1543     return;
1544   }
1546   /* FIXME: Hide ldap size limit messages */
1547   if (preg_match('/ldap_error/', $errstr)){
1548     if (preg_match('/sizelimit/', $errstr)){
1549       return;
1550     }
1551   }
1553   /* Create header as needed */
1554   if ($error_collector == ""){
1555     if ($_SESSION['js']==FALSE){
1556       $error_collector= "<div>";
1557     } else {
1558       $error_collector= "<table width=\"100%\" style='background-color:#E0E0E0;border-bottom:1px solid black'><tr><td><img alt=\"\" align=\"middle\" src='".get_template_path('images/warning.png')."'>&nbsp;<font style='font-size:14px;font-weight:bold'>"._("Generating this page caused the PHP interpreter to raise some errors!")."</font></td><td align=right><button onClick='toggle(\"errorbox\")'>"._("Toggle information")."</button></td></tr></table><div id='errorbox' style='position:absolute; z-index:0; visibility: hidden'>";
1559     }
1560   }
1561  
1562   /* Create error header */
1563   $error_collector.= "<table width=\"100%\" cellspacing=0 style='background-color:#402005;color:white;border:2px solid red'><tr><td colspan=3><h1 style='color:white'>"._("PHP error")." \"$errstr\"</h1></td></tr>";
1564   
1565   /* Extract traceback data - if available */
1566   if (function_exists('debug_backtrace')){
1567     $trace= debug_backtrace();
1569     /* Generate trace history */
1570     for ($index= 1; $index<count($trace); $index++){
1571       $ct= $trace[$index];
1572       $loc= "";
1573       if (isset($ct['class'])){
1574         $loc.= _("class")." ".$ct['class'];
1575         if (isset($ct['function'])){
1576           $loc.= " / ";
1577         }
1578       }
1579       if (isset($ct['function'])){
1580         $loc.= _("function")." ".$ct['function'];
1581       }
1582       if (isset($ct['type'])){
1583         switch ($ct['type']){
1584           case "::":
1585             $type= _("static");
1586           break;
1588           case "->":
1589             $type= _("method");
1590           break;
1591         }
1592       } else {
1593         $type= "-";
1594       }
1595       $args= "";
1596       foreach ($ct['args'] as $arg){
1597         $args.= htmlentities("\"$arg\", ");
1598       }
1599       $args= preg_replace("/, $/", "", $args);
1600       if ($args == ""){
1601         $args= "-";
1602       }
1603       $file= $ct['file'];
1604       $line= $ct['line'];
1605       $color= ($index&1)?'#404040':'606060';
1606       $error_collector.= "<tr style='background-color:$color'><td style='padding-left:20px' width=\"30%\">"._("Trace")."[$index]: $loc</td>";
1607       $error_collector.= "<td>"._("File").": $file ("._('Line')." $line)</td><td width=\"10%\">"._("Type").": $type</td></tr>";
1608       $error_collector.= "<tr style='background-color:$color'><td colspan=3 style='padding-left:20px;'>"._("Arguments").": $args</td></tr>";
1609     }
1610   }
1612   /* Close error table */
1613   $error_collector.= "</table>";
1615   /* Write to syslog */
1616   gosa_log ("PHP error: $errstr ($errfile, line $errline)");
1620 function dummy_error_handler()
1624 function rmdirRecursive($path, $followLinks=false) {
1625   $dir= opendir($path);
1626   while($entry= readdir($dir)) {
1627     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1628       unlink($path."/".$entry);
1629     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1630       rmdirRecursive($path."/".$entry);
1631     }
1632   }
1633   closedir($dir);
1634   return rmdir($path);
1637 function clean_smarty_compile_dir($directory)
1639   global $svn_revision;
1641   if(is_dir($directory) && is_readable($directory)) {
1642     // Set revision filename to REVISION
1643     $revision_file= $directory."/REVISION";
1645     /* Is there a stamp containing the current revision? */
1646     if(!file_exists($revision_file)) {
1647       // create revision file
1648       create_revision($revision_file, $svn_revision);
1649     } else {
1650       # check for "$config->...['CONFIG']/revision" and the
1651       # contents should match the revision number
1652       if(!compare_revision($revision_file, $svn_revision)){
1653         // If revision differs, clean compile directory
1654         foreach(scandir($directory) as $file) {
1655           if( is_file($directory."/".$file) &&
1656               is_writable($directory."/".$file)) {
1657               // delete file
1658               if(!unlink($directory."/".$file)) {
1659                 print_red("File ".$directory."/".$file." could not be deleted.");
1660                 // This should never be reached
1661               }
1662           } elseif(is_dir($directory."/".$file) &&
1663                     is_writable($directory."/".$file)) {
1664                     // Just recursively delete it
1665              rmdirRecursive($directory."/".$file);
1666           }
1667         }
1668         // We should now create a fresh revision file
1669         clean_smarty_compile_dir($directory);
1670       } else {
1671         // Revision matches, nothing to do
1672       }
1673     }
1674   } else {
1675     // Smarty compile dir is not accessible
1676     // (Smarty will warn about this)
1677   }
1680 function create_revision($revision_file, $revision)
1682   $result= false;
1683   
1684   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1685     if($fh= fopen($revision_file, "w")) {
1686       if(fwrite($fh, $revision)) {
1687         $result= true;
1688       }
1689     }
1690     fclose($fh);
1691   } else {
1692     print_red("Can not write to revision file");
1693   }
1695   return $result;
1698 function compare_revision($revision_file, $revision)
1700   // false means revision differs
1701   $result= false;
1702   
1703   if(file_exists($revision_file) && is_readable($revision_file)) {
1704     // Open file
1705     if($fh= fopen($revision_file, "r")) {
1706       // Compare File contents with current revision
1707       if($revision == fread($fh, filesize($revision_file))) {
1708         $result= true;
1709       }
1710     } else {
1711       print_red("Can not open revision file");
1712     }
1713     // Close file
1714     fclose($fh);
1715   }
1717   return $result;
1720 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1721 ?>