Code

ed1364b9816bc06e46aef2bc4d3153925d42c1ed
[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", "/home/cajus/");
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");
41 /* Define constants for debugging */
42 define ("DEBUG_TRACE",   1);
43 define ("DEBUG_LDAP",    2);
44 define ("DEBUG_MYSQL",   4);
45 define ("DEBUG_SHELL",   8);
46 define ("DEBUG_POST",   16);
47 define ("DEBUG_SESSION",32);
48 define ("DEBUG_CONFIG", 64);
50 /* Rewrite german 'umlauts' and spanish 'accents'
51    to get better results */
52 $REWRITE= array( "ä" => "ae",
53     "ö" => "oe",
54     "ü" => "ue",
55     "Ä" => "Ae",
56     "Ö" => "Oe",
57     "Ü" => "Ue",
58     "ß" => "ss",
59     "á" => "a",
60     "é" => "e",
61     "í" => "i",
62     "ó" => "o",
63     "ú" => "u",
64     "Á" => "A",
65     "É" => "E",
66     "Í" => "I",
67     "Ó" => "O",
68     "Ú" => "U",
69     "ñ" => "ny",
70     "Ñ" => "Ny" );
73 /* Function to include all class_ files starting at a
74    given directory base */
75 function get_dir_list($folder= ".")
76 {
77   $currdir=getcwd();
78   if ($folder){
79     chdir("$folder");
80   }
82   $dh = opendir(".");
83   while(false !== ($file = readdir($dh))){
85     /* Recurse through all "common" directories */
86     if(is_dir($file) && $file!="." && $file!=".." && $file!="CVS"){
87       get_dir_list($file);
88       continue;
89     }
91     /* Include existing class_ files */
92     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
93       require_once($file);
94     }
95   }
97   closedir($dh);
98   chdir($currdir);
99 }
102 /* Create seed with microseconds */
103 function make_seed() {
104   list($usec, $sec) = explode(' ', microtime());
105   return (float) $sec + ((float) $usec * 100000);
109 /* Debug level action */
110 function DEBUG($level, $line, $function, $file, $data, $info="")
112   if ($_SESSION['DEBUGLEVEL'] & $level){
113     $output= "DEBUG[$level] ";
114     if ($function != ""){
115       $output.= "($file:$function():$line) - $info: ";
116     } else {
117       $output.= "($file:$line) - $info: ";
118     }
119     echo $output;
120     if (is_array($data)){
121       print_a($data);
122     } else {
123       echo "'$data'";
124     }
125     echo "<br>";
126   }
130 /* Simple function to get browser language and convert it to
131    xx_XY needed by locales. Ignores sublanguages and weights. */
132 function get_browser_language()
134   global $BASE_DIR;
136   /* Get list of languages */
137   if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
138     $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
139     $languages= split (',', $lang);
140     $languages[]= "C";
141   } else {
142     $languages= array("C");
143   }
145   /* Walk through languages and get first supported */
146   foreach ($languages as $val){
148     /* Strip off weight */
149     $lang= preg_replace("/;q=.*$/i", "", $val);
151     /* Simplify sub language handling */
152     $lang= preg_replace("/-.*$/", "", $lang);
154     /* Cancel loop if available in GOsa, or the last
155        entry has been reached */
156     if (is_dir("$BASE_DIR/locale/$lang")){
157       break;
158     }
159   }
161   return (strtolower($lang)."_".strtoupper($lang));
165 /* Rewrite ui object to another dn */
166 function change_ui_dn($dn, $newdn)
168   $ui= $_SESSION['ui'];
169   if ($ui->dn == $dn){
170     $ui->dn= $newdn;
171     $_SESSION['ui']= $ui;
172   }
176 /* Return theme path for specified file */
177 function get_template_path($filename= '', $plugin= FALSE, $path= "")
179   global $config, $BASE_DIR;
181   if (!isset($config->data['MAIN']['THEME'])){
182     $theme= 'default';
183   } else {
184     $theme= $config->data['MAIN']['THEME'];
185   }
187   /* Return path for empty filename */
188   if ($filename == ''){
189     return ("themes/$theme/");
190   }
192   /* Return plugin dir or root directory? */
193   if ($plugin){
194     if ($path == ""){
195       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
196     } else {
197       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
198     }
199     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
200       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
201     }
202     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
203       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
204     }
205     if ($path == ""){
206       return ($_SESSION['plugin_dir']."/$filename");
207     } else {
208       return ($path."/$filename");
209     }
210   } else {
211     if (file_exists("themes/$theme/$filename")){
212       return ("themes/$theme/$filename");
213     }
214     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
215       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
216     }
217     if (file_exists("themes/default/$filename")){
218       return ("themes/default/$filename");
219     }
220     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
221       return ("$BASE_DIR/ihtml/themes/default/$filename");
222     }
223     return ($filename);
224   }
228 function array_remove_entries($needles, $haystack)
230   $tmp= array();
232   /* Loop through entries to be removed */
233   foreach ($haystack as $entry){
234     if (!in_array($entry, $needles)){
235       $tmp[]= $entry;
236     }
237   }
239   return ($tmp);
243 function gosa_log ($message)
245   global $ui;
247   /* Preset to something reasonable */
248   $username= " unauthenticated";
250   /* Replace username if object is present */
251   if (isset($ui)){
252     if ($ui->username != ""){
253       $username= "[$ui->username]";
254     } else {
255       $username= "unknown";
256     }
257   }
259   syslog(LOG_INFO,"GOsa$username: $message");
263 function ldap_init ($server, $base, $binddn='', $pass='')
265   global $config;
267   $ldap = new LDAP ($binddn, $pass, $server, isset($config->current['RECURSIVE'])                                                && $config->current['RECURSIVE'] == "true",
268       isset($config->current['TLS']) && $config->current['TLS'] == "true");
270   /* Sadly we've no proper return values here. Use the error message instead. */
271   if (!preg_match("/Success/i", $ldap->error)){
272     print_red(sprintf(_("Error when connecting the LDAP. Server said '%s'."),
273           $ldap->get_error()));
274     echo $_SESSION['errors'];
276     /* Hard error. We'd like to use the LDAP, anyway... */
277     exit;
278   }
280   /* Preset connection base to $base and return to caller */
281   $ldap->cd ($base);
282   return $ldap;
286 function ldap_login_user ($username, $password)
288   global $config;
290   /* look through the entire ldap */
291   $ldap = $config->get_ldap_link();
292   if (!preg_match("/Success/i", $ldap->error)){
293     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
294     echo $_SESSION['errors'];
295     exit;
296   }
297   $ldap->cd($config->current['BASE']);
298   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
300   /* get results, only a count of 1 is valid */
301   switch ($ldap->count()){
303     /* user not found */
304     case 0:     return (NULL);
305             break;
307             /* valid uniq user */
308     case 1: 
309             break;
311             /* found more than one matching id */
312     default:
313             print_red(_("Username / UID is not unique. Please check your LDAP database."));
314             return (NULL);
315   }
317   /* LDAP schema is not case sensitive. Perform additional check. */
318   $attrs= $ldap->fetch();
319   if ($attrs['uid'][0] != $username){
320     return(NULL);
321   }
323   /* got user dn, fill acl's */
324   $ui= new userinfo($config, $ldap->getDN());
325   $ui->username= $username;
327   /* password check, bind as user with supplied password  */
328   $ldap->disconnect();
329   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
330       isset($config->current['RECURSIVE']) &&
331       $config->current['RECURSIVE'] == "true",
332       isset($config->current['TLS'])
333       && $config->current['TLS'] == "true");
334   if (!preg_match("/Success/i", $ldap->error)){
335     return (NULL);
336   }
338   /* Username is set, load subtreeACL's now */
339   $ui->loadACL();
341   return ($ui);
345 function add_lock ($object, $user)
347   global $config;
349   /* Just a sanity check... */
350   if ($object == "" || $user == ""){
351     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
352     return;
353   }
355   /* Check for existing entries in lock area */
356   $ldap= $config->get_ldap_link();
357   $ldap->cd ($config->current['CONFIG']);
358   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=$object))",
359       array("gosaUser"));
360   if (!preg_match("/Success/i", $ldap->error)){
361     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()));
362     return;
363   }
365   /* Add lock if none present */
366   if ($ldap->count() == 0){
367     $attrs= array();
368     $name= md5($object);
369     $ldap->cd("cn=$name,".$config->current['CONFIG']);
370     $attrs["objectClass"] = "gosaLockEntry";
371     $attrs["gosaUser"] = $user;
372     $attrs["gosaObject"] = $object;
373     $attrs["cn"] = "$name";
374     $ldap->add($attrs);
375     if (!preg_match("/Success/i", $ldap->error)){
376       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
377             $ldap->get_error()));
378       return;
379     }
380   }
384 function del_lock ($object)
386   global $config;
388   /* Sanity check */
389   if ($object == ""){
390     return;
391   }
393   /* Check for existance and remove the entry */
394   $ldap= $config->get_ldap_link();
395   $ldap->cd ($config->current['CONFIG']);
396   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=$object))", array("gosaObject"));
397   $attrs= $ldap->fetch();
398   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
399     $ldap->rmdir ($ldap->getDN());
401     if (!preg_match("/Success/i", $ldap->error)){
402       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
403             $ldap->get_error()));
404       return;
405     }
406   }
410 function del_user_locks($userdn)
412   global $config;
414   /* Get LDAP ressources */ 
415   $ldap= $config->get_ldap_link();
416   $ldap->cd ($config->current['CONFIG']);
418   /* Remove all objects of this user, drop errors silently in this case. */
419   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
420   while ($attrs= $ldap->fetch()){
421     $ldap->rmdir($attrs['dn']);
422   }
426 function get_lock ($object)
428   global $config;
430   /* Sanity check */
431   if ($object == ""){
432     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
433     return("");
434   }
436   /* Get LDAP link, check for presence of the lock entry */
437   $user= "";
438   $ldap= $config->get_ldap_link();
439   $ldap->cd ($config->current['CONFIG']);
440   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=$object))", array("gosaUser"));
441   if (!preg_match("/Success/i", $ldap->error)){
442     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
443     return("");
444   }
446   /* Check for broken locking information in LDAP */
447   if ($ldap->count() > 1){
449     /* Hmm. We're removing broken LDAP information here and issue a warning. */
450     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
452     /* Clean up these references now... */
453     while ($attrs= $ldap->fetch()){
454       $ldap->rmdir($attrs['dn']);
455     }
457     return("");
459   } elseif ($ldap->count() == 1){
460     $attrs = $ldap->fetch();
461     $user= $attrs['gosaUser'][0];
462   }
464   return ($user);
468 function get_list($subtreeACL, $filter, $subsearch= TRUE, $base="", $attrs= array(), $flag= FALSE)
470   global $config;
472   /* Base the search on default base if not set */
473   $ldap= $config->get_ldap_link($flag);
474   if ($base == ""){
475     $ldap->cd ($config->current['BASE']);
476   } else {
477     $ldap->cd ($base);
478   }
480   /* Perform ONE or SUB scope searches? */
481   if ($subsearch) {
482     $ldap->search ($filter, $attrs);
483   } else {
484     $ldap->ls ($filter);
485   }
487   /* Check for size limit exceeded messages for GUI feedback */
488   if (preg_match("/size limit/i", $ldap->error)){
489     $_SESSION['limit_exceeded']= TRUE;
490   } else {
491     $_SESSION['limit_exceeded']= FALSE;
492   }
494   /* Crawl through reslut entries and perform the migration to the
495      result array */
496   $result= array();
497   while($attrs = $ldap->fetch()) {
498     $dn= preg_replace("/[ ]*,[ ]*/", ",", $ldap->getDN());
499     foreach ($subtreeACL as $key => $value){
500       if (preg_match("/$key/", $dn)){
501         $attrs["dn"]= $dn;
502         $result[]= $attrs;
503         break;
504       }
505     }
506   }
508   return ($result);
512 function check_sizelimit()
514   /* Ignore dialog? */
515   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
516     return ("");
517   }
519   /* Eventually show dialog */
520   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
521     $smarty= get_smarty();
522     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
523           $_SESSION['size_limit']));
524     $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).'">'));
525     return($smarty->fetch(get_template_path('sizelimit.tpl')));
526   }
528   return ("");
532 function print_sizelimit_warning()
534   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
535       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
536     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
537   } else {
538     $config= "";
539   }
540   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
541     return ("("._("incomplete").") $config");
542   }
543   return ("");
547 function eval_sizelimit()
549   if (isset($_POST['set_size_action'])){
551     /* User wants new size limit? */
552     if (is_id($_POST['new_limit']) &&
553         isset($_POST['action']) && $_POST['action']=="newlimit"){
555       $_SESSION['size_limit']= validate($_POST['new_limit']);
556       $_SESSION['size_ignore']= FALSE;
557     }
559     /* User wants no limits? */
560     if (isset($_POST['action']) && $_POST['action']=="ignore"){
561       $_SESSION['size_limit']= 0;
562       $_SESSION['size_ignore']= TRUE;
563     }
565     /* User wants incomplete results */
566     if (isset($_POST['action']) && $_POST['action']=="limited"){
567       $_SESSION['size_ignore']= TRUE;
568     }
569   }
571   /* Allow fallback to dialog */
572   if (isset($_POST['edit_sizelimit'])){
573     $_SESSION['size_ignore']= FALSE;
574   }
578 function get_permissions ($dn, $subtreeACL)
580   global $config;
582   $base= $config->current['BASE'];
583   $tmp= "d,".$dn;
584   $sacl= array();
586   /* Sort subacl's for lenght to simplify matching
587      for subtrees */
588   foreach ($subtreeACL as $key => $value){
589     $sacl[$key]= strlen($key);
590   }
591   arsort ($sacl);
592   reset ($sacl);
594   /* Successively remove leading parts of the dn's until
595      it doesn't contain commas anymore */
596   while (preg_match('/,/', $tmp)){
597     $tmp= ltrim(strstr($tmp, ","), ",");
599     /* Check for acl that may apply */
600     foreach ($sacl as $key => $value){
601       if (preg_match("/$key$/", $tmp)){
602         return ($subtreeACL[$key]);
603       }
604     }
605   }
607   return array("");
611 function get_module_permission($acl_array, $module, $dn)
613   global $ui;
615   $final= "";
616   foreach($acl_array as $acl){
618     /* Check for selfflag (!) in ACL to determine if
619        the user is allowed to change parts of his/her
620        own account */
621     if (preg_match("/^!/", $acl)){
622       if ($dn != "" && $dn != $ui->dn){
624         /* No match for own DN, give up on this ACL */
625         continue;
627       } else {
629         /* Matches own DN, remove the selfflag */
630         $acl= preg_replace("/^!/", "", $acl);
632       }
633     }
635     /* Remove leading garbage */
636     $acl= preg_replace("/^:/", "", $acl);
638     /* Discover if we've access to the submodule by comparing
639        all allowed submodules specified in the ACL */
640     $tmp= split(",", $acl);
641     foreach ($tmp as $mod){
642       if (preg_match("/$module#/", $mod)){
643         $final= strstr($mod, "#")."#";
644         continue;
645       }
646       if (preg_match("/[^#]$module$/", $mod)){
647         return ("#all#");
648       }
649       if (preg_match("/^all$/", $mod)){
650         return ("#all#");
651       }
652     }
653   }
655   /* Return assembled ACL, or none */
656   if ($final != ""){
657     return (preg_replace('/##/', '#', $final));
658   }
660   /* Nothing matches - disable access for this object */
661   return ("#none#");
665 function get_userinfo()
667   global $ui;
669   return $ui;
673 function get_smarty()
675   global $smarty;
677   return $smarty;
681 function convert_department_dn($dn)
683   $dep= "";
685   /* Build a sub-directory style list of the tree level
686      specified in $dn */
687   foreach (split (",", $dn) as $val){
689     /* We're only interested in organizational units... */
690     if (preg_match ("/ou=/", $val)){
691       $dep= preg_replace("/ou=([^,]+)/", "\\1", $val)."/$dep";
692     }
694     /* ... and location objects */
695     if (preg_match ("/l=/", $val)){
696       $dep= preg_replace("/l=([^,]+)/", "\\1", $val)."/$dep";
697     }
698   }
700   /* Return and remove accidently trailing slashes */
701   return rtrim($dep, "/");
705 function get_ou($name)
707   global $config;
709   $ou= $config->current[$name];
710   if ($ou != ""){
711     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
712       return "ou=$ou,";
713     } else {
714       return "$ou,";
715     }
716   } else {
717     return "";
718   }
722 function get_people_ou()
724   return (get_ou("PEOPLE"));
728 function get_groups_ou()
730   return (get_ou("GROUPS"));
734 function get_winstations_ou()
736   return (get_ou("WINSTATIONS"));
740 function get_base_from_people($dn)
742   global $config;
744   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/";
745   $base= preg_replace($pattern, '', $dn);
747   /* Set to base, if we're not on a correct subtree */
748   if (!isset($config->idepartments[$base])){
749     $base= $config->current['BASE'];
750   }
752   return ($base);
756 function get_departments($ignore_dn= "")
758   global $config;
760   /* Initialize result hash */
761   $result= array();
762   $result['/']= $config->current['BASE'];
764   /* Get list of department objects */
765   $ldap= $config->get_ldap_link();
766   $ldap->cd ($config->current['BASE']);
767   $ldap->search ("(objectClass=gosaDepartment)", array("ou"));
768   while ($attrs= $ldap->fetch()){
769     $dn= $ldap->getDN();
770     if ($dn == $ignore_dn){
771       continue;
772     }
773     $result[convert_department_dn($dn)]= $dn;
774   }
776   return ($result);
780 function chkacl($acl, $name)
782   /* Look for attribute in ACL */
783   if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
784     return ("");
785   }
787   /* Optically disable html object for no match */
788   return (" disabled ");
792 function is_phone_nr($nr)
794   if ($nr == ""){
795     return (TRUE);
796   }
798   return preg_match ("/^[0-9 ()+*-]+$/", $nr);
802 function is_url($url)
804   if ($url == ""){
805     return (TRUE);
806   }
808   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
812 function is_dn($dn)
814   if ($dn == ""){
815     return (TRUE);
816   }
818   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
822 function is_uid($uid)
824   global $config;
826   if ($uid == ""){
827     return (TRUE);
828   }
830   /* STRICT adds spaces and case insenstivity to the uid check.
831      This is dangerous and should not be used. */
832   if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
833     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
834   } else {
835     return preg_match ("/^[a-z0-9_-]+$/", $uid);
836   }
840 function is_id($id)
842   if ($id == ""){
843     return (FALSE);
844   }
846   return preg_match ("/^[0-9]+$/", $id);
850 function is_path($path)
852   if ($path == ""){
853     return (TRUE);
854   }
855   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
856     return (FALSE);
857   }
859   return preg_match ("/\/.+$/", $path);
863 function is_email($address, $template= FALSE)
865   if ($address == ""){
866     return (TRUE);
867   }
868   if ($template){
869     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
870         $address);
871   } else {
872     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
873         $address);
874   }
878 function print_red()
880   /* Check number of arguments */
881   if (func_num_args() < 1){
882     return;
883   }
885   /* Get arguments, save string */
886   $array = func_get_args();
887   $string= $array[0];
889   /* Step through arguments */
890   for ($i= 1; $i<count($array); $i++){
891     $string= preg_replace ("/%s/", $array[$i], $string, 1);
892   }
894   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
895      the other case... */
896   if (isset($_SESSION['DEBUGLEVEL'])){
897     $_SESSION['errors'].= "<div align=\"left\" style=\"border-width:5px;".
898       "border-style:solid;border-color:red; background-color:black;".
899       "margin-bottom:10px; padding:8px;\"><table summary=''><tr><td><img alt=\"\" src=\"".
900       get_template_path('images/warning.png')."\"></td>".
901       "<td width=\"100%\" align=\"center\"><font color=\"#FFFFFF\">".
902       "<b style='font-size:16px;'>$string</b></font></td><td>".
903       "<img alt=\"\"src=\"".get_template_path('images/warning.png').
904       "\"></td></tr></table></div>\n";
905   } else {
906     echo "Error: $string\n";
907   }
911 function gen_locked_message($user, $dn)
913   global $plug, $config;
915   $_SESSION['dn']= $dn;
916   $ldap= $config->get_ldap_link();
917   $ldap->cat ($user);
918   $attrs= $ldap->fetch();
919   $uid= $attrs["uid"][0];
921   /* Prepare and show template */
922   $smarty= get_smarty();
923   $smarty->assign ("dn", $dn);
924   $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>"));
926   return ($smarty->fetch (get_template_path('islocked.tpl')));
930 function to_string ($value)
932   /* If this is an array, generate a text blob */
933   if (is_array($value)){
934     $ret= "";
935     foreach ($value as $line){
936       $ret.= $line."<br>\n";
937     }
938     return ($ret);
939   } else {
940     return ($value);
941   }
945 function get_printer_list($cups_server)
947   global $config;
949   $res= array();
951   /* Use CUPS, if we've access to it */
952   if (function_exists('cups_get_dest_list')){
953     $dest_list= cups_get_dest_list ($cups_server);
955     foreach ($dest_list as $prt){
956       $attr= cups_get_printer_attributes ($cups_server, $prt->name);
958       foreach ($attr as $prt_info){
959         if ($prt_info->name == "printer-info"){
960           $info= $prt_info->value;
961           break;
962         }
963       }
964       $res[$prt->name]= "$info [$prt->name]";
965     }
967     /* CUPS is not available, try lpstat as a replacement */
968   } else {
969     unset ($ar);
970     exec("lpstat -p", $ar);
971     foreach($ar as $val){
972       list($dummy, $printer, $rest)= split(' ', $val, 3);
973       if (preg_match('/^[^@]+$/', $printer)){
974         $res[$printer]= "$printer";
975       }
976     }
977   }
979   /* Merge in printers from LDAP */
980   $ldap= $config->get_ldap_link();
981   $ldap->cd ($config->current['BASE']);
982   $ldap->search('(objectClass=gotoPrinter)', array('cn'));
983   while ($attrs= $ldap->fetch()){
984     $res[$attrs["cn"][0]]= $attrs["cn"][0];
985   }
987   return $res;
991 function sess_del ($var)
993   /* New style */
994   unset ($_SESSION[$var]);
996   /* ... work around, since the first one
997      doesn't seem to work all the time */
998   session_unregister ($var);
1002 function show_errors($message)
1004   $complete= "";
1006   /* Assemble the message array to a plain string */
1007   foreach ($message as $error){
1008     if ($complete == ""){
1009       $complete= $error;
1010     } else {
1011       $complete= "$error<br>$complete";
1012     }
1013   }
1015   /* Fill ERROR variable with nice error dialog */
1016   print_red($complete);
1020 function show_ldap_error($message)
1022   if (!preg_match("/Success/i", $message)){
1023     print_red (_("LDAP error:")." $message");
1024     return TRUE;
1025   } else {
1026     return FALSE;
1027   }
1031 function rewrite($s)
1033   global $REWRITE;
1035   foreach ($REWRITE as $key => $val){
1036     $s= preg_replace("/$key/", "$val", $s);
1037   }
1039   return ($s);
1043 function dn2base($dn)
1045   global $config;
1047   if (get_people_ou() != ""){
1048     $dn= preg_replace('/,'.get_people_ou().'/' , ',', $dn);
1049   }
1050   if (get_groups_ou() != ""){
1051     $dn= preg_replace('/,'.get_groups_ou().'/' , ',', $dn);
1052   }
1053   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1055   return ($base);
1060 function check_command($cmdline)
1062   $cmd= preg_replace("/ .*$/", "", $cmdline);
1064   /* Check if command exists in filesystem */
1065   if (!file_exists($cmd)){
1066     return (FALSE);
1067   }
1069   /* Check if command is executable */
1070   if (!is_executable($cmd)){
1071     return (FALSE);
1072   }
1074   return (TRUE);
1078 function print_header($image, $headline, $info= "")
1080   $display= "<div class=\"plugtop\">\n";
1081   $display.= "  <img src=\"$image\" align=\"middle\" alt=\"*\">&nbsp;$headline\n";
1082   $display.= "</div>\n";
1084   if ($info != ""){
1085     $display.= "<div class=\"pluginfo\">\n";
1086     $display.= "$info";
1087     $display.= "</div>\n";
1088   } else {
1089     $display.= "<div style=\"height:5px;\">\n";
1090     $display.= "&nbsp;";
1091     $display.= "</div>\n";
1092   }
1094   return ($display);
1098 function register_global($name, $object)
1100   $_SESSION[$name]= $object;
1104 function is_global($name)
1106   return isset($_SESSION[$name]);
1110 function get_global($name)
1112   return $_SESSION[$name];
1116 function range_selector($dcnt,$start,$range=25)
1119   /* Entries shown left and right from the selected entry */
1120   $max_entries= 10;
1122   /* Initialize and take care that max_entries is even */
1123   $output="";
1124   if ($max_entries & 1){
1125     $max_entries++;
1126   }
1128   /* Prevent output to start or end out of range */
1129   if ($start < 0 ){
1130     $start= 0 ;
1131   }
1132   if ($start >= $dcnt){
1133     $start= $range * (int)(($dcnt / $range) + 0.5);
1134   }
1136   $numpages= (($dcnt / $range));
1137   if(((int)($numpages))!=($numpages))
1138     $numpages = (int)$numpages + 1;
1139   $ppage= (int)(($start / $range) + 0.5);
1142   /* Align selected page to +/- max_entries/2 */
1143   $begin= $ppage - $max_entries/2;
1144   $end= $ppage + $max_entries/2;
1146   /* Adjust begin/end, so that the selected value is somewhere in
1147      the middle and the size is max_entries if possible */
1148   if ($begin < 0){
1149     $end-= $begin + 1;
1150     $begin= 0;
1151   }
1152   if ($end > $numpages) {
1153     $end= $numpages;
1154   }
1155   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1156     $begin= $end - $max_entries;
1157   }
1159   /* Draw decrement */
1160   if ($start > 0 ) {
1161     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1162       (($start-$range))."\">".
1163       "<img alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1164   }
1166   /* Draw pages */
1167   for ($i= $begin; $i < $end; $i++) {
1168     if ($ppage == $i){
1169       $output.= "<a style=\"background-color:#D0D0D0;\" href=\"main.php?plug=".
1170         validate($_GET['plug'])."&amp;start=".
1171         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1172     } else {
1173       $output.= "<a href=\"main.php?plug=".validate($_GET['plug']).
1174         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1175     }
1176   }
1178   /* Draw increment */
1179   if($start < ($dcnt-$range)) {
1180     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1181       (($start+($range)))."\">".
1182       "<img alt=\"\" src=\"images/forward.png\" border=0 align=\"middle\"></a>";
1183   }
1185   return($output);
1189 function apply_filter()
1191   $apply= "";
1193   $apply= ''.
1194     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1195     '<input type="submit" name="apply" value="'._("Apply").'"></td></tr></table>';
1197   return ($apply);
1201 function back_to_main()
1203   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1204     _("Back").'"></p><input type="hidden" name="ignore">';
1206   return ($string);
1210 function normalize_netmask($netmask)
1212   /* Check for notation of netmask */
1213   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1214     $num= (int)($netmask);
1215     $netmask= "";
1217     for ($byte= 0; $byte<4; $byte++){
1218       $result=0;
1220       for ($i= 7; $i>=0; $i--){
1221         if ($num-- > 0){
1222           $result+= pow(2,$i);
1223         }
1224       }
1226       $netmask.= $result.".";
1227     }
1229     return (preg_replace('/\.$/', '', $netmask));
1230   }
1232   return ($netmask);
1236 function netmask_to_bits($netmask)
1238   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1239   $res= 0;
1241   for ($n= 0; $n<4; $n++){
1242     $start= 255;
1243     $name= "nm$n";
1245     for ($i= 0; $i<8; $i++){
1246       if ($start == (int)($$name)){
1247         $res+= 8 - $i;
1248         break;
1249       }
1250       $start-= pow(2,$i);
1251     }
1252   }
1254   return ($res);
1258 function recurse($rule, $variables)
1260   $result= array();
1262   if (!count($variables)){
1263     return array($rule);
1264   }
1266   reset($variables);
1267   $key= key($variables);
1268   $val= current($variables);
1269   unset ($variables[$key]);
1271   foreach($val as $possibility){
1272     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1273     $result= array_merge($result, recurse($nrule, $variables));
1274   }
1276   return ($result);
1280 function expand_id($rule, $attributes)
1282   /* Check for id rule */
1283   if(preg_match('/^id(:|#)\d+$/',$rule)){
1284     return (array("\{$rule}"));
1285   }
1287   /* Check for clean attribute */
1288   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1289     $rule= preg_replace('/^%/', '', $rule);
1290     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1291     return (array($val));
1292   }
1294   /* Check for attribute with parameters */
1295   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1296     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1297     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1298     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1299     $start= preg_replace ('/-.*$/', '', $param);
1300     $stop = preg_replace ('/^[^-]+-/', '', $param);
1302     /* Assemble results */
1303     $result= array();
1304     for ($i= $start; $i<= $stop; $i++){
1305       $result[]= substr($val, 0, $i);
1306     }
1307     return ($result);
1308   }
1310   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1311   return (array($rule));
1315 function gen_uids($rule, $attributes)
1317   global $config;
1319   /* Search for keys and fill the variables array with all 
1320      possible values for that key. */
1321   $part= "";
1322   $trigger= false;
1323   $stripped= "";
1324   $variables= array();
1326   for ($pos= 0; $pos < strlen($rule); $pos++){
1328     if ($rule[$pos] == "{" ){
1329       $trigger= true;
1330       $part= "";
1331       continue;
1332     }
1334     if ($rule[$pos] == "}" ){
1335       $variables[$pos]= expand_id($part, $attributes);
1336       $stripped.= "\{$pos}";
1337       $trigger= false;
1338       continue;
1339     }
1341     if ($trigger){
1342       $part.= $rule[$pos];
1343     } else {
1344       $stripped.= $rule[$pos];
1345     }
1346   }
1348   /* Recurse through all possible combinations */
1349   $proposed= recurse($stripped, $variables);
1351   /* Get list of used ID's */
1352   $used= array();
1353   $ldap= $config->get_ldap_link();
1354   $ldap->cd($config->current['BASE']);
1355   $ldap->search('(uid=*)');
1357   while($attrs= $ldap->fetch()){
1358     $used[]= $attrs['uid'][0];
1359   }
1361   /* Remove used uids and watch out for id tags */
1362   $ret= array();
1363   foreach($proposed as $uid){
1365     /* Check for id tag and modify uid if needed */
1366     if(preg_match('/\{id:\d+}/',$uid)){
1367       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1369       for ($i= 0; $i < pow(10,$size); $i++){
1370         $number= sprintf("%0".$size."d", $i);
1371         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1372         if (!in_array($res, $used)){
1373           $uid= $res;
1374           break;
1375         }
1376       }
1377     }
1379     if(preg_match('/\{id#\d+}/',$uid)){
1380       $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1382       while (true){
1383         mt_srand((double) microtime()*1000000);
1384         $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1385         $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1386         if (!in_array($res, $used)){
1387           $uid= $res;
1388           break;
1389         }
1390       }
1391     }
1393     /* Don't assign used ones */
1394     if (!in_array($uid, $used)){
1395       $ret[]= $uid;
1396     }
1397   }
1399   return(array_unique($ret));
1403 function array_search_r($needle, $key, $haystack){
1405   foreach($haystack as $index => $value){
1406     $match= 0;
1408     if (is_array($value)){
1409       $match= array_search_r($needle, $key, $value);
1410     }
1412     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1413       $match=1;
1414     }
1416     if ($match){
1417       return 1;
1418     }
1419   }
1421   return 0;
1422
1425 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1426    Need to convert... */
1427 function to_byte($value) {
1428   $value= strtolower(trim($value));
1430   if(!is_numeric(substr($value, -1))) {
1432     switch(substr($value, -1)) {
1433       case 'g':
1434         $mult= 1073741824;
1435         break;
1436       case 'm':
1437         $mult= 1048576;
1438         break;
1439       case 'k':
1440         $mult= 1024;
1441         break;
1442     }
1444     return ($mult * (int)substr($value, 0, -1));
1445   } else {
1446     return $value;
1447   }
1451 function in_array_ics($value, $items)
1453   if (!is_array($items)){
1454     return (FALSE);
1455   }
1456   
1457   foreach ($items as $item){
1458     if (strtolower($item) == strtolower($value)) {
1459       return (TRUE);
1460     }
1461   }
1463   return (FALSE);
1464
1467 function generate_alphabet($count= 10)
1469   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1470   $alphabet= "";
1471   $c= 0;
1473   /* Fill cells with charaters */
1474   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1475     if ($c == 0){
1476       $alphabet.= "<tr>";
1477     }
1479     $ch = mb_substr($characters, $i, 1, "UTF8");
1480     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1481       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1483     if ($c++ == $count){
1484       $alphabet.= "</tr>";
1485       $c= 0;
1486     }
1487   }
1489   /* Fill remaining cells */
1490   while ($c++ <= $count){
1491     $alphabet.= "<td>&nbsp;</td>";
1492   }
1494   return ($alphabet);
1498 function validate($string)
1500   return (strip_tags(preg_replace('/\0/', '', $string)));
1503 function get_gosa_version()
1505   global $svn_revision, $svn_path;
1507   /* Extract informations */
1508   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1510   /* Release or development? */
1511   if (preg_match('%/gosa/trunk/%', $svn_path)){
1512     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1513   } else {
1514     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1515     return (sprintf(_("GOsa $release"), $revision));
1516   }
1520 function rmdirRecursive($path, $followLinks=false) {
1521   $dir= opendir($path);
1522   while($entry= readdir($dir)) {
1523     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1524       unlink($path."/".$entry);
1525     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1526       rmdirRecursive($path."/".$entry);
1527     }
1528   }
1529   closedir($dir);
1530   return rmdir($path);
1533 function scan_directory($path,$sort_desc=false)
1535 $ret = false;
1537 /* is this a dir ? */
1538 if(is_dir($path)) {
1539   
1540   /* is this path a readable one */
1541   if(is_readable($path)){
1542     
1543     /* Get contents and write it into an array */   
1544     $ret = array();    
1545   
1546     $dir = opendir($path);
1547     
1548     /* Is this a correct result ?*/
1549     if($dir){
1550       while($fp = readdir($dir))
1551         $ret[]= $fp;
1552       }
1553     }
1554   }
1555   /* Sort array ascending , like scandir */
1556   sort($ret);
1558   /* Sort descending if parameter is sort_desc is set */
1559   if($sort_desc) {
1560     $ret = array_reverse($ret);
1561     }
1563   return($ret);
1566 function clean_smarty_compile_dir($directory)
1568   global $svn_revision;
1570   if(is_dir($directory) && is_readable($directory)) {
1571     // Set revision filename to REVISION
1572     $revision_file= $directory."/REVISION";
1574     /* Is there a stamp containing the current revision? */
1575     if(!file_exists($revision_file)) {
1576       // create revision file
1577       create_revision($revision_file, $svn_revision);
1578     } else {
1579       # check for "$config->...['CONFIG']/revision" and the
1580       # contents should match the revision number
1581       if(!compare_revision($revision_file, $svn_revision)){
1582         // If revision differs, clean compile directory
1583         foreach(scan_directory($directory) as $file) {
1584           if( is_file($directory."/".$file) &&
1585               is_writable($directory."/".$file)) {
1586               // delete file
1587               if(!unlink($directory."/".$file)) {
1588                 print_red("File ".$directory."/".$file." could not be deleted.");
1589                 // This should never be reached
1590               }
1591           } elseif(is_dir($directory."/".$file) &&
1592                     is_writable($directory."/".$file)) {
1593                     // Just recursively delete it
1594              rmdirRecursive($directory."/".$file);
1595           }
1596         }
1597         // We should now create a fresh revision file
1598         clean_smarty_compile_dir($directory);
1599       } else {
1600         // Revision matches, nothing to do
1601       }
1602     }
1603   } else {
1604     // Smarty compile dir is not accessible
1605     // (Smarty will warn about this)
1606   }
1609 function create_revision($revision_file, $revision)
1611   $result= false;
1612   
1613   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1614     if($fh= fopen($revision_file, "w")) {
1615       if(fwrite($fh, $revision)) {
1616         $result= true;
1617       }
1618     }
1619     fclose($fh);
1620   } else {
1621     print_red("Can not write to revision file");
1622   }
1624   return $result;
1627 function compare_revision($revision_file, $revision)
1629   // false means revision differs
1630   $result= false;
1631   
1632   if(file_exists($revision_file) && is_readable($revision_file)) {
1633     // Open file
1634     if($fh= fopen($revision_file, "r")) {
1635       // Compare File contents with current revision
1636       if($revision == fread($fh, filesize($revision_file))) {
1637         $result= true;
1638       }
1639     } else {
1640       print_red("Can not open revision file");
1641     }
1642     // Close file
1643     fclose($fh);
1644   }
1646   return $result;
1649 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1651   $str = ""; // Our return value will be saved in this var
1653   $color  = dechex($percentage+150);
1654   $color2 = dechex(150 - $percentage);
1655   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1657   $progress = (int)(($percentage /100)*$width);
1659   /* Abort printing out percentage, if divs are to small */
1662   /* If theres a better solution for this, use it... */
1663   $str = "
1664     <div style=\" width:".($width)."px; 
1665     height:".($height)."px;
1666   background-color:#000000;
1667 padding:1px;\">
1669           <div style=\" width:".($width)."px;
1670         background-color:#$bgcolor;
1671 height:".($height)."px;\">
1673          <div style=\" width:".$progress."px;
1674 height:".$height."px;
1675        background-color:#".$color2.$color2.$color."; \">";
1678        if(($height >10)&&($showvalue)){
1679          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1680            <b>".$percentage."%</b>
1681            </font>";
1682        }
1684        $str.= "</div></div></div>";
1686        return($str);
1690 function search_config($arr, $name, $return)
1692   if (is_array($arr)){
1693     foreach ($arr as $a){
1694       if (isset($a['CLASS']) &&
1695           strtolower($a['CLASS']) == strtolower($name)){
1697         if (isset($a[$return])){
1698           return ($a[$return]);
1699         } else {
1700           return ("");
1701         }
1702       } else {
1703         $res= search_config ($a, $name, $return);
1704         if ($res != ""){
1705           return $res;
1706         }
1707       }
1708     }
1709   }
1710   return ("");
1714 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1715 ?>