Code

users page, some style fixed
[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 /* Include required files */
26 require_once ("class_ldap.inc");
27 require_once ("class_config.inc");
28 require_once ("class_userinfo.inc");
29 require_once ("class_plugin.inc");
30 require_once ("class_pluglist.inc");
31 require_once ("class_tabs.inc");
32 require_once ("class_mail-methods.inc");
33 require_once("class_password-methods.inc");
34 require_once ("debuglib.inc");
36 /* Define constants for debugging */
37 define ("DEBUG_TRACE",   1);
38 define ("DEBUG_LDAP",    2);
39 define ("DEBUG_MYSQL",   4);
40 define ("DEBUG_SHELL",   8);
41 define ("DEBUG_POST",   16);
42 define ("DEBUG_SESSION",32);
43 define ("DEBUG_CONFIG", 64);
45 /* Rewrite german 'umlauts' and spanish 'accents'
46    to get better results */
47 $REWRITE= array( "ä" => "ae",
48     "ö" => "oe",
49     "ü" => "ue",
50     "Ä" => "Ae",
51     "Ö" => "Oe",
52     "Ü" => "Ue",
53     "ß" => "ss",
54     "á" => "a",
55     "é" => "e",
56     "í" => "i",
57     "ó" => "o",
58     "ú" => "u",
59     "Á" => "A",
60     "É" => "E",
61     "Í" => "I",
62     "Ó" => "O",
63     "Ú" => "U",
64     "ñ" => "ny",
65     "Ñ" => "Ny" );
68 /* Function to include all class_ files starting at a
69    given directory base */
70 function get_dir_list($folder= ".")
71 {
72   $currdir=getcwd();
73   if ($folder){
74     chdir("$folder");
75   }
77   $dh = opendir(".");
78   while(false !== ($file = readdir($dh))){
80     /* Recurse through all "common" directories */
81     if(is_dir($file) && $file!="." && $file!=".." && $file!="CVS"){
82       get_dir_list($file);
83       continue;
84     }
86     /* Include existing class_ files */
87     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
88       require_once($file);
89     }
90   }
92   closedir($dh);
93   chdir($currdir);
94 }
97 /* Create seed with microseconds */
98 function make_seed() {
99   list($usec, $sec) = explode(' ', microtime());
100   return (float) $sec + ((float) $usec * 100000);
104 /* Debug level action */
105 function DEBUG($level, $line, $function, $file, $data, $info="")
107   if ($_SESSION['DEBUGLEVEL'] & $level){
108     $output= "DEBUG[$level] ";
109     if ($function != ""){
110       $output.= "($file:$function():$line) - $info: ";
111     } else {
112       $output.= "($file:$line) - $info: ";
113     }
114     echo $output;
115     if (is_array($data)){
116       print_a($data);
117     } else {
118       echo "'$data'";
119     }
120     echo "<br>";
121   }
125 /* Simple function to get browser language and convert it to
126    xx_XY needed by locales. Ignores sublanguages and weights. */
127 function get_browser_language()
129   global $BASE_DIR;
131   /* Get list of languages */
132   if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
133     $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
134     $languages= split (',', $lang);
135     $languages[]= "C";
136   } else {
137     $languages= array("C");
138   }
140   /* Walk through languages and get first supported */
141   foreach ($languages as $val){
143     /* Strip off weight */
144     $lang= preg_replace("/;q=.*$/i", "", $val);
146     /* Simplify sub language handling */
147     $lang= preg_replace("/-.*$/", "", $lang);
149     /* Cancel loop if available in GOsa, or the last
150        entry has been reached */
151     if (is_dir("$BASE_DIR/locale/$lang")){
152       break;
153     }
154   }
156   return (strtolower($lang)."_".strtoupper($lang));
160 /* Rewrite ui object to another dn */
161 function change_ui_dn($dn, $newdn)
163   $ui= $_SESSION['ui'];
164   if ($ui->dn == $dn){
165     $ui->dn= $newdn;
166     $_SESSION['ui']= $ui;
167   }
171 /* Return theme path for specified file */
172 function get_template_path($filename= '', $plugin= FALSE, $path= "")
174   global $config, $BASE_DIR;
176   if (!isset($config->data['MAIN']['THEME'])){
177     $theme= 'default';
178   } else {
179     $theme= $config->data['MAIN']['THEME'];
180   }
182   /* Return path for empty filename */
183   if ($filename == ''){
184     return ("themes/$theme/");
185   }
187   /* Return plugin dir or root directory? */
188   if ($plugin){
189     if ($path == ""){
190       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
191     } else {
192       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
193     }
194     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
195       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
196     }
197     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
198       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
199     }
200     if ($path == ""){
201       return ($_SESSION['plugin_dir']."/$filename");
202     } else {
203       return ($path."/$filename");
204     }
205   } else {
206     if (file_exists("themes/$theme/$filename")){
207       return ("themes/$theme/$filename");
208     }
209     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
210       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
211     }
212     if (file_exists("themes/default/$filename")){
213       return ("themes/default/$filename");
214     }
215     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
216       return ("$BASE_DIR/ihtml/themes/default/$filename");
217     }
218     return ($filename);
219   }
223 function array_remove_entries($needles, $haystack)
225   $tmp= array();
227   /* Loop through entries to be removed */
228   foreach ($haystack as $entry){
229     if (!in_array($entry, $needles)){
230       $tmp[]= $entry;
231     }
232   }
234   return ($tmp);
238 function gosa_log ($message)
240   global $ui;
242   /* Preset to something reasonable */
243   $username= " unauthenticated";
245   /* Replace username if object is present */
246   if (isset($ui)){
247     if ($ui->username != ""){
248       $username= "[$ui->username]";
249     } else {
250       $username= "unknown";
251     }
252   }
254   syslog(LOG_WARNING,"GOsa$username: $message");
258 function ldap_init ($server, $base, $binddn='', $pass='')
260   global $config;
262   $ldap = new LDAP ($binddn, $pass, $server, isset($config->current['RECURSIVE'])                                                && $config->current['RECURSIVE'] == "true",
263       isset($config->current['TLS']) && $config->current['TLS'] == "true");
265   /* Sadly we've no proper return values here. Use the error message instead. */
266   if (!preg_match("/Success/i", $ldap->error)){
267     print_red(sprintf(_("Error when connecting the LDAP. Server said '%s'."),
268           $ldap->get_error()));
269     echo $_SESSION['errors'];
271     /* Hard error. We'd like to use the LDAP, anyway... */
272     exit;
273   }
275   /* Preset connection base to $base and return to caller */
276   $ldap->cd ($base);
277   return $ldap;
281 function ldap_login_user ($username, $password)
283   global $config;
285   /* look through the entire ldap */
286   $ldap = $config->get_ldap_link();
287   if (!preg_match("/Success/i", $ldap->error)){
288     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
289     echo $_SESSION['errors'];
290     exit;
291   }
292   $ldap->cd($config->current['BASE']);
293   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
295   /* get results, only a count of 1 is valid */
296   switch ($ldap->count()){
298     /* user not found */
299     case 0:     return (NULL);
300             break;
302             /* valid uniq user */
303     case 1: 
304             break;
306             /* found more than one matching id */
307     default:
308             print_red(_("Username / UID is not unique. Please check your LDAP database."));
309             return (NULL);
310   }
312   /* LDAP schema is not case sensitive. Perform additional check. */
313   $attrs= $ldap->fetch();
314   if ($attrs['uid'][0] != $username){
315     return(NULL);
316   }
318   /* got user dn, fill acl's */
319   $ui= new userinfo($config, $ldap->getDN());
320   $ui->username= $username;
322   /* password check, bind as user with supplied password  */
323   $ldap->disconnect();
324   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
325       isset($config->current['RECURSIVE']) &&
326       $config->current['RECURSIVE'] == "true",
327       isset($config->current['TLS'])
328       && $config->current['TLS'] == "true");
329   if (!preg_match("/Success/i", $ldap->error)){
330     return (NULL);
331   }
333   /* Username is set, load subtreeACL's now */
334   $ui->loadACL();
336   return ($ui);
340 function add_lock ($object, $user)
342   global $config;
344   /* Just a sanity check... */
345   if ($object == "" || $user == ""){
346     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
347     return;
348   }
350   /* Check for existing entries in lock area */
351   $ldap= $config->get_ldap_link();
352   $ldap->cd ($config->current['CONFIG']);
353   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=$object))",
354       array("gosaUser"));
355   if (!preg_match("/Success/i", $ldap->error)){
356     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()));
357     return;
358   }
360   /* Add lock if none present */
361   if ($ldap->count() == 0){
362     $attrs= array();
363     $name= md5($object);
364     $ldap->cd("cn=$name,".$config->current['CONFIG']);
365     $attrs["objectClass"] = "gosaLockEntry";
366     $attrs["gosaUser"] = $user;
367     $attrs["gosaObject"] = $object;
368     $attrs["cn"] = "$name";
369     $ldap->add($attrs);
370     if (!preg_match("/Success/i", $ldap->error)){
371       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
372             $ldap->get_error()));
373       return;
374     }
375   }
379 function del_lock ($object)
381   global $config;
383   /* Sanity check */
384   if ($object == ""){
385     return;
386   }
388   /* Check for existance and remove the entry */
389   $ldap= $config->get_ldap_link();
390   $ldap->cd ($config->current['CONFIG']);
391   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=$object))", array("gosaObject"));
392   $attrs= $ldap->fetch();
393   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
394     $ldap->rmdir ($ldap->getDN());
396     if (!preg_match("/Success/i", $ldap->error)){
397       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
398             $ldap->get_error()));
399       return;
400     }
401   }
405 function del_user_locks($userdn)
407   global $config;
409   /* Get LDAP ressources */ 
410   $ldap= $config->get_ldap_link();
411   $ldap->cd ($config->current['CONFIG']);
413   /* Remove all objects of this user, drop errors silently in this case. */
414   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
415   while ($attrs= $ldap->fetch()){
416     $ldap->rmdir($attrs['dn']);
417   }
421 function get_lock ($object)
423   global $config;
425   /* Sanity check */
426   if ($object == ""){
427     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
428     return("");
429   }
431   /* Get LDAP link, check for presence of the lock entry */
432   $user= "";
433   $ldap= $config->get_ldap_link();
434   $ldap->cd ($config->current['CONFIG']);
435   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=$object))", array("gosaUser"));
436   if (!preg_match("/Success/i", $ldap->error)){
437     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
438     return("");
439   }
441   /* Check for broken locking information in LDAP */
442   if ($ldap->count() > 1){
444     /* Hmm. We're removing broken LDAP information here and issue a warning. */
445     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
447     /* Clean up these references now... */
448     while ($attrs= $ldap->fetch()){
449       $ldap->rmdir($attrs['dn']);
450     }
452     return("");
454   } elseif ($ldap->count() == 1){
455     $attrs = $ldap->fetch();
456     $user= $attrs['gosaUser'][0];
457   }
459   return ($user);
463 function get_list($subtreeACL, $filter, $subsearch= TRUE, $base="", $attrs= array(), $flag= FALSE)
465   global $config;
467   /* Base the search on default base if not set */
468   $ldap= $config->get_ldap_link($flag);
469   if ($base == ""){
470     $ldap->cd ($config->current['BASE']);
471   } else {
472     $ldap->cd ($base);
473   }
475   /* Perform ONE or SUB scope searches? */
476   if ($subsearch) {
477     $ldap->search ($filter, $attrs);
478   } else {
479     $ldap->ls ($filter);
480   }
482   /* Check for size limit exceeded messages for GUI feedback */
483   if (preg_match("/size limit/i", $ldap->error)){
484     $_SESSION['limit_exceeded']= TRUE;
485   } else {
486     $_SESSION['limit_exceeded']= FALSE;
487   }
489   /* Crawl through reslut entries and perform the migration to the
490      result array */
491   $result= array();
492   while($attrs = $ldap->fetch()) {
493     $dn= preg_replace("/[ ]*,[ ]*/", ",", $ldap->getDN());
494     foreach ($subtreeACL as $key => $value){
495       if (preg_match("/$key/", $dn)){
496         $attrs["dn"]= $dn;
497         $result[]= $attrs;
498         break;
499       }
500     }
501   }
503   return ($result);
507 function check_sizelimit()
509   /* Ignore dialog? */
510   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
511     return ("");
512   }
514   /* Eventually show dialog */
515   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
516     $smarty= get_smarty();
517     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
518           $_SESSION['size_limit']));
519     $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).'">'));
520     return($smarty->fetch(get_template_path('sizelimit.tpl')));
521   }
523   return ("");
527 function print_sizelimit_warning()
529   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
530       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
531     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
532   } else {
533     $config= "";
534   }
535   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
536     return ("("._("incomplete").") $config");
537   }
538   return ("");
542 function eval_sizelimit()
544   if (isset($_POST['set_size_action'])){
546     /* User wants new size limit? */
547     if (is_id($_POST['new_limit']) &&
548         isset($_POST['action']) && $_POST['action']=="newlimit"){
550       $_SESSION['size_limit']= validate($_POST['new_limit']);
551       $_SESSION['size_ignore']= FALSE;
552     }
554     /* User wants no limits? */
555     if (isset($_POST['action']) && $_POST['action']=="ignore"){
556       $_SESSION['size_limit']= 0;
557       $_SESSION['size_ignore']= TRUE;
558     }
560     /* User wants incomplete results */
561     if (isset($_POST['action']) && $_POST['action']=="limited"){
562       $_SESSION['size_ignore']= TRUE;
563     }
564   }
566   /* Allow fallback to dialog */
567   if (isset($_POST['edit_sizelimit'])){
568     $_SESSION['size_ignore']= FALSE;
569   }
573 function get_permissions ($dn, $subtreeACL)
575   global $config;
577   $base= $config->current['BASE'];
578   $tmp= "d,".$dn;
579   $sacl= array();
581   /* Sort subacl's for lenght to simplify matching
582      for subtrees */
583   foreach ($subtreeACL as $key => $value){
584     $sacl[$key]= strlen($key);
585   }
586   arsort ($sacl);
587   reset ($sacl);
589   /* Successively remove leading parts of the dn's until
590      it doesn't contain commas anymore */
591   while (preg_match('/,/', $tmp)){
592     $tmp= ltrim(strstr($tmp, ","), ",");
594     /* Check for acl that may apply */
595     foreach ($sacl as $key => $value){
596       if (preg_match("/$key$/", $tmp)){
597         return ($subtreeACL[$key]);
598       }
599     }
600   }
602   return array("");
606 function get_module_permission($acl_array, $module, $dn)
608   global $ui;
610   $final= "";
611   foreach($acl_array as $acl){
613     /* Check for selfflag (!) in ACL to determine if
614        the user is allowed to change parts of his/her
615        own account */
616     if (preg_match("/^!/", $acl)){
617       if ($dn != "" && $dn != $ui->dn){
619         /* No match for own DN, give up on this ACL */
620         continue;
622       } else {
624         /* Matches own DN, remove the selfflag */
625         $acl= preg_replace("/^!/", "", $acl);
627       }
628     }
630     /* Remove leading garbage */
631     $acl= preg_replace("/^:/", "", $acl);
633     /* Discover if we've access to the submodule by comparing
634        all allowed submodules specified in the ACL */
635     $tmp= split(",", $acl);
636     foreach ($tmp as $mod){
637       if (preg_match("/$module#/", $mod)){
638         $final= strstr($mod, "#")."#";
639         continue;
640       }
641       if (preg_match("/[^#]$module$/", $mod)){
642         return ("#all#");
643       }
644       if (preg_match("/^all$/", $mod)){
645         return ("#all#");
646       }
647     }
648   }
650   /* Return assembled ACL, or none */
651   if ($final != ""){
652     return (preg_replace('/##/', '#', $final));
653   }
655   /* Nothing matches - disable access for this object */
656   return ("#none#");
660 function get_userinfo()
662   global $ui;
664   return $ui;
668 function get_smarty()
670   global $smarty;
672   return $smarty;
676 function convert_department_dn($dn)
678   $dep= "";
680   /* Build a sub-directory style list of the tree level
681      specified in $dn */
682   foreach (split (",", $dn) as $val){
684     /* We're only interested in organizational units... */
685     if (preg_match ("/ou=/", $val)){
686       $dep= preg_replace("/ou=([^,]+)/", "\\1", $val)."/$dep";
687     }
689     /* ... and location objects */
690     if (preg_match ("/l=/", $val)){
691       $dep= preg_replace("/l=([^,]+)/", "\\1", $val)."/$dep";
692     }
693   }
695   /* Return and remove accidently trailing slashes */
696   return rtrim($dep, "/");
700 function get_ou($name)
702   global $config;
704   $ou= $config->current[$name];
705   if ($ou != ""){
706     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
707       return "ou=$ou,";
708     } else {
709       return "$ou,";
710     }
711   } else {
712     return "";
713   }
717 function get_people_ou()
719   return (get_ou("PEOPLE"));
723 function get_groups_ou()
725   return (get_ou("GROUPS"));
729 function get_winstations_ou()
731   return (get_ou("WINSTATIONS"));
735 function get_base_from_people($dn)
737   global $config;
739   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
740   $base= preg_replace($pattern, '', $dn);
742   /* Set to base, if we're not on a correct subtree */
743   if (!isset($config->idepartments[$base])){
744     $base= $config->current['BASE'];
745   }
747   return ($base);
751 function get_departments($ignore_dn= "")
753   global $config;
755   /* Initialize result hash */
756   $result= array();
757   $result['/']= $config->current['BASE'];
759   /* Get list of department objects */
760   $ldap= $config->get_ldap_link();
761   $ldap->cd ($config->current['BASE']);
762   $ldap->search ("(objectClass=gosaDepartment)", array("ou"));
763   while ($attrs= $ldap->fetch()){
764     $dn= $ldap->getDN();
765     if ($dn == $ignore_dn){
766       continue;
767     }
768     $result[convert_department_dn($dn)]= $dn;
769   }
771   return ($result);
775 function chkacl($acl, $name)
777   /* Look for attribute in ACL */
778   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
779     return ("");
780   }
782   /* Optically disable html object for no match */
783   return (" disabled ");
787 function is_phone_nr($nr)
789   if ($nr == ""){
790     return (TRUE);
791   }
793   return preg_match ("/^[0-9 ()+*-]+$/", $nr);
797 function is_url($url)
799   if ($url == ""){
800     return (TRUE);
801   }
803   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
807 function is_dn($dn)
809   if ($dn == ""){
810     return (TRUE);
811   }
813   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
817 function is_uid($uid)
819   global $config;
821   if ($uid == ""){
822     return (TRUE);
823   }
825   /* STRICT adds spaces and case insenstivity to the uid check.
826      This is dangerous and should not be used. */
827   if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
828     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
829   } else {
830     return preg_match ("/^[a-z0-9_-]+$/", $uid);
831   }
835 function is_id($id)
837   if ($id == ""){
838     return (FALSE);
839   }
841   return preg_match ("/^[0-9]+$/", $id);
845 function is_path($path)
847   if ($path == ""){
848     return (TRUE);
849   }
850   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
851     return (FALSE);
852   }
854   return preg_match ("/\/.+$/", $path);
858 function is_email($address, $template= FALSE)
860   if ($address == ""){
861     return (TRUE);
862   }
863   if ($template){
864     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
865         $address);
866   } else {
867     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
868         $address);
869   }
873 function print_red()
875   /* Check number of arguments */
876   if (func_num_args() < 1){
877     return;
878   }
880   /* Get arguments, save string */
881   $array = func_get_args();
882   $string= $array[0];
884   /* Step through arguments */
885   for ($i= 1; $i<count($array); $i++){
886     $string= preg_replace ("/%s/", $array[$i], $string, 1);
887   }
889   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
890      the other case... */
891   if (isset($_SESSION['DEBUGLEVEL'])){
892     $_SESSION['errors'].= "<div align=\"center\" style=\"border-width:5px;".
893       "border-style:solid;border-color:red; background-color:black;".
894       "margin-bottom:10px; padding:8px;\"><table><tr><td><img alt=\"\" src=\"".
895       get_template_path('images/warning.png')."\"></td>".
896       "<td width=\"100%\" align=\"center\"><font color=\"#FFFFFF\">".
897       "<b style='font-size:16px;'>$string</b></font></td><td>".
898       "<img alt=\"\"src=\"".get_template_path('images/warning.png').
899       "\"></td></tr></table></div>\n";
900   } else {
901     echo "Error: $string\n";
902   }
906 function gen_locked_message($user, $dn)
908   global $plug, $config;
910   $_SESSION['dn']= $dn;
911   $ldap= $config->get_ldap_link();
912   $ldap->cat ($user);
913   $attrs= $ldap->fetch();
914   $uid= $attrs["uid"][0];
916   /* Prepare and show template */
917   $smarty= get_smarty();
918   $smarty->assign ("dn", $dn);
919   $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&viewid=$uid>$uid</a>"));
921   return ($smarty->fetch (get_template_path('islocked.tpl')));
925 function to_string ($value)
927   /* If this is an array, generate a text blob */
928   if (is_array($value)){
929     $ret= "";
930     foreach ($value as $line){
931       $ret.= $line."<br>\n";
932     }
933     return ($ret);
934   } else {
935     return ($value);
936   }
940 function get_printer_list($cups_server)
942   global $config;
944   $res= array();
946   /* Use CUPS, if we've access to it */
947   if (function_exists('cups_get_dest_list')){
948     $dest_list= cups_get_dest_list ($cups_server);
950     foreach ($dest_list as $prt){
951       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
953       foreach ($attr as $prt_info){
954         if ($prt_info->name == "printer-info"){
955           $info= $prt_info->value;
956           break;
957         }
958       }
959       $res[$prt->name]= "$info [$prt->name]";
960     }
962     /* CUPS is not available, try lpstat as a replacement */
963   } else {
964     unset ($ar);
965     exec("lpstat -p", $ar);
966     foreach($ar as $val){
967       list($dummy, $printer, $rest)= split(' ', $val, 3);
968       if (preg_match('/^[^@]+$/', $printer)){
969         $res[$printer]= "$printer";
970       }
971     }
972   }
974   /* Merge in printers from LDAP */
975   $ldap= $config->get_ldap_link();
976   $ldap->cd ($config->current['BASE']);
977   $ldap->search('(objectClass=gotoPrinter)', array('cn'));
978   while ($attrs= $ldap->fetch()){
979     $res[$attrs["cn"][0]]= $attrs["cn"][0];
980   }
982   return $res;
986 function sess_del ($var)
988   /* New style */
989   unset ($_SESSION[$var]);
991   /* ... work around, since the first one
992      doesn't seem to work all the time */
993   session_unregister ($var);
997 function show_errors($message)
999   $complete= "";
1001   /* Assemble the message array to a plain string */
1002   foreach ($message as $error){
1003     if ($complete == ""){
1004       $complete= $error;
1005     } else {
1006       $complete= "$error<br>$complete";
1007     }
1008   }
1010   /* Fill ERROR variable with nice error dialog */
1011   print_red($complete);
1015 function show_ldap_error($message)
1017   if (!preg_match("/Success/i", $message)){
1018     print_red (_("LDAP error:")." $message");
1019     return TRUE;
1020   } else {
1021     return FALSE;
1022   }
1026 function rewrite($s)
1028   global $REWRITE;
1030   foreach ($REWRITE as $key => $val){
1031     $s= preg_replace("/$key/", "$val", $s);
1032   }
1034   return ($s);
1038 function dn2base($dn)
1040   global $config;
1042   if (get_people_ou() != ""){
1043     $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1044   }
1045   if (get_groups_ou() != ""){
1046     $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1047   }
1048   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1050   return ($base);
1055 function check_command($cmdline)
1057   $cmd= preg_replace("/ .*$/", "", $cmdline);
1059   /* Check if command exists in filesystem */
1060   if (!file_exists($cmd)){
1061     return (FALSE);
1062   }
1064   /* Check if command is executable */
1065   if (!is_executable($cmd)){
1066     return (FALSE);
1067   }
1069   return (TRUE);
1073 function print_header($image, $headline, $info= "")
1075   $display= "<div class=\"plugtop\">\n";
1076   $display.= "  <img src=\"$image\" align=\"middle\" alt=\"*\">&nbsp;$headline\n";
1077   $display.= "</div>\n";
1079   if ($info != ""){
1080     $display.= "<div class=\"pluginfo\">\n";
1081     $display.= "$info";
1082     $display.= "</div>\n";
1083   } else {
1084     $display.= "<div style=\"height:5px;\">\n";
1085     $display.= "&nbsp;";
1086     $display.= "</div>\n";
1087   }
1089   return ($display);
1093 function register_global($name, $object)
1095   $_SESSION[$name]= $object;
1099 function is_global($name)
1101   return isset($_SESSION[$name]);
1105 function get_global($name)
1107   return $_SESSION[$name];
1111 function range_selector($dcnt,$start,$range=25)
1114   /* Entries shown left and right from the selected entry */
1115   $max_entries= 10;
1117   /* Initialize and take care that max_entries is even */
1118   $output="";
1119   if ($max_entries & 1){
1120     $max_entries++;
1121   }
1123   /* Prevent output to start or end out of range */
1124   if ($start < 0 ){
1125     $start= 0 ;
1126   }
1127   if ($start >= $dcnt){
1128     $start= $range * (int)(($dcnt / $range) + 0.5);
1129   }
1131   $numpages= (($dcnt / $range));
1132   if(((int)($numpages))!=($numpages))
1133     $numpages = (int)$numpages + 1;
1134   $ppage= (int)(($start / $range) + 0.5);
1137   /* Align selected page to +/- max_entries/2 */
1138   $begin= $ppage - $max_entries/2;
1139   $end= $ppage + $max_entries/2;
1141   /* Adjust begin/end, so that the selected value is somewhere in
1142      the middle and the size is max_entries if possible */
1143   if ($begin < 0){
1144     $end-= $begin + 1;
1145     $begin= 0;
1146   }
1147   if ($end > $numpages) {
1148     $end= $numpages;
1149   }
1150   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1151     $begin= $end - $max_entries;
1152   }
1154   /* Draw decrement */
1155   if ($start > 0 ) {
1156     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1157       (($start-$range))."\">".
1158       "<img alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1159   }
1161   /* Draw pages */
1162   for ($i= $begin; $i < $end; $i++) {
1163     if ($ppage == $i){
1164       $output.= "<a style=\"background-color:#D0D0D0;\" href=\"main.php?plug=".
1165         validate($_GET['plug'])."&start=".
1166         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1167     } else {
1168       $output.= "<a href=\"main.php?plug=".validate($_GET['plug']).
1169         "&start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1170     }
1171   }
1173   /* Draw increment */
1174   if($start < ($dcnt-$range)) {
1175     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1176       (($start+($range)))."\">".
1177       "<img alt=\"\" src=\"images/forward.png\" border=0 align=\"middle\"></a>";
1178   }
1180   return($output);
1184 function apply_filter()
1186   $apply= "";
1188   $apply= ''.
1189     '<table width="100%"  style="border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1190     '<input type="submit" name="apply" value="'._("Apply").'"></td></tr></table>';
1192   return ($apply);
1196 function back_to_main()
1198   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1199     _("Back").'"></p><input type="hidden" name="ignore">';
1201   return ($string);
1205 function normalize_netmask($netmask)
1207   /* Check for notation of netmask */
1208   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1209     $num= (int)($netmask);
1210     $netmask= "";
1212     for ($byte= 0; $byte<4; $byte++){
1213       $result=0;
1215       for ($i= 7; $i>=0; $i--){
1216         if ($num-- > 0){
1217           $result+= pow(2,$i);
1218         }
1219       }
1221       $netmask.= $result.".";
1222     }
1224     return (preg_replace('/\.$/', '', $netmask));
1225   }
1227   return ($netmask);
1231 function netmask_to_bits($netmask)
1233   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1234   $res= 0;
1236   for ($n= 0; $n<4; $n++){
1237     $start= 255;
1238     $name= "nm$n";
1240     for ($i= 0; $i<8; $i++){
1241       if ($start == (int)($$name)){
1242         $res+= 8 - $i;
1243         break;
1244       }
1245       $start-= pow(2,$i);
1246     }
1247   }
1249   return ($res);
1253 function recurse($rule, $variables)
1255   $result= array();
1257   if (!count($variables)){
1258     return array($rule);
1259   }
1261   reset($variables);
1262   $key= key($variables);
1263   $val= current($variables);
1264   unset ($variables[$key]);
1266   foreach($val as $possibility){
1267     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1268     $result= array_merge($result, recurse($nrule, $variables));
1269   }
1271   return ($result);
1275 function expand_id($rule, $attributes)
1277   /* Check for id rule */
1278   if(preg_match('/^id(:|#)\d+$/',$rule)){
1279     return (array("\{$rule}"));
1280   }
1282   /* Check for clean attribute */
1283   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1284     $rule= preg_replace('/^%/', '', $rule);
1285     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1286     return (array($val));
1287   }
1289   /* Check for attribute with parameters */
1290   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1291     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1292     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1293     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1294     $start= preg_replace ('/-.*$/', '', $param);
1295     $stop = preg_replace ('/^[^-]+-/', '', $param);
1297     /* Assemble results */
1298     $result= array();
1299     for ($i= $start; $i<= $stop; $i++){
1300       $result[]= substr($val, 0, $i);
1301     }
1302     return ($result);
1303   }
1305   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1306   return (array($rule));
1310 function gen_uids($rule, $attributes)
1312   global $config;
1314   /* Search for keys and fill the variables array with all 
1315      possible values for that key. */
1316   $part= "";
1317   $trigger= false;
1318   $stripped= "";
1319   $variables= array();
1321   for ($pos= 0; $pos < strlen($rule); $pos++){
1323     if ($rule[$pos] == "{" ){
1324       $trigger= true;
1325       $part= "";
1326       continue;
1327     }
1329     if ($rule[$pos] == "}" ){
1330       $variables[$pos]= expand_id($part, $attributes);
1331       $stripped.= "\{$pos}";
1332       $trigger= false;
1333       continue;
1334     }
1336     if ($trigger){
1337       $part.= $rule[$pos];
1338     } else {
1339       $stripped.= $rule[$pos];
1340     }
1341   }
1343   /* Recurse through all possible combinations */
1344   $proposed= recurse($stripped, $variables);
1346   /* Get list of used ID's */
1347   $used= array();
1348   $ldap= $config->get_ldap_link();
1349   $ldap->cd($config->current['BASE']);
1350   $ldap->search('(uid=*)');
1352   while($attrs= $ldap->fetch()){
1353     $used[]= $attrs['uid'][0];
1354   }
1356   /* Remove used uids and watch out for id tags */
1357   $ret= array();
1358   foreach($proposed as $uid){
1360     /* Check for id tag and modify uid if needed */
1361     if(preg_match('/\{id:\d+}/',$uid)){
1362       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1364       for ($i= 0; $i < pow(10,$size); $i++){
1365         $number= sprintf("%0".$size."d", $i);
1366         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1367         if (!in_array($res, $used)){
1368           $uid= $res;
1369           break;
1370         }
1371       }
1372     }
1374     if(preg_match('/\{id#\d+}/',$uid)){
1375       $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1377       while (true){
1378         mt_srand((double) microtime()*1000000);
1379         $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1380         $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1381         if (!in_array($res, $used)){
1382           $uid= $res;
1383           break;
1384         }
1385       }
1386     }
1388     /* Don't assign used ones */
1389     if (!in_array($uid, $used)){
1390       $ret[]= $uid;
1391     }
1392   }
1394   return(array_unique($ret));
1398 function array_search_r($needle, $key, $haystack){
1400   foreach($haystack as $index => $value){
1401     $match= 0;
1403     if (is_array($value)){
1404       $match= array_search_r($needle, $key, $value);
1405     }
1407     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1408       $match=1;
1409     }
1411     if ($match){
1412       return 1;
1413     }
1414   }
1416   return 0;
1417
1420 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1421    Need to convert... */
1422 function to_byte($value) {
1423   $value= strtolower(trim($value));
1425   if(!is_numeric(substr($value, -1))) {
1427     switch(substr($value, -1)) {
1428       case 'g':
1429         $mult= 1073741824;
1430         break;
1431       case 'm':
1432         $mult= 1048576;
1433         break;
1434       case 'k':
1435         $mult= 1024;
1436         break;
1437     }
1439     return ($mult * (int)substr($value, 0, -1));
1440   } else {
1441     return $value;
1442   }
1446 function in_array_ics($value, $items)
1448   foreach ($items as $item){
1449     if (strtolower($item) == strtolower($value)) {
1450       return (TRUE);
1451     }
1452   }
1454   return (FALSE);
1455
1458 function generate_alphabet($count= 10)
1460   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1461   $alphabet= "";
1462   $c= 0;
1464   /* Fill cells with charaters */
1465   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1466     if ($c == 0){
1467       $alphabet.= "<tr>";
1468     }
1470     $ch = mb_substr($characters, $i, 1, "UTF8");
1471     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1472       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1474     if ($c++ == $count){
1475       $alphabet.= "</tr>";
1476       $c= 0;
1477     }
1478   }
1480   /* Fill remaining cells */
1481   while ($c++ <= $count){
1482     $alphabet.= "<td>&nbsp;</td>";
1483   }
1485   return ($alphabet);
1489 function validate($string)
1491   return (strip_tags(preg_replace('/\0/', '', $string)));
1494 function get_gosa_version()
1496   /* Variables filled in by subversion */
1497   $svn_path = '$HeadURL$';
1498   $svn_revision = '$Revision$';
1500   /* Extract informations */
1501   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1503   /* Release or development? */
1504   if (preg_match('%/gosa/trunk/%', $svn_path)){
1505     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1506   } else {
1507     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1508     return (sprintf(_("GOsa $release"), $revision));
1509   }
1512 function gosaRaiseError($errno, $errstr, $errfile, $errline)
1514   global $error_collector;
1516   /* Workaround for buggy imap_open error outputs */
1517   if (preg_match('/imap_open/', $errstr)){
1518     return;
1519   }
1521   /* FIXME: Workaround for PHP5 error message flooding. The new OOM
1522      code want's us to use public/protected/private instead of flat
1523      var declarations. For now I can't workaround this - let's ignore
1524      the messages till the next major release which may drop support
1525      for PHP4. */
1526   if (preg_match('/var: Deprecated./', $errstr)){
1527     return;
1528   }
1530   /* FIXME: Same as above. Compatibility does error flooding.*/
1531   if (preg_match('/zend.ze1_compatibility_mode/', $errstr)){
1532     return;
1533   }
1535   /* Create header as needed */
1536   if ($error_collector == ""){
1537     if ($_SESSION['js']==FALSE){
1538       $error_collector= "<div>";
1539     } else {
1540       $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'>";
1541     }
1542   }
1543  
1544   /* Extract traceback data */
1545   $trace= debug_backtrace();
1546   
1547   /* Create error header */
1548   $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>";
1549   
1550   /* Generate trace history */
1551   for ($index= 1; $index<count($trace); $index++){
1552     $ct= $trace[$index];
1553     $loc= "";
1554     if (isset($ct['class'])){
1555       $loc.= _("class")." ".$ct['class'];
1556       if (isset($ct['function'])){
1557         $loc.= " / ";
1558       }
1559     }
1560     if (isset($ct['function'])){
1561       $loc.= _("function")." ".$ct['function'];
1562     }
1563     if (isset($ct['type'])){
1564       switch ($ct['type']){
1565         case "::":
1566                 $type= _("static");
1567                 break;
1569         case "->":
1570                 $type= _("method");
1571                 break;
1572       }
1573     } else {
1574       $type= "-";
1575     }
1576     $args= "";
1577     foreach ($ct['args'] as $arg){
1578       $args.= htmlentities("\"$arg\", ");
1579     }
1580     $args= preg_replace("/, $/", "", $args);
1581     if ($args == ""){
1582       $args= "-";
1583     }
1584     $file= $ct['file'];
1585     $line= $ct['line'];
1586     $color= ($index&1)?'#404040':'606060';
1587     $error_collector.= "<tr style='background-color:$color'><td style='padding-left:20px' width=\"30%\">"._("Trace")."[$index]: $loc</td>";
1588     $error_collector.= "<td>"._("File").": $file ("._('Line')." $line)</td><td width=\"10%\">"._("Type").": $type</td></tr>";
1589     $error_collector.= "<tr style='background-color:$color'><td colspan=3 style='padding-left:20px;'>"._("Arguments").": $args</td></tr>";
1590   }
1592   /* Close error table */
1593   $error_collector.= "</table>";
1595   /* Write to syslog */
1596   gosa_log ("PHP error: $errstr ($errfile, line $errline)");
1599 function dummy_error_handler()
1603 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1604 ?>