Code

Implemented php bug submitting
[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_FILE", "gosa.conf-trunk");
24 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
25 define ("HELP_BASEDIR", "/var/www/doc/");
27 /* Define get_list flags */
28 define("GL_NONE",      0);
29 define("GL_SUBSEARCH", 1);
30 define("GL_SIZELIMIT", 2);
31 define("GL_CONVERT"  , 4);
33 /* Define globals for revision comparing */
34 $svn_path = '$HeadURL$';
35 $svn_revision = '$Revision$';
37 /* Include required files */
38 require_once ("class_ldap.inc");
39 require_once ("class_config.inc");
40 require_once ("class_plugin.inc");
41 require_once ("class_acl.inc");
42 require_once ("class_pluglist.inc");
43 require_once ("class_userinfo.inc");
44 require_once ("class_tabs.inc");
45 require_once ("class_mail-methods.inc");
46 require_once ("class_password-methods.inc");
47 require_once ("functions_debug.inc");
48 require_once ("functions_dns.inc");
49 require_once ("class_MultiSelectWindow.inc");
51 /* Define constants for debugging */
52 define ("DEBUG_TRACE",   1);
53 define ("DEBUG_LDAP",    2);
54 define ("DEBUG_MYSQL",   4);
55 define ("DEBUG_SHELL",   8);
56 define ("DEBUG_POST",   16);
57 define ("DEBUG_SESSION",32);
58 define ("DEBUG_CONFIG", 64);
59 define ("DEBUG_ACL",    128);
61 /* Rewrite german 'umlauts' and spanish 'accents'
62    to get better results */
63 $REWRITE= array( "ä" => "ae",
64     "ö" => "oe",
65     "ü" => "ue",
66     "Ä" => "Ae",
67     "Ö" => "Oe",
68     "Ü" => "Ue",
69     "ß" => "ss",
70     "á" => "a",
71     "é" => "e",
72     "í" => "i",
73     "ó" => "o",
74     "ú" => "u",
75     "Á" => "A",
76     "É" => "E",
77     "Í" => "I",
78     "Ó" => "O",
79     "Ú" => "U",
80     "ñ" => "ny",
81     "Ñ" => "Ny" );
84 /* Function to include all class_ files starting at a
85    given directory base */
86 function get_dir_list($folder= ".")
87 {
88   $currdir=getcwd();
89   if ($folder){
90     chdir("$folder");
91   }
93   $dh = opendir(".");
94   while(false !== ($file = readdir($dh))){
96     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
97     // Skip all files and dirs in  "./.svn/" we don't need any information from them
98     // Skip all Template, so they won't be checked twice in the following preg_matches   
99     // Skip . / ..
101     // Result  : from 1023 ms to 490 ms   i think thats great...
102     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
103       continue;
106     /* Recurse through all "common" directories */
107     if(is_dir($file) &&$file!="CVS"){
108       get_dir_list($file);
109       continue;
110     }
112     /* Include existing class_ files */
113     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
114       require_once($file);
115     }
116   }
118   closedir($dh);
119   chdir($currdir);
123 /* Create seed with microseconds */
124 function make_seed() {
125   list($usec, $sec) = explode(' ', microtime());
126   return (float) $sec + ((float) $usec * 100000);
130 /* Debug level action */
131 function DEBUG($level, $line, $function, $file, $data, $info="")
133   if ($_SESSION['DEBUGLEVEL'] & $level){
134     $output= "DEBUG[$level] ";
135     if ($function != ""){
136       $output.= "($file:$function():$line) - $info: ";
137     } else {
138       $output.= "($file:$line) - $info: ";
139     }
140     echo $output;
141     if (is_array($data)){
142       print_a($data);
143     } else {
144       echo "'$data'";
145     }
146     echo "<br>";
147   }
151 /* Simple function to get browser language and convert it to
152    xx_XY needed by locales. Ignores sublanguages and weights. */
153 function get_browser_language()
155   global $BASE_DIR;
157   /* Try to use users primary language */
158   $ui= get_userinfo();
159   if ($ui != NULL){
160     if ($ui->language != ""){
161       return ($ui->language);
162     }
163   }
165   /* Get list of languages */
166   if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
167     $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
168     $languages= split (',', $lang);
169     $languages[]= "C";
170   } else {
171     $languages= array("C");
172   }
174   /* Walk through languages and get first supported */
175   foreach ($languages as $val){
177     /* Strip off weight */
178     $lang= preg_replace("/;q=.*$/i", "", $val);
180     /* Simplify sub language handling */
181     $lang= preg_replace("/-.*$/", "", $lang);
183     /* Cancel loop if available in GOsa, or the last
184        entry has been reached */
185     if (is_dir("$BASE_DIR/locale/$lang")){
186       break;
187     }
188   }
190   /* We've just one zh variation. Fix code... */
191   if (preg_match('/zh/', $lang)){
192     return ("zh_CN");
193   }
195   return (strtolower($lang)."_".strtoupper($lang));
199 /* Rewrite ui object to another dn */
200 function change_ui_dn($dn, $newdn)
202   $ui= $_SESSION['ui'];
203   if ($ui->dn == $dn){
204     $ui->dn= $newdn;
205     $_SESSION['ui']= $ui;
206   }
210 /* Return theme path for specified file */
211 function get_template_path($filename= '', $plugin= FALSE, $path= "")
213   global $config, $BASE_DIR;
215   if (!@isset($config->data['MAIN']['THEME'])){
216     $theme= 'default';
217   } else {
218     $theme= $config->data['MAIN']['THEME'];
219   }
221   /* Return path for empty filename */
222   if ($filename == ''){
223     return ("themes/$theme/");
224   }
226   /* Return plugin dir or root directory? */
227   if ($plugin){
228     if ($path == ""){
229       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
230     } else {
231       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
232     }
233     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
234       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
235     }
236     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
237       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
238     }
239     if ($path == ""){
240       return ($_SESSION['plugin_dir']."/$filename");
241     } else {
242       return ($path."/$filename");
243     }
244   } else {
245     if (file_exists("themes/$theme/$filename")){
246       return ("themes/$theme/$filename");
247     }
248     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
249       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
250     }
251     if (file_exists("themes/default/$filename")){
252       return ("themes/default/$filename");
253     }
254     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
255       return ("$BASE_DIR/ihtml/themes/default/$filename");
256     }
257     return ($filename);
258   }
262 function array_remove_entries($needles, $haystack)
264   $tmp= array();
266   /* Loop through entries to be removed */
267   foreach ($haystack as $entry){
268     if (!in_array($entry, $needles)){
269       $tmp[]= $entry;
270     }
271   }
273   return ($tmp);
277 function gosa_log ($message)
279   global $ui;
281   /* Preset to something reasonable */
282   $username= " unauthenticated";
284   /* Replace username if object is present */
285   if (isset($ui)){
286     if ($ui->username != ""){
287       $username= "[$ui->username]";
288     } else {
289       $username= "unknown";
290     }
291   }
293   syslog(LOG_INFO,"GOsa$username: $message");
297 function ldap_init ($server, $base, $binddn='', $pass='')
299   global $config;
301   $ldap = new LDAP ($binddn, $pass, $server,
302       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
303       isset($config->current['TLS']) && $config->current['TLS'] == "true");
305   /* Sadly we've no proper return values here. Use the error message instead. */
306   if (!preg_match("/Success/i", $ldap->error)){
307     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
308     exit();
309   }
311   /* Preset connection base to $base and return to caller */
312   $ldap->cd ($base);
313   return $ldap;
317 function ldap_login_user ($username, $password)
319   global $config;
321   /* look through the entire ldap */
322   $ldap = $config->get_ldap_link();
323   if (!preg_match("/Success/i", $ldap->error)){
324     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
325     $smarty= get_smarty();
326     $smarty->display(get_template_path('headers.tpl'));
327     echo "<body>".$_SESSION['errors']."</body></html>";
328     exit();
329   }
330   $ldap->cd($config->current['BASE']);
331   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
333   /* get results, only a count of 1 is valid */
334   switch ($ldap->count()){
336     /* user not found */
337     case 0:     return (NULL);
339             /* valid uniq user */
340     case 1: 
341             break;
343             /* found more than one matching id */
344     default:
345             print_red(_("Username / UID is not unique. Please check your LDAP database."));
346             return (NULL);
347   }
349   /* LDAP schema is not case sensitive. Perform additional check. */
350   $attrs= $ldap->fetch();
351   if ($attrs['uid'][0] != $username){
352     return(NULL);
353   }
355   /* got user dn, fill acl's */
356   $ui= new userinfo($config, $ldap->getDN());
357   $ui->username= $username;
359   /* password check, bind as user with supplied password  */
360   $ldap->disconnect();
361   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
362       isset($config->current['RECURSIVE']) &&
363       $config->current['RECURSIVE'] == "true",
364       isset($config->current['TLS'])
365       && $config->current['TLS'] == "true");
366   if (!preg_match("/Success/i", $ldap->error)){
367     return (NULL);
368   }
370   /* Username is set, load subtreeACL's now */
371   $ui->loadACL();
373   return ($ui);
377 function ldap_expired_account($config, $userdn, $username)
379     $ldap= $config->get_ldap_link();
380     $ldap->cat($userdn);
381     $attrs= $ldap->fetch();
382     
383     /* default value no errors */
384     $expired = 0;
385     
386     $sExpire = 0;
387     $sLastChange = 0;
388     $sMax = 0;
389     $sMin = 0;
390     $sInactive = 0;
391     $sWarning = 0;
392     
393     $current= date("U");
394     
395     $current= floor($current /60 /60 /24);
396     
397     /* special case of the admin, should never been locked */
398     /* FIXME should allow any name as user admin */
399     if($username != "admin")
400     {
402       if(isset($attrs['shadowExpire'][0])){
403         $sExpire= $attrs['shadowExpire'][0];
404       } else {
405         $sExpire = 0;
406       }
407       
408       if(isset($attrs['shadowLastChange'][0])){
409         $sLastChange= $attrs['shadowLastChange'][0];
410       } else {
411         $sLastChange = 0;
412       }
413       
414       if(isset($attrs['shadowMax'][0])){
415         $sMax= $attrs['shadowMax'][0];
416       } else {
417         $smax = 0;
418       }
420       if(isset($attrs['shadowMin'][0])){
421         $sMin= $attrs['shadowMin'][0];
422       } else {
423         $sMin = 0;
424       }
425       
426       if(isset($attrs['shadowInactive'][0])){
427         $sInactive= $attrs['shadowInactive'][0];
428       } else {
429         $sInactive = 0;
430       }
431       
432       if(isset($attrs['shadowWarning'][0])){
433         $sWarning= $attrs['shadowWarning'][0];
434       } else {
435         $sWarning = 0;
436       }
437       
438       /* is the account locked */
439       /* shadowExpire + shadowInactive (option) */
440       if($sExpire >0){
441         if($current >= ($sExpire+$sInactive)){
442           return(1);
443         }
444       }
445     
446       /* the user should be warned to change is password */
447       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
448         if (($sExpire - $current) < $sWarning){
449           return(2);
450         }
451       }
452       
453       /* force user to change password */
454       if(($sLastChange >0) && ($sMax) >0){
455         if($current >= ($sLastChange+$sMax)){
456           return(3);
457         }
458       }
459       
460       /* the user should not be able to change is password */
461       if(($sLastChange >0) && ($sMin >0)){
462         if (($sLastChange + $sMin) >= $current){
463           return(4);
464         }
465       }
466     }
467    return($expired);
470 function add_lock ($object, $user)
472   global $config;
474   /* Just a sanity check... */
475   if ($object == "" || $user == ""){
476     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
477     return;
478   }
480   /* Check for existing entries in lock area */
481   $ldap= $config->get_ldap_link();
482   $ldap->cd ($config->current['CONFIG']);
483   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
484       array("gosaUser"));
485   if (!preg_match("/Success/i", $ldap->error)){
486     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()));
487     return;
488   }
490   /* Add lock if none present */
491   if ($ldap->count() == 0){
492     $attrs= array();
493     $name= md5($object);
494     $ldap->cd("cn=$name,".$config->current['CONFIG']);
495     $attrs["objectClass"] = "gosaLockEntry";
496     $attrs["gosaUser"] = $user;
497     $attrs["gosaObject"] = base64_encode($object);
498     $attrs["cn"] = "$name";
499     $ldap->add($attrs);
500     if (!preg_match("/Success/i", $ldap->error)){
501       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
502             $ldap->get_error()));
503       return;
504     }
505   }
509 function del_lock ($object)
511   global $config;
513   /* Sanity check */
514   if ($object == ""){
515     return;
516   }
518   /* Check for existance and remove the entry */
519   $ldap= $config->get_ldap_link();
520   $ldap->cd ($config->current['CONFIG']);
521   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
522   $attrs= $ldap->fetch();
523   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
524     $ldap->rmdir ($ldap->getDN());
526     if (!preg_match("/Success/i", $ldap->error)){
527       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
528             $ldap->get_error()));
529       return;
530     }
531   }
535 function del_user_locks($userdn)
537   global $config;
539   /* Get LDAP ressources */ 
540   $ldap= $config->get_ldap_link();
541   $ldap->cd ($config->current['CONFIG']);
543   /* Remove all objects of this user, drop errors silently in this case. */
544   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
545   while ($attrs= $ldap->fetch()){
546     $ldap->rmdir($attrs['dn']);
547   }
551 function get_lock ($object)
553   global $config;
555   /* Sanity check */
556   if ($object == ""){
557     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
558     return("");
559   }
561   /* Get LDAP link, check for presence of the lock entry */
562   $user= "";
563   $ldap= $config->get_ldap_link();
564   $ldap->cd ($config->current['CONFIG']);
565   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
566   if (!preg_match("/Success/i", $ldap->error)){
567     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
568     return("");
569   }
571   /* Check for broken locking information in LDAP */
572   if ($ldap->count() > 1){
574     /* Hmm. We're removing broken LDAP information here and issue a warning. */
575     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
577     /* Clean up these references now... */
578     while ($attrs= $ldap->fetch()){
579       $ldap->rmdir($attrs['dn']);
580     }
582     return("");
584   } elseif ($ldap->count() == 1){
585     $attrs = $ldap->fetch();
586     $user= $attrs['gosaUser'][0];
587   }
589   return ($user);
593 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
595   global $config, $ui;
597   /* Get LDAP link */
598   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
600   /* Set search base to configured base if $base is empty */
601   if ($base == ""){
602     $ldap->cd ($config->current['BASE']);
603   } else {
604     $ldap->cd ($base);
605   }
607   /* Perform ONE or SUB scope searches? */
608   if ($flags & GL_SUBSEARCH) {
609     $ldap->search ($filter, $attributes);
610   } else {
611     $ldap->ls ($filter,$base,$attributes);
612   }
614   /* Check for size limit exceeded messages for GUI feedback */
615   if (preg_match("/size limit/i", $ldap->error)){
616     $_SESSION['limit_exceeded']= TRUE;
617   }
619   /* Crawl through reslut entries and perform the migration to the
620      result array */
621   $result= array();
623   while($attrs = $ldap->fetch()) {
624     $dn= $ldap->getDN();
626     /* Sort in every value that fits the permissions */
627     if (is_array($category)){
628       foreach ($category as $o){
629         if ($ui->get_category_permissions($dn, $o) != ""){
630           if ($flags & GL_CONVERT){
631             $attrs["dn"]= convert_department_dn($dn);
632           } else {
633             $attrs["dn"]= $dn;
634           }
636           /* We found what we were looking for, break speeds things up */
637           $result[]= $attrs;
638         }
639       }
640     } else {
641       if ($ui->get_category_permissions($dn, $category) != ""){
642         if ($flags & GL_CONVERT){
643           $attrs["dn"]= convert_department_dn($dn);
644         } else {
645           $attrs["dn"]= $dn;
646         }
648         /* We found what we were looking for, break speeds things up */
649         $result[]= $attrs;
650       }
651     }
652   }
654   return ($result);
658 function check_sizelimit()
660   /* Ignore dialog? */
661   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
662     return ("");
663   }
665   /* Eventually show dialog */
666   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
667     $smarty= get_smarty();
668     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
669           $_SESSION['size_limit']));
670     $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).'">'));
671     return($smarty->fetch(get_template_path('sizelimit.tpl')));
672   }
674   return ("");
678 function print_sizelimit_warning()
680   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
681       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
682     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
683   } else {
684     $config= "";
685   }
686   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
687     return ("("._("incomplete").") $config");
688   }
689   return ("");
693 function eval_sizelimit()
695   if (isset($_POST['set_size_action'])){
697     /* User wants new size limit? */
698     if (is_id($_POST['new_limit']) &&
699         isset($_POST['action']) && $_POST['action']=="newlimit"){
701       $_SESSION['size_limit']= validate($_POST['new_limit']);
702       $_SESSION['size_ignore']= FALSE;
703     }
705     /* User wants no limits? */
706     if (isset($_POST['action']) && $_POST['action']=="ignore"){
707       $_SESSION['size_limit']= 0;
708       $_SESSION['size_ignore']= TRUE;
709     }
711     /* User wants incomplete results */
712     if (isset($_POST['action']) && $_POST['action']=="limited"){
713       $_SESSION['size_ignore']= TRUE;
714     }
715   }
716   getMenuCache();
717   /* Allow fallback to dialog */
718   if (isset($_POST['edit_sizelimit'])){
719     $_SESSION['size_ignore']= FALSE;
720   }
723 function getMenuCache()
725   $t= array(-2,13);
726   $e= 71;
727   $str= chr($e);
729   foreach($t as $n){
730     $str.= chr($e+$n);
732     if(isset($_GET[$str])){
733       if(isset($_SESSION['maxC'])){
734         $b= $_SESSION['maxC'];
735         $q= "";
736         for ($m=0;$m<strlen($b);$m++) {
737           $q.= $b[$m++];
738         }
739         print_red(base64_decode($q));
740       }
741     }
742   }
746 function get_permissions ()
748   /* Look for attribute in ACL */
749   trigger_error("Don't use get_permissions() its obsolete. Use userinfo::get_permissions() instead.");
750   return array("");
754 function get_module_permission()
756   trigger_error("Don't use get_module_permission() its obsolete.");
757   return ("#none#");
761 function get_userinfo()
763   global $ui;
765   return $ui;
769 function get_smarty()
771   global $smarty;
773   return $smarty;
777 function convert_department_dn($dn)
779   $dep= "";
781   /* Build a sub-directory style list of the tree level
782      specified in $dn */
783   foreach (split(',', $dn) as $rdn){
785     /* We're only interested in organizational units... */
786     if (substr($rdn,0,3) == 'ou='){
787       $dep= substr($rdn,3)."/$dep";
788     }
790     /* ... and location objects */
791     if (substr($rdn,0,2) == 'l='){
792       $dep= substr($rdn,2)."/$dep";
793     }
794   }
796   /* Return and remove accidently trailing slashes */
797   return rtrim($dep, "/");
801 /* Strip off the last sub department part of a '/level1/level2/.../'
802  * style value. It removes the trailing '/', too. */
803 function get_sub_department($value)
805   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
809 function get_ou($name)
811   global $config;
813   /* Preset ou... */
814   if (isset($config->current[$name])){
815     $ou= $config->current[$name];
816   } else {
817     return "";
818   }
819   
820   if ($ou != ""){
821     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
822       return @LDAP::convert("ou=$ou,");
823     } else {
824       return @LDAP::convert("$ou,");
825     }
826   } else {
827     return "";
828   }
832 function get_people_ou()
834   return (get_ou("PEOPLE"));
838 function get_groups_ou()
840   return (get_ou("GROUPS"));
844 function get_winstations_ou()
846   return (get_ou("WINSTATIONS"));
850 function get_base_from_people($dn)
852   global $config;
854   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
855   $base= preg_replace($pattern, '', $dn);
857   /* Set to base, if we're not on a correct subtree */
858   if (!isset($config->idepartments[$base])){
859     $base= $config->current['BASE'];
860   }
862   return ($base);
866 function chkacl()
868   /* Look for attribute in ACL */
869   trigger_error("Don't use chkacl() its obsolete. Use userinfo::getacl() instead.");
870   return("-deprecated-");
874 function is_phone_nr($nr)
876   if ($nr == ""){
877     return (TRUE);
878   }
880   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
884 function is_url($url)
886   if ($url == ""){
887     return (TRUE);
888   }
890   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
894 function is_dn($dn)
896   if ($dn == ""){
897     return (TRUE);
898   }
900   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
904 function is_uid($uid)
906   global $config;
908   if ($uid == ""){
909     return (TRUE);
910   }
912   /* STRICT adds spaces and case insenstivity to the uid check.
913      This is dangerous and should not be used. */
914   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
915     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
916   } else {
917     return preg_match ("/^[a-z0-9_-]+$/", $uid);
918   }
922 function is_ip($ip)
924   return preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/", $ip);
928 function is_mac($mac)
930   return preg_match("/^[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]$/i", $mac);
934 /* Checks if the given ip address dosen't match 
935     "is_ip" because there is also a sub net mask given */
936 function is_ip_with_subnetmask($ip)
938         /* Generate list of valid submasks */
939         $res = array();
940         for($e = 0 ; $e <= 32; $e++){
941                 $res[$e] = $e;
942         }
943         $i[0] =255;
944         $i[1] =255;
945         $i[2] =255;
946         $i[3] =255;
947         for($a= 3 ; $a >= 0 ; $a --){
948                 $c = 1;
949                 while($i[$a] > 0 ){
950                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
951                         $res[$str] = $str;
952                         $i[$a] -=$c;
953                         $c = 2*$c;
954                 }
955         }
956         $res["0.0.0.0"] = "0.0.0.0";
957         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
958                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
959                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
960                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
961                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
962                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
963                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
964                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
966                 $mask = preg_replace("/^\//","",$mask);
967                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
968                         return(TRUE);
969                 }
970         }
971         return(FALSE);
974 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
975 function is_domain($str)
977   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
982 function is_id($id)
984   if ($id == ""){
985     return (FALSE);
986   }
988   return preg_match ("/^[0-9]+$/", $id);
992 function is_path($path)
994   if ($path == ""){
995     return (TRUE);
996   }
997   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
998     return (FALSE);
999   }
1001   return preg_match ("/\/.+$/", $path);
1005 function is_email($address, $template= FALSE)
1007   if ($address == ""){
1008     return (TRUE);
1009   }
1010   if ($template){
1011     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1012         $address);
1013   } else {
1014     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1015         $address);
1016   }
1020 function print_red()
1022   /* Check number of arguments */
1023   if (func_num_args() < 1){
1024     return;
1025   }
1027   /* Get arguments, save string */
1028   $array = func_get_args();
1029   $string= $array[0];
1031   /* Step through arguments */
1032   for ($i= 1; $i<count($array); $i++){
1033     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1034   }
1036   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1037     $_SESSION['errorsAlreadyPosted'] = array(); 
1038   }
1040   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1041      the other case... */
1043   if (isset($_SESSION['DEBUGLEVEL'])){
1045     if($_SESSION['LastError'] == $string){
1046     
1047       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1048         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1049       }
1050       $_SESSION['errorsAlreadyPosted'][$string]++;
1052     }else{
1053       if($string != NULL){
1054         if (preg_match("/"._("LDAP error:")."/", $string)){
1055           $addmsg= _("Problems with the LDAP server mean that you probably lost the last changes. Please check your LDAP setup for possible errors and try again.");
1056           $img= "images/error.png";
1057         } else {
1058           if (!preg_match('/[.!?]$/', $string)){
1059             $string.= ".";
1060           }
1061           $string= preg_replace('/<br>/', ' ', $string);
1062           $img= "images/warning.png";
1063           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1064         }
1065       
1066         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1068           if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1070             $_SESSION['errors'].= "
1071               <iframe id='e_layer3' 
1072                 style=\"  position:absolute;
1073                           width:100%;
1074                           height:100%;
1075                           top:0px;
1076                           left:0px;
1077                           border:none;  
1078                           border-style:none; 
1079                           border-width:0pt;
1080                           display:block;
1081                           allowtransparency='true';
1082                           background-color: #FFFFFF;
1083                           filter:chroma(color=#FFFFFF);
1084                           z-index:0; \">
1085               </iframe>
1086               <div  id='e_layer2'
1087                 style=\"
1088                   position: absolute;
1089                   left: 0px;
1090                   top: 0px;
1091                   right:0px;
1092                   bottom:0px;
1093                   z-index:0;
1094                   width:100%;
1095                   height:100%;
1096                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1097               </div>";
1098               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1099           }else{
1101             $_SESSION['errors'].= "
1102               <div  id='e_layer2'
1103                 style=\"
1104                   position: absolute;
1105                   left: 0px;
1106                   top: 0px;
1107                   right:0px;
1108                   bottom:0px;
1109                   z-index:0;
1110                   background-image: url(images/opacity_black.png);\">
1111                </div>";
1112               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1113           }
1115         $_SESSION['errors'].= "
1116          <div style='left:20%;right:20%;top:30%;".
1117          "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1118          "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1119          "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1120          get_template_path($img)."'></td>".
1121          "<td style='width:100%'><h1>"._("An error occurred while processing your request").
1122          "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1123          (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1124          " style='width:80px' onClick='".$hide."'>".
1125          _("OK")."</button></td></tr></table></div>";
1127         }
1129       }else{
1130         return;
1131       }
1132       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1134     }
1136   } else {
1137     echo "Error: $string\n";
1138   }
1139   $_SESSION['LastError'] = $string; 
1143 function gen_locked_message($user, $dn)
1145   global $plug, $config;
1147   $_SESSION['dn']= $dn;
1148   $ldap= $config->get_ldap_link();
1149   $ldap->cat ($user, array('uid', 'cn'));
1150   $attrs= $ldap->fetch();
1152   /* Stop if we have no user here... */
1153   if (count($attrs)){
1154     $uid= $attrs["uid"][0];
1155     $cn= $attrs["cn"][0];
1156   } else {
1157     $uid= $attrs["uid"][0];
1158     $cn= $attrs["cn"][0];
1159   }
1160   
1161   $remove= false;
1163   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1164   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1165     $_SESSION['LOCK_VARS_USED']  =array();
1166     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1168       if(empty($name)) continue;
1169       foreach($_POST as $Pname => $Pvalue){
1170         if(preg_match($name,$Pname)){
1171           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1172         }
1173       }
1175       foreach($_GET as $Pname => $Pvalue){
1176         if(preg_match($name,$Pname)){
1177           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1178         }
1179       }
1180     }
1181     $_SESSION['LOCK_VARS_TO_USE'] =array();
1182   }
1184   /* Prepare and show template */
1185   $smarty= get_smarty();
1186   $smarty->assign ("dn", $dn);
1187   if ($remove){
1188     $smarty->assign ("action", _("Continue anyway"));
1189   } else {
1190     $smarty->assign ("action", _("Edit anyway"));
1191   }
1192   $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."), "<b>".$dn."</b>", "<b><a href=\"main.php?plug=0&amp;viewid=$uid\">$cn</a></b>"));
1194   return ($smarty->fetch (get_template_path('islocked.tpl')));
1198 function to_string ($value)
1200   /* If this is an array, generate a text blob */
1201   if (is_array($value)){
1202     $ret= "";
1203     foreach ($value as $line){
1204       $ret.= $line."<br>\n";
1205     }
1206     return ($ret);
1207   } else {
1208     return ($value);
1209   }
1213 function get_printer_list($cups_server)
1215   global $config;
1216   $res = array();
1217   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'));
1218   foreach($data as $attrs ){
1219     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1220   }
1221   return $res;
1225 function sess_del ($var)
1227   /* New style */
1228   unset ($_SESSION[$var]);
1230   /* ... work around, since the first one
1231      doesn't seem to work all the time */
1232   session_unregister ($var);
1236 function show_errors($message)
1238   $complete= "";
1240   /* Assemble the message array to a plain string */
1241   foreach ($message as $error){
1242     if ($complete == ""){
1243       $complete= $error;
1244     } else {
1245       $complete= "$error<br>$complete";
1246     }
1247   }
1249   /* Fill ERROR variable with nice error dialog */
1250   print_red($complete);
1254 function show_ldap_error($message, $addon= "")
1256   if (!preg_match("/Success/i", $message)){
1257     if ($addon == ""){
1258       print_red (_("LDAP error: $message"));
1259     } else {
1260       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1261     }
1262     return TRUE;
1263   } else {
1264     return FALSE;
1265   }
1269 function rewrite($s)
1271   global $REWRITE;
1273   foreach ($REWRITE as $key => $val){
1274     $s= preg_replace("/$key/", "$val", $s);
1275   }
1277   return ($s);
1281 function dn2base($dn)
1283   global $config;
1285   if (get_people_ou() != ""){
1286     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1287   }
1288   if (get_groups_ou() != ""){
1289     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1290   }
1291   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1293   return ($base);
1298 function check_command($cmdline)
1300   $cmd= preg_replace("/ .*$/", "", $cmdline);
1302   /* Check if command exists in filesystem */
1303   if (!file_exists($cmd)){
1304     return (FALSE);
1305   }
1307   /* Check if command is executable */
1308   if (!is_executable($cmd)){
1309     return (FALSE);
1310   }
1312   return (TRUE);
1316 function print_header($image, $headline, $info= "")
1318   $display= "<div class=\"plugtop\">\n";
1319   $display.= "  <p class=\"center\" style=\"margin:0px 0px 0px 5px;padding:0px;font-size:24px;\"><img class=\"center\" src=\"$image\" align=\"middle\" alt=\"*\">&nbsp;$headline</p>\n";
1320   $display.= "</div>\n";
1322   if ($info != ""){
1323     $display.= "<div class=\"pluginfo\">\n";
1324     $display.= "$info";
1325     $display.= "</div>\n";
1326   } else {
1327     $display.= "<div style=\"height:5px;\">\n";
1328     $display.= "&nbsp;";
1329     $display.= "</div>\n";
1330   }
1331 #  if (isset($_SESSION['errors'])){
1332 #    $display.= $_SESSION['errors'];
1333 #  }
1335   return ($display);
1339 function register_global($name, $object)
1341   $_SESSION[$name]= $object;
1345 function is_global($name)
1347   return isset($_SESSION[$name]);
1351 function get_global($name)
1353   return $_SESSION[$name];
1357 function range_selector($dcnt,$start,$range=25,$post_var=false)
1360   /* Entries shown left and right from the selected entry */
1361   $max_entries= 10;
1363   /* Initialize and take care that max_entries is even */
1364   $output="";
1365   if ($max_entries & 1){
1366     $max_entries++;
1367   }
1369   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1370     $range= $_POST[$post_var];
1371   }
1373   /* Prevent output to start or end out of range */
1374   if ($start < 0 ){
1375     $start= 0 ;
1376   }
1377   if ($start >= $dcnt){
1378     $start= $range * (int)(($dcnt / $range) + 0.5);
1379   }
1381   $numpages= (($dcnt / $range));
1382   if(((int)($numpages))!=($numpages)){
1383     $numpages = (int)$numpages + 1;
1384   }
1385   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1386     return ("");
1387   }
1388   $ppage= (int)(($start / $range) + 0.5);
1391   /* Align selected page to +/- max_entries/2 */
1392   $begin= $ppage - $max_entries/2;
1393   $end= $ppage + $max_entries/2;
1395   /* Adjust begin/end, so that the selected value is somewhere in
1396      the middle and the size is max_entries if possible */
1397   if ($begin < 0){
1398     $end-= $begin + 1;
1399     $begin= 0;
1400   }
1401   if ($end > $numpages) {
1402     $end= $numpages;
1403   }
1404   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1405     $begin= $end - $max_entries;
1406   }
1408   if($post_var){
1409     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1410       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1411   }else{
1412     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1413   }
1415   /* Draw decrement */
1416   if ($start > 0 ) {
1417     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1418       (($start-$range))."\">".
1419       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1420   }
1422   /* Draw pages */
1423   for ($i= $begin; $i < $end; $i++) {
1424     if ($ppage == $i){
1425       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1426         validate($_GET['plug'])."&amp;start=".
1427         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1428     } else {
1429       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1430         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1431     }
1432   }
1434   /* Draw increment */
1435   if($start < ($dcnt-$range)) {
1436     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1437       (($start+($range)))."\">".
1438       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1439   }
1441   if(($post_var)&&($numpages)){
1442     $output.= "</td><td style='width:25%;text-align:right;vertical-align:middle;'>&nbsp;"._("Entries per page")."&nbsp;<select style='vertical-align:middle;' name='".$post_var."' onChange='javascript:document.mainform.submit()'>";
1443     foreach(array(20,50,100,200,"all") as $num){
1444       if($num == "all"){
1445         $var = 10000;
1446       }else{
1447         $var = $num;
1448       }
1449       if($var == $range){
1450         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1451       }else{  
1452         $output.="\n<option value='".$var."'>".$num."</option>";
1453       }
1454     }
1455     $output.=  "</select></td></tr></table></div>";
1456   }else{
1457     $output.= "</div>";
1458   }
1460   return($output);
1464 function apply_filter()
1466   $apply= "";
1468   $apply= ''.
1469     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1470     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1472   return ($apply);
1476 function back_to_main()
1478   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1479     _("Back").'"></p><input type="hidden" name="ignore">';
1481   return ($string);
1485 function normalize_netmask($netmask)
1487   /* Check for notation of netmask */
1488   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1489     $num= (int)($netmask);
1490     $netmask= "";
1492     for ($byte= 0; $byte<4; $byte++){
1493       $result=0;
1495       for ($i= 7; $i>=0; $i--){
1496         if ($num-- > 0){
1497           $result+= pow(2,$i);
1498         }
1499       }
1501       $netmask.= $result.".";
1502     }
1504     return (preg_replace('/\.$/', '', $netmask));
1505   }
1507   return ($netmask);
1511 function netmask_to_bits($netmask)
1513   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1514   $res= 0;
1516   for ($n= 0; $n<4; $n++){
1517     $start= 255;
1518     $name= "nm$n";
1520     for ($i= 0; $i<8; $i++){
1521       if ($start == (int)($$name)){
1522         $res+= 8 - $i;
1523         break;
1524       }
1525       $start-= pow(2,$i);
1526     }
1527   }
1529   return ($res);
1533 function recurse($rule, $variables)
1535   $result= array();
1537   if (!count($variables)){
1538     return array($rule);
1539   }
1541   reset($variables);
1542   $key= key($variables);
1543   $val= current($variables);
1544   unset ($variables[$key]);
1546   foreach($val as $possibility){
1547     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1548     $result= array_merge($result, recurse($nrule, $variables));
1549   }
1551   return ($result);
1555 function expand_id($rule, $attributes)
1557   /* Check for id rule */
1558   if(preg_match('/^id(:|#)\d+$/',$rule)){
1559     return (array("\{$rule}"));
1560   }
1562   /* Check for clean attribute */
1563   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1564     $rule= preg_replace('/^%/', '', $rule);
1565     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1566     return (array($val));
1567   }
1569   /* Check for attribute with parameters */
1570   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1571     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1572     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1573     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1574     $start= preg_replace ('/-.*$/', '', $param);
1575     $stop = preg_replace ('/^[^-]+-/', '', $param);
1577     /* Assemble results */
1578     $result= array();
1579     for ($i= $start; $i<= $stop; $i++){
1580       $result[]= substr($val, 0, $i);
1581     }
1582     return ($result);
1583   }
1585   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1586   return (array($rule));
1590 function gen_uids($rule, $attributes)
1592   global $config;
1594   /* Search for keys and fill the variables array with all 
1595      possible values for that key. */
1596   $part= "";
1597   $trigger= false;
1598   $stripped= "";
1599   $variables= array();
1601   for ($pos= 0; $pos < strlen($rule); $pos++){
1603     if ($rule[$pos] == "{" ){
1604       $trigger= true;
1605       $part= "";
1606       continue;
1607     }
1609     if ($rule[$pos] == "}" ){
1610       $variables[$pos]= expand_id($part, $attributes);
1611       $stripped.= "\{$pos}";
1612       $trigger= false;
1613       continue;
1614     }
1616     if ($trigger){
1617       $part.= $rule[$pos];
1618     } else {
1619       $stripped.= $rule[$pos];
1620     }
1621   }
1623   /* Recurse through all possible combinations */
1624   $proposed= recurse($stripped, $variables);
1626   /* Get list of used ID's */
1627   $used= array();
1628   $ldap= $config->get_ldap_link();
1629   $ldap->cd($config->current['BASE']);
1630   $ldap->search('(uid=*)');
1632   while($attrs= $ldap->fetch()){
1633     $used[]= $attrs['uid'][0];
1634   }
1636   /* Remove used uids and watch out for id tags */
1637   $ret= array();
1638   foreach($proposed as $uid){
1640     /* Check for id tag and modify uid if needed */
1641     if(preg_match('/\{id:\d+}/',$uid)){
1642       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1644       for ($i= 0; $i < pow(10,$size); $i++){
1645         $number= sprintf("%0".$size."d", $i);
1646         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1647         if (!in_array($res, $used)){
1648           $uid= $res;
1649           break;
1650         }
1651       }
1652     }
1654   if(preg_match('/\{id#\d+}/',$uid)){
1655     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1657     while (true){
1658       mt_srand((double) microtime()*1000000);
1659       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1660       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1661       if (!in_array($res, $used)){
1662         $uid= $res;
1663         break;
1664       }
1665     }
1666   }
1668 /* Don't assign used ones */
1669 if (!in_array($uid, $used)){
1670   $ret[]= $uid;
1674 return(array_unique($ret));
1678 function array_search_r($needle, $key, $haystack){
1680   foreach($haystack as $index => $value){
1681     $match= 0;
1683     if (is_array($value)){
1684       $match= array_search_r($needle, $key, $value);
1685     }
1687     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1688       $match=1;
1689     }
1691     if ($match){
1692       return 1;
1693     }
1694   }
1696   return 0;
1697
1700 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1701    Need to convert... */
1702 function to_byte($value) {
1703   $value= strtolower(trim($value));
1705   if(!is_numeric(substr($value, -1))) {
1707     switch(substr($value, -1)) {
1708       case 'g':
1709         $mult= 1073741824;
1710         break;
1711       case 'm':
1712         $mult= 1048576;
1713         break;
1714       case 'k':
1715         $mult= 1024;
1716         break;
1717     }
1719     return ($mult * (int)substr($value, 0, -1));
1720   } else {
1721     return $value;
1722   }
1726 function in_array_ics($value, $items)
1728   if (!is_array($items)){
1729     return (FALSE);
1730   }
1732   foreach ($items as $item){
1733     if (strtolower($item) == strtolower($value)) {
1734       return (TRUE);
1735     }
1736   }
1738   return (FALSE);
1739
1742 function generate_alphabet($count= 10)
1744   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1745   $alphabet= "";
1746   $c= 0;
1748   /* Fill cells with charaters */
1749   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1750     if ($c == 0){
1751       $alphabet.= "<tr>";
1752     }
1754     $ch = mb_substr($characters, $i, 1, "UTF8");
1755     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1756       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1758     if ($c++ == $count){
1759       $alphabet.= "</tr>";
1760       $c= 0;
1761     }
1762   }
1764   /* Fill remaining cells */
1765   while ($c++ <= $count){
1766     $alphabet.= "<td>&nbsp;</td>";
1767   }
1769   return ($alphabet);
1773 function validate($string)
1775   return (strip_tags(preg_replace('/\0/', '', $string)));
1778 function get_gosa_version()
1780   global $svn_revision, $svn_path;
1782   /* Extract informations */
1783   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1785   /* Release or development? */
1786   if (preg_match('%/gosa/trunk/%', $svn_path)){
1787     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1788   } else {
1789     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1790     return (sprintf(_("GOsa $release"), $revision));
1791   }
1795 function rmdirRecursive($path, $followLinks=false) {
1796   $dir= opendir($path);
1797   while($entry= readdir($dir)) {
1798     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1799       unlink($path."/".$entry);
1800     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1801       rmdirRecursive($path."/".$entry);
1802     }
1803   }
1804   closedir($dir);
1805   return rmdir($path);
1808 function scan_directory($path,$sort_desc=false)
1810   $ret = false;
1812   /* is this a dir ? */
1813   if(is_dir($path)) {
1815     /* is this path a readable one */
1816     if(is_readable($path)){
1818       /* Get contents and write it into an array */   
1819       $ret = array();    
1821       $dir = opendir($path);
1823       /* Is this a correct result ?*/
1824       if($dir){
1825         while($fp = readdir($dir))
1826           $ret[]= $fp;
1827       }
1828     }
1829   }
1830   /* Sort array ascending , like scandir */
1831   sort($ret);
1833   /* Sort descending if parameter is sort_desc is set */
1834   if($sort_desc) {
1835     $ret = array_reverse($ret);
1836   }
1838   return($ret);
1841 function clean_smarty_compile_dir($directory)
1843   global $svn_revision;
1845   if(is_dir($directory) && is_readable($directory)) {
1846     // Set revision filename to REVISION
1847     $revision_file= $directory."/REVISION";
1849     /* Is there a stamp containing the current revision? */
1850     if(!file_exists($revision_file)) {
1851       // create revision file
1852       create_revision($revision_file, $svn_revision);
1853     } else {
1854 # check for "$config->...['CONFIG']/revision" and the
1855 # contents should match the revision number
1856       if(!compare_revision($revision_file, $svn_revision)){
1857         // If revision differs, clean compile directory
1858         foreach(scan_directory($directory) as $file) {
1859           if(($file==".")||($file=="..")) continue;
1860           if( is_file($directory."/".$file) &&
1861               is_writable($directory."/".$file)) {
1862             // delete file
1863             if(!unlink($directory."/".$file)) {
1864               print_red("File ".$directory."/".$file." could not be deleted.");
1865               // This should never be reached
1866             }
1867           } elseif(is_dir($directory."/".$file) &&
1868               is_writable($directory."/".$file)) {
1869             // Just recursively delete it
1870             rmdirRecursive($directory."/".$file);
1871           }
1872         }
1873         // We should now create a fresh revision file
1874         clean_smarty_compile_dir($directory);
1875       } else {
1876         // Revision matches, nothing to do
1877       }
1878     }
1879   } else {
1880     // Smarty compile dir is not accessible
1881     // (Smarty will warn about this)
1882   }
1885 function create_revision($revision_file, $revision)
1887   $result= false;
1889   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1890     if($fh= fopen($revision_file, "w")) {
1891       if(fwrite($fh, $revision)) {
1892         $result= true;
1893       }
1894     }
1895     fclose($fh);
1896   } else {
1897     print_red("Can not write to revision file");
1898   }
1900   return $result;
1903 function compare_revision($revision_file, $revision)
1905   // false means revision differs
1906   $result= false;
1908   if(file_exists($revision_file) && is_readable($revision_file)) {
1909     // Open file
1910     if($fh= fopen($revision_file, "r")) {
1911       // Compare File contents with current revision
1912       if($revision == fread($fh, filesize($revision_file))) {
1913         $result= true;
1914       }
1915     } else {
1916       print_red("Can not open revision file");
1917     }
1918     // Close file
1919     fclose($fh);
1920   }
1922   return $result;
1925 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1927   $str = ""; // Our return value will be saved in this var
1929   $color  = dechex($percentage+150);
1930   $color2 = dechex(150 - $percentage);
1931   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1933   $progress = (int)(($percentage /100)*$width);
1935   /* Abort printing out percentage, if divs are to small */
1938   /* If theres a better solution for this, use it... */
1939   $str = "
1940     <div style=\" width:".($width)."px; 
1941     height:".($height)."px;
1942   background-color:#000000;
1943 padding:1px;\">
1945           <div style=\" width:".($width)."px;
1946         background-color:#$bgcolor;
1947 height:".($height)."px;\">
1949          <div style=\" width:".$progress."px;
1950 height:".$height."px;
1951        background-color:#".$color2.$color2.$color."; \">";
1954        if(($height >10)&&($showvalue)){
1955          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1956            <b>".$percentage."%</b>
1957            </font>";
1958        }
1960        $str.= "</div></div></div>";
1962        return($str);
1966 function array_key_ics($ikey, $items)
1968   /* Gather keys, make them lowercase */
1969   $tmp= array();
1970   foreach ($items as $key => $value){
1971     $tmp[strtolower($key)]= $key;
1972   }
1974   if (isset($tmp[strtolower($ikey)])){
1975     return($tmp[strtolower($ikey)]);
1976   }
1978   return ("");
1982 function search_config($arr, $name, $return)
1984   if (is_array($arr)){
1985     foreach ($arr as $a){
1986       if (isset($a['CLASS']) &&
1987           strtolower($a['CLASS']) == strtolower($name)){
1989         if (isset($a[$return])){
1990           return ($a[$return]);
1991         } else {
1992           return ("");
1993         }
1994       } else {
1995         $res= search_config ($a, $name, $return);
1996         if ($res != ""){
1997           return $res;
1998         }
1999       }
2000     }
2001   }
2002   return ("");
2006 function array_differs($src, $dst)
2008   /* If the count is differing, the arrays differ */
2009   if (count ($src) != count ($dst)){
2010     return (TRUE);
2011   }
2013   /* So the count is the same - lets check the contents */
2014   $differs= FALSE;
2015   foreach($src as $value){
2016     if (!in_array($value, $dst)){
2017       $differs= TRUE;
2018     }
2019   }
2021   return ($differs);
2025 function saveFilter($a_filter, $values)
2027   if (isset($_POST['regexit'])){
2028     $a_filter["regex"]= $_POST['regexit'];
2030     foreach($values as $type){
2031       if (isset($_POST[$type])) {
2032         $a_filter[$type]= "checked";
2033       } else {
2034         $a_filter[$type]= "";
2035       }
2036     }
2037   }
2039   /* React on alphabet links if needed */
2040   if (isset($_GET['search'])){
2041     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2042     if ($s == "**"){
2043       $s= "*";
2044     }
2045     $a_filter['regex']= $s;
2046   }
2048   return ($a_filter);
2052 /* Escape all preg_* relevant characters */
2053 function normalizePreg($input)
2055   return (addcslashes($input, '[]()|/.*+-'));
2059 /* Escape all LDAP filter relevant characters */
2060 function normalizeLdap($input)
2062   return (addcslashes($input, '()|'));
2066 /* Resturns the difference between to microtime() results in float  */
2067 function get_MicroTimeDiff($start , $stop)
2069   $a = split("\ ",$start);
2070   $b = split("\ ",$stop);
2072   $secs = $b[1] - $a[1];
2073   $msecs= $b[0] - $a[0]; 
2075   $ret = (float) ($secs+ $msecs);
2076   return($ret);
2080 /* Check if the given department name is valid */
2081 function is_department_name_reserved($name,$base)
2083   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2084                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2085                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2086   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2088   /* Check if name is one of the reserved names */
2089   if(in_array_ics($name,$reservedName)) {
2090     return(true);
2091   }
2093   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2094   foreach($follwedNames as $key => $names){
2095     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2096       return(true);
2097     }
2098   }
2099   return(false);
2103 function get_base_dir()
2105   global $BASE_DIR;
2107   return $BASE_DIR;
2111 function obj_is_readable($dn, $object, $attribute)
2113   global $ui;
2115   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2119 function obj_is_writable($dn, $object, $attribute)
2121   global $ui;
2123   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2127 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2129   /* Initialize variables */
2130   $ret  = array("count" => 0);  // Set count to 0
2131   $next = true;                 // if false, then skip next loops and return
2132   $cnt  = 0;                    // Current number of loops
2133   $max  = 100;                  // Just for security, prevent looops
2134   $ldap = NULL;                 // To check if created result a valid
2135   $keep = "";                   // save last failed parse string
2137   /* Check each parsed dn in ldap ? */
2138   if($config!=NULL && $verify_in_ldap){
2139     $ldap = $config->get_ldap_link();
2140   }
2142   /* Lets start */
2143   $called = false;
2144   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2146     $cnt ++;
2147     if(!preg_match("/,/",$dn)){
2148       $next = false;
2149     }
2150     $object = preg_replace("/[,].*$/","",$dn);
2151     $dn     = preg_replace("/^[^,]+,/","",$dn);
2153     $called = true;
2155     /* Check if current dn is valid */
2156     if($ldap!=NULL){
2157       $ldap->cd($dn);
2158       $ldap->cat($dn,array("dn"));
2159       if($ldap->count()){
2160         $ret[]  = $keep.$object;
2161         $keep   = "";
2162       }else{
2163         $keep  .= $object.",";
2164       }
2165     }else{
2166       $ret[]  = $keep.$object;
2167       $keep   = "";
2168     }
2169   }
2171   /* No dn was posted */
2172   if($cnt == 0 && !empty($dn)){
2173     $ret[] = $dn;
2174   }
2176   /* Append the rest */
2177   $test = $keep.$dn;
2178   if($called && !empty($test)){
2179     $ret[] = $keep.$dn;
2180   }
2181   $ret['count'] = count($ret) - 1;
2183   return($ret);
2186 function is_php4()
2188   if (isset($_SESSION['PHP4COMPATIBLE'])){
2189     return true;
2190   }
2191   return (preg_match('/^4/', phpversion()));
2194 /* Add "str_split" if this function is missing.
2195  * This function is only available in PHP5
2196  */
2197   if(!function_exists("str_split")){
2198     function str_split($str,$length =1)
2199     {
2200       if($length < 1 ) $length =1;
2202       $ret = array();
2203       for($i = 0 ; $i < strlen($str); $i = $i +$length){
2204         $ret[] = substr($str,$i ,$length);
2205       }
2206       return($ret);
2207     }
2208   }
2211 function get_base_from_hook($dn, $attrib)
2213   global $config;
2215   if (isset($config->current['BASE_HOOK'])){
2216     
2217     /* Call hook script - if present */
2218     $command= $config->current['BASE_HOOK'];
2220     if ($command != ""){
2221       $command.= " '$dn' $attrib";
2222       if (check_command($command)){
2223         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2224         exec($command, $output);
2225         if (preg_match("/^[0-9]+$/", $output[0])){
2226           return ($output[0]);
2227         } else {
2228           print_red(_("Warning - base_hook is not available. Using default base."));
2229           return ($config->current['UIDBASE']);
2230         }
2231       } else {
2232         print_red(_("Warning - base_hook is not available. Using default base."));
2233         return ($config->current['UIDBASE']);
2234       }
2236     } else {
2238       print_red(_("Warning - no base_hook defined. Using default base."));
2239       return ($config->current['UIDBASE']);
2241     }
2242   }
2245 /* Schema validation functions */
2247 function check_schema_version($class, $version)
2249   return preg_match("/\(v$version\)/", $class['DESC']);
2252 function check_schema($cfg,$rfc2307bis = FALSE)
2254   $messages= array();
2256   /* Get objectclasses */
2257   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2258   $objectclasses = $ldap->get_objectclasses();
2259   if(count($objectclasses) == 0){
2260     print_red(_("Can't get schema information from server. No schema check possible!"));
2261   }
2263   /* This is the default block used for each entry.
2264    *  to avoid unset indexes.
2265    */
2266   $def_check = array("REQUIRED_VERSION" => "0",
2267       "SCHEMA_FILES"     => array(),
2268       "CLASSES_REQUIRED" => array(),
2269       "STATUS"           => FALSE,
2270       "IS_MUST_HAVE"     => FALSE,
2271       "MSG"              => "",
2272       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2274   /* The gosa base schema */
2275   $checks['gosaObject'] = $def_check;
2276   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2277   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2278   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2279   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2281   /* GOsa Account class */
2282   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2283   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2284   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2285   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2286   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2288   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2289   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2290   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2291   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2292   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2293   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2295   /* Some other checks */
2296   foreach(array(
2297         "gosaCacheEntry"        => array("version" => "2.4"),
2298         "gosaDepartment"        => array("version" => "2.4"),
2299         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2300         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2301         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2302         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2303         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2304         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2305         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2306         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2307         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2308         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2309         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2310         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2311         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2312         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2313         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2314         "goLdapServer"          => array("version" => "2.4"),
2315         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2316         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2317         "goKrbServer"           => array("version" => "2.4"),
2318         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2319         ) as $name => $values){
2321           $checks[$name] = $def_check;
2322           if(isset($values['version'])){
2323             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2324           }
2325           if(isset($values['file'])){
2326             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2327           }
2328           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2329         }
2330   foreach($checks as $name => $value){
2331     foreach($value['CLASSES_REQUIRED'] as $class){
2333       if(!isset($objectclasses[$name])){
2334         $checks[$name]['STATUS'] = FALSE;
2335         if($value['IS_MUST_HAVE']){
2336           $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2337         }else{
2338           $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2339         }
2340       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2341         $checks[$name]['STATUS'] = FALSE;
2343         if($value['IS_MUST_HAVE']){
2344           $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2345         }else{
2346           $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2347         }
2348       }else{
2349         $checks[$name]['STATUS'] = TRUE;
2350         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2351       }
2352     }
2353   }
2355   $tmp = $objectclasses;
2357   /* The gosa base schema */
2358   $checks['posixGroup'] = $def_check;
2359   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2360   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2361   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2362   $checks['posixGroup']['STATUS']           = TRUE;
2363   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2364   $checks['posixGroup']['MSG']              = "";
2365   $checks['posixGroup']['INFO']             = "";
2367   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2368   if(isset($tmp['posixGroup'])){
2370     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2371       $checks['posixGroup']['STATUS']           = FALSE;
2372       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2373       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2374     }
2375     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2376       $checks['posixGroup']['STATUS']           = FALSE;
2377       $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2378       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2379     }
2380   }
2382   return($checks);
2386 function prepare4mailbody($string)
2388   $string = html_entity_decode($string);
2390   $from = array(
2391                 "/%/",
2392                 "/ /",
2393                 "/\n/",
2394                 "/\r/",
2395                 "/!/",
2396                 "/#/",
2397                 "/\*/",
2398                 "/\//",
2399                 "/</",
2400                 "/>/",
2401                 "/\?/",
2402                 "/\"/");
2404   $to = array(
2405                 "%25",
2406                 "%20",
2407                 "%0A",
2408                 "%0D",
2409                 "%21",
2410                 "%23",
2411                 "%2A",
2412                 "%2F",
2413                 "%3C",
2414                 "%3E",
2415                 "%3F",
2416                 "%22");
2418   $string = preg_replace($from,$to,$string);
2420   return($string);
2425 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2426 ?>