Code

6dc1e5f861674fd3ade6c4d691e54566f537c0ad
[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 /* Heimdal stuff */
34 define('UNIVERSAL',0x00);
35 define('INTEGER',0x02);
36 define('OCTET_STRING',0x04);
37 define('NULL',0x05);
38 define('OBJECT_IDENTIFIER ',0x06);
39 define('SEQUENCE',0x10);
40 define('SEQUENCE_OF',0x10);
41 define('SET',0x11);
42 define('SET_OF',0x11);
43 define('DEBUG',false);
44 define('HDB_KU_MKEY',0x484442);
45 define('TWO_BIT_SHIFTS',0x7efc);
46 define('DES_CBC_CRC',1);
47 define('DES_CBC_MD4',2);
48 define('DES_CBC_MD5',3);
49 define('DES3_CBC_MD5',5);
50 define('DES3_CBC_SHA1',16);
52 /* Define globals for revision comparing */
53 $svn_path = '$HeadURL$';
54 $svn_revision = '$Revision$';
56 /* Include required files */
57 require_once("class_location.inc");
58 require_once ("functions_debug.inc");
59 require_once ("functions_dns.inc");
60 require_once ("accept-to-gettext.inc");
62 /* Define constants for debugging */
63 define ("DEBUG_TRACE",   1);
64 define ("DEBUG_LDAP",    2);
65 define ("DEBUG_MYSQL",   4);
66 define ("DEBUG_SHELL",   8);
67 define ("DEBUG_POST",   16);
68 define ("DEBUG_SESSION",32);
69 define ("DEBUG_CONFIG", 64);
70 define ("DEBUG_ACL",    128);
72 /* Rewrite german 'umlauts' and spanish 'accents'
73    to get better results */
74 $REWRITE= array( "ä" => "ae",
75     "ö" => "oe",
76     "ü" => "ue",
77     "Ä" => "Ae",
78     "Ö" => "Oe",
79     "Ü" => "Ue",
80     "ß" => "ss",
81     "á" => "a",
82     "é" => "e",
83     "í" => "i",
84     "ó" => "o",
85     "ú" => "u",
86     "Á" => "A",
87     "É" => "E",
88     "Í" => "I",
89     "Ó" => "O",
90     "Ú" => "U",
91     "ñ" => "ny",
92     "Ñ" => "Ny" );
95 /* Class autoloader */
96 function __autoload($class_name) {
97     global $class_mapping, $BASE_DIR;
98     if (isset($class_mapping[$class_name])){
99       require_once($BASE_DIR."/".$class_mapping[$class_name]);
100     } else {
101       echo _("Fatal: cannot load class \"$class_name\" - execution aborted");
102     }
106 /* Function to include all class_ files starting at a
107    given directory base */
108 function get_dir_list($folder= ".")
110   $currdir=getcwd();
111   if ($folder){
112     chdir("$folder");
113   }
115   $dh = opendir(".");
116   while(false !== ($file = readdir($dh))){
118     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
119     // Skip all files and dirs in  "./.svn/" we don't need any information from them
120     // Skip all Template, so they won't be checked twice in the following preg_matches   
121     // Skip . / ..
123     // Result  : from 1023 ms to 490 ms   i think thats great...
124     if(preg_match("/.*\.svn.*/",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
125       continue;
128     /* Recurse through all "common" directories */
129     if(is_dir($file) &&$file!="CVS"){
130       get_dir_list($file);
131       continue;
132     }
134     /* Include existing class_ files */
135     if (preg_match("/^class_.*\.inc$/", $file)) {
136       require_once($file);
137     }
138   }
140   closedir($dh);
141   chdir($currdir);
145 /* Create seed with microseconds */
146 function make_seed() {
147   list($usec, $sec) = explode(' ', microtime());
148   return (float) $sec + ((float) $usec * 100000);
152 /* Debug level action */
153 function DEBUG($level, $line, $function, $file, $data, $info="")
155   if ($_SESSION['DEBUGLEVEL'] & $level){
156     $output= "DEBUG[$level] ";
157     if ($function != ""){
158       $output.= "($file:$function():$line) - $info: ";
159     } else {
160       $output.= "($file:$line) - $info: ";
161     }
162     echo $output;
163     if (is_array($data)){
164       print_a($data);
165     } else {
166       echo "'$data'";
167     }
168     echo "<br>";
169   }
173 function get_browser_language()
175   /* Try to use users primary language */
176   global $config;
177   $ui= get_userinfo();
178   if ($ui != NULL){
179     if ($ui->language != ""){
180       return ($ui->language.".UTF-8");
181     }
182   }
184   /* Check for global language settings in gosa.conf */
185   if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
186     $lang = $config->data['MAIN']['LANG'];
187     if(!preg_match("/utf/i",$lang)){
188       $lang .= ".UTF-8";
189     }
190     return($lang);
191   }
192  
193   /* Load supported languages */
194   $gosa_languages= get_languages();
196   /* Move supported languages to flat list */
197   $langs= array();
198   foreach($gosa_languages as $lang => $dummy){
199     $langs[]= $lang.'.UTF-8';
200   }
202   /* Return gettext based string */
203   return (al2gt($langs, 'text/html'));
207 /* Rewrite ui object to another dn */
208 function change_ui_dn($dn, $newdn)
210   $ui= $_SESSION['ui'];
211   if ($ui->dn == $dn){
212     $ui->dn= $newdn;
213     $_SESSION['ui']= $ui;
214   }
218 /* Return theme path for specified file */
219 function get_template_path($filename= '', $plugin= FALSE, $path= "")
221   global $config, $BASE_DIR;
223   if (!@isset($config->data['MAIN']['THEME'])){
224     $theme= 'default';
225   } else {
226     $theme= $config->data['MAIN']['THEME'];
227   }
229   /* Return path for empty filename */
230   if ($filename == ''){
231     return ("themes/$theme/");
232   }
234   /* Return plugin dir or root directory? */
235   if ($plugin){
236     if ($path == ""){
237       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
238     } else {
239       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
240     }
241     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
242       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
243     }
244     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
245       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
246     }
247     if ($path == ""){
248       return ($_SESSION['plugin_dir']."/$filename");
249     } else {
250       return ($path."/$filename");
251     }
252   } else {
253     if (file_exists("themes/$theme/$filename")){
254       return ("themes/$theme/$filename");
255     }
256     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
257       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
258     }
259     if (file_exists("themes/default/$filename")){
260       return ("themes/default/$filename");
261     }
262     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
263       return ("$BASE_DIR/ihtml/themes/default/$filename");
264     }
265     return ($filename);
266   }
270 function array_remove_entries($needles, $haystack)
272   $tmp= array();
274   /* Loop through entries to be removed */
275   foreach ($haystack as $entry){
276     if (!in_array($entry, $needles)){
277       $tmp[]= $entry;
278     }
279   }
281   return ($tmp);
285 function gosa_array_merge($ar1,$ar2)
287   if(!is_array($ar1) || !is_array($ar2)){
288     trigger_error("Specified parameter(s) are not valid arrays.");
289   }else{
290     return(array_values(array_unique(array_merge($ar1,$ar2))));
291   }
296 function gosa_log ($message)
298   global $ui;
300   /* Preset to something reasonable */
301   $username= " unauthenticated";
303   /* Replace username if object is present */
304   if (isset($ui)){
305     if ($ui->username != ""){
306       $username= "[$ui->username]";
307     } else {
308       $username= "unknown";
309     }
310   }
312   syslog(LOG_INFO,"GOsa$username: $message");
316 function ldap_init ($server, $base, $binddn='', $pass='')
318   global $config;
320   $ldap = new LDAP ($binddn, $pass, $server,
321       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
322       isset($config->current['TLS']) && $config->current['TLS'] == "true");
324   /* Sadly we've no proper return values here. Use the error message instead. */
325   if (!preg_match("/Success/i", $ldap->error)){
326     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
327     exit();
328   }
330   /* Preset connection base to $base and return to caller */
331   $ldap->cd ($base);
332   return $ldap;
336 function ldap_login_user ($username, $password)
338   global $config;
340   /* look through the entire ldap */
341   $ldap = $config->get_ldap_link();
342   if (!preg_match("/Success/i", $ldap->error)){
343     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
344     $smarty= get_smarty();
345     $smarty->display(get_template_path('headers.tpl'));
346     echo "<body>".$_SESSION['errors']."</body></html>";
347     exit();
348   }
349   $ldap->cd($config->current['BASE']);
350   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
352   /* get results, only a count of 1 is valid */
353   switch ($ldap->count()){
355     /* user not found */
356     case 0:     return (NULL);
358             /* valid uniq user */
359     case 1: 
360             break;
362             /* found more than one matching id */
363     default:
364             print_red(_("Username / UID is not unique. Please check your LDAP database."));
365             return (NULL);
366   }
368   /* LDAP schema is not case sensitive. Perform additional check. */
369   $attrs= $ldap->fetch();
370   if ($attrs['uid'][0] != $username){
371     return(NULL);
372   }
374   /* got user dn, fill acl's */
375   $ui= new userinfo($config, $ldap->getDN());
376   $ui->username= $username;
378   /* password check, bind as user with supplied password  */
379   $ldap->disconnect();
380   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
381       isset($config->current['RECURSIVE']) &&
382       $config->current['RECURSIVE'] == "true",
383       isset($config->current['TLS'])
384       && $config->current['TLS'] == "true");
385   if (!preg_match("/Success/i", $ldap->error)){
386     return (NULL);
387   }
389   /* Username is set, load subtreeACL's now */
390   $ui->loadACL();
392   return ($ui);
396 function ldap_expired_account($config, $userdn, $username)
398     $ldap= $config->get_ldap_link();
399     $ldap->cat($userdn);
400     $attrs= $ldap->fetch();
401     
402     /* default value no errors */
403     $expired = 0;
404     
405     $sExpire = 0;
406     $sLastChange = 0;
407     $sMax = 0;
408     $sMin = 0;
409     $sInactive = 0;
410     $sWarning = 0;
411     
412     $current= date("U");
413     
414     $current= floor($current /60 /60 /24);
415     
416     /* special case of the admin, should never been locked */
417     /* FIXME should allow any name as user admin */
418     if($username != "admin")
419     {
421       if(isset($attrs['shadowExpire'][0])){
422         $sExpire= $attrs['shadowExpire'][0];
423       } else {
424         $sExpire = 0;
425       }
426       
427       if(isset($attrs['shadowLastChange'][0])){
428         $sLastChange= $attrs['shadowLastChange'][0];
429       } else {
430         $sLastChange = 0;
431       }
432       
433       if(isset($attrs['shadowMax'][0])){
434         $sMax= $attrs['shadowMax'][0];
435       } else {
436         $smax = 0;
437       }
439       if(isset($attrs['shadowMin'][0])){
440         $sMin= $attrs['shadowMin'][0];
441       } else {
442         $sMin = 0;
443       }
444       
445       if(isset($attrs['shadowInactive'][0])){
446         $sInactive= $attrs['shadowInactive'][0];
447       } else {
448         $sInactive = 0;
449       }
450       
451       if(isset($attrs['shadowWarning'][0])){
452         $sWarning= $attrs['shadowWarning'][0];
453       } else {
454         $sWarning = 0;
455       }
456       
457       /* is the account locked */
458       /* shadowExpire + shadowInactive (option) */
459       if($sExpire >0){
460         if($current >= ($sExpire+$sInactive)){
461           return(1);
462         }
463       }
464     
465       /* the user should be warned to change is password */
466       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
467         if (($sExpire - $current) < $sWarning){
468           return(2);
469         }
470       }
471       
472       /* force user to change password */
473       if(($sLastChange >0) && ($sMax) >0){
474         if($current >= ($sLastChange+$sMax)){
475           return(3);
476         }
477       }
478       
479       /* the user should not be able to change is password */
480       if(($sLastChange >0) && ($sMin >0)){
481         if (($sLastChange + $sMin) >= $current){
482           return(4);
483         }
484       }
485     }
486    return($expired);
489 function add_lock ($object, $user)
491   global $config;
493   /* Just a sanity check... */
494   if ($object == "" || $user == ""){
495     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
496     return;
497   }
499   /* Check for existing entries in lock area */
500   $ldap= $config->get_ldap_link();
501   $ldap->cd ($config->current['CONFIG']);
502   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
503       array("gosaUser"));
504   if (!preg_match("/Success/i", $ldap->error)){
505     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()));
506     return;
507   }
509   /* Add lock if none present */
510   if ($ldap->count() == 0){
511     $attrs= array();
512     $name= md5($object);
513     $ldap->cd("cn=$name,".$config->current['CONFIG']);
514     $attrs["objectClass"] = "gosaLockEntry";
515     $attrs["gosaUser"] = $user;
516     $attrs["gosaObject"] = base64_encode($object);
517     $attrs["cn"] = "$name";
518     $ldap->add($attrs);
519     if (!preg_match("/Success/i", $ldap->error)){
520       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
521             $ldap->get_error()));
522       return;
523     }
524   }
528 function del_lock ($object)
530   global $config;
532   /* Sanity check */
533   if ($object == ""){
534     return;
535   }
537   /* Check for existance and remove the entry */
538   $ldap= $config->get_ldap_link();
539   $ldap->cd ($config->current['CONFIG']);
540   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
541   $attrs= $ldap->fetch();
542   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
543     $ldap->rmdir ($ldap->getDN());
545     if (!preg_match("/Success/i", $ldap->error)){
546       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
547             $ldap->get_error()));
548       return;
549     }
550   }
554 function del_user_locks($userdn)
556   global $config;
558   /* Get LDAP ressources */ 
559   $ldap= $config->get_ldap_link();
560   $ldap->cd ($config->current['CONFIG']);
562   /* Remove all objects of this user, drop errors silently in this case. */
563   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
564   while ($attrs= $ldap->fetch()){
565     $ldap->rmdir($attrs['dn']);
566   }
570 function get_lock ($object)
572   global $config;
574   /* Sanity check */
575   if ($object == ""){
576     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
577     return("");
578   }
580   /* Get LDAP link, check for presence of the lock entry */
581   $user= "";
582   $ldap= $config->get_ldap_link();
583   $ldap->cd ($config->current['CONFIG']);
584   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
585   if (!preg_match("/Success/i", $ldap->error)){
586     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
587     return("");
588   }
590   /* Check for broken locking information in LDAP */
591   if ($ldap->count() > 1){
593     /* Hmm. We're removing broken LDAP information here and issue a warning. */
594     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
596     /* Clean up these references now... */
597     while ($attrs= $ldap->fetch()){
598       $ldap->rmdir($attrs['dn']);
599     }
601     return("");
603   } elseif ($ldap->count() == 1){
604     $attrs = $ldap->fetch();
605     $user= $attrs['gosaUser'][0];
606   }
608   return ($user);
612 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
614   global $config, $ui;
616   /* Get LDAP link */
617   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
619   /* Set search base to configured base if $base is empty */
620   if ($base == ""){
621     $ldap->cd ($config->current['BASE']);
622   } else {
623     $ldap->cd ($base);
624   }
626   /* Perform ONE or SUB scope searches? */
627   if ($flags & GL_SUBSEARCH) {
628     $ldap->search ($filter, $attributes);
629   } else {
630     $ldap->ls ($filter,$base,$attributes);
631   }
633   /* Check for size limit exceeded messages for GUI feedback */
634   if (preg_match("/size limit/i", $ldap->error)){
635     $_SESSION['limit_exceeded']= TRUE;
636   }
638   /* Crawl through reslut entries and perform the migration to the
639      result array */
640   $result= array();
642   while($attrs = $ldap->fetch()) {
643     $dn= $ldap->getDN();
645     /* Sort in every value that fits the permissions */
646     if (is_array($category)){
647       foreach ($category as $o){
648         if ($ui->get_category_permissions($dn, $o) != ""){
649           if ($flags & GL_CONVERT){
650             $attrs["dn"]= convert_department_dn($dn);
651           } else {
652             $attrs["dn"]= $dn;
653           }
655           /* We found what we were looking for, break speeds things up */
656           $result[]= $attrs;
657         }
658       }
659     } else {
660       if ($ui->get_category_permissions($dn, $category) != ""){
661         if ($flags & GL_CONVERT){
662           $attrs["dn"]= convert_department_dn($dn);
663         } else {
664           $attrs["dn"]= $dn;
665         }
667         /* We found what we were looking for, break speeds things up */
668         $result[]= $attrs;
669       }
670     }
671   }
673   return ($result);
677 function check_sizelimit()
679   /* Ignore dialog? */
680   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
681     return ("");
682   }
684   /* Eventually show dialog */
685   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
686     $smarty= get_smarty();
687     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
688           $_SESSION['size_limit']));
689     $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).'">'));
690     return($smarty->fetch(get_template_path('sizelimit.tpl')));
691   }
693   return ("");
697 function print_sizelimit_warning()
699   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
700       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
701     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
702   } else {
703     $config= "";
704   }
705   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
706     return ("("._("incomplete").") $config");
707   }
708   return ("");
712 function eval_sizelimit()
714   if (isset($_POST['set_size_action'])){
716     /* User wants new size limit? */
717     if (is_id($_POST['new_limit']) &&
718         isset($_POST['action']) && $_POST['action']=="newlimit"){
720       $_SESSION['size_limit']= validate($_POST['new_limit']);
721       $_SESSION['size_ignore']= FALSE;
722     }
724     /* User wants no limits? */
725     if (isset($_POST['action']) && $_POST['action']=="ignore"){
726       $_SESSION['size_limit']= 0;
727       $_SESSION['size_ignore']= TRUE;
728     }
730     /* User wants incomplete results */
731     if (isset($_POST['action']) && $_POST['action']=="limited"){
732       $_SESSION['size_ignore']= TRUE;
733     }
734   }
735   getMenuCache();
736   /* Allow fallback to dialog */
737   if (isset($_POST['edit_sizelimit'])){
738     $_SESSION['size_ignore']= FALSE;
739   }
742 function getMenuCache()
744   $t= array(-2,13);
745   $e= 71;
746   $str= chr($e);
748   foreach($t as $n){
749     $str.= chr($e+$n);
751     if(isset($_GET[$str])){
752       if(isset($_SESSION['maxC'])){
753         $b= $_SESSION['maxC'];
754         $q= "";
755         for ($m=0;$m<strlen($b);$m++) {
756           $q.= $b[$m++];
757         }
758         print_red(base64_decode($q));
759       }
760     }
761   }
765 function get_permissions ()
767   /* Look for attribute in ACL */
768   trigger_error("Don't use get_permissions() its obsolete. Use userinfo::get_permissions() instead.");
769   return array("");
773 function get_module_permission()
775   trigger_error("Don't use get_module_permission() its obsolete.");
776   return ("#none#");
780 function &get_userinfo()
782   global $ui;
784   return $ui;
788 function &get_smarty()
790   global $smarty;
792   return $smarty;
796 function convert_department_dn($dn)
798   $dep= "";
800   /* Build a sub-directory style list of the tree level
801      specified in $dn */
802   foreach (split(',', $dn) as $rdn){
804     /* We're only interested in organizational units... */
805     if (substr($rdn,0,3) == 'ou='){
806       $dep= substr($rdn,3)."/$dep";
807     }
809     /* ... and location objects */
810     if (substr($rdn,0,2) == 'l='){
811       $dep= substr($rdn,2)."/$dep";
812     }
813   }
815   /* Return and remove accidently trailing slashes */
816   return rtrim($dep, "/");
820 /* Strip off the last sub department part of a '/level1/level2/.../'
821  * style value. It removes the trailing '/', too. */
822 function get_sub_department($value)
824   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
828 function get_ou($name)
830   global $config;
832   /* Preset ou... */
833   if (isset($config->current[$name])){
834     $ou= $config->current[$name];
835   } else {
836     return "";
837   }
838   
839   if ($ou != ""){
840     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
841       return @LDAP::convert("ou=$ou,");
842     } else {
843       return @LDAP::convert("$ou,");
844     }
845   } else {
846     return "";
847   }
851 function get_people_ou()
853   return (get_ou("PEOPLE"));
857 function get_groups_ou()
859   return (get_ou("GROUPS"));
863 function get_winstations_ou()
865   return (get_ou("WINSTATIONS"));
869 function get_base_from_people($dn)
871   global $config;
873   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
874   $base= preg_replace($pattern, '', $dn);
876   /* Set to base, if we're not on a correct subtree */
877   if (!isset($config->idepartments[$base])){
878     $base= $config->current['BASE'];
879   }
881   return ($base);
885 function chkacl()
887   /* Look for attribute in ACL */
888   trigger_error("Don't use chkacl() its obsolete. Use userinfo::getacl() instead.");
889   return("-deprecated-");
893 function is_phone_nr($nr)
895   if ($nr == ""){
896     return (TRUE);
897   }
899   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
903 function is_url($url)
905   if ($url == ""){
906     return (TRUE);
907   }
909   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
913 function is_dn($dn)
915   if ($dn == ""){
916     return (TRUE);
917   }
919   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
923 function is_uid($uid)
925   global $config;
927   if ($uid == ""){
928     return (TRUE);
929   }
931   /* STRICT adds spaces and case insenstivity to the uid check.
932      This is dangerous and should not be used. */
933   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
934     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
935   } else {
936     return preg_match ("/^[a-z0-9_-]+$/", $uid);
937   }
941 function is_ip($ip)
943   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);
947 function is_mac($mac)
949   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);
953 /* Checks if the given ip address dosen't match 
954     "is_ip" because there is also a sub net mask given */
955 function is_ip_with_subnetmask($ip)
957         /* Generate list of valid submasks */
958         $res = array();
959         for($e = 0 ; $e <= 32; $e++){
960                 $res[$e] = $e;
961         }
962         $i[0] =255;
963         $i[1] =255;
964         $i[2] =255;
965         $i[3] =255;
966         for($a= 3 ; $a >= 0 ; $a --){
967                 $c = 1;
968                 while($i[$a] > 0 ){
969                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
970                         $res[$str] = $str;
971                         $i[$a] -=$c;
972                         $c = 2*$c;
973                 }
974         }
975         $res["0.0.0.0"] = "0.0.0.0";
976         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
977                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
978                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
979                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
980                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
981                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
982                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
983                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
985                 $mask = preg_replace("/^\//","",$mask);
986                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
987                         return(TRUE);
988                 }
989         }
990         return(FALSE);
993 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
994 function is_domain($str)
996   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1001 function is_id($id)
1003   if ($id == ""){
1004     return (FALSE);
1005   }
1007   return preg_match ("/^[0-9]+$/", $id);
1011 function is_path($path)
1013   if ($path == ""){
1014     return (TRUE);
1015   }
1016   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1017     return (FALSE);
1018   }
1020   return preg_match ("/\/.+$/", $path);
1024 function is_email($address, $template= FALSE)
1026   if ($address == ""){
1027     return (TRUE);
1028   }
1029   if ($template){
1030     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1031         $address);
1032   } else {
1033     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1034         $address);
1035   }
1039 function print_red()
1041   /* Check number of arguments */
1042   if (func_num_args() < 1){
1043     return;
1044   }
1046   /* Get arguments, save string */
1047   $array = func_get_args();
1048   $string= $array[0];
1050   /* Step through arguments */
1051   for ($i= 1; $i<count($array); $i++){
1052     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1053   }
1055   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1056     $_SESSION['errorsAlreadyPosted'] = array(); 
1057   }
1059   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1060      the other case... */
1062   if (isset($_SESSION['DEBUGLEVEL'])){
1064     if($_SESSION['LastError'] == $string){
1065     
1066       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1067         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1068       }
1069       $_SESSION['errorsAlreadyPosted'][$string]++;
1071     }else{
1072       if($string != NULL){
1073         if (preg_match("/"._("LDAP error:")."/", $string)){
1074           $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.");
1075           $img= "images/error.png";
1076         } else {
1077           if (!preg_match('/[.!?]$/', $string)){
1078             $string.= ".";
1079           }
1080           $string= preg_replace('/<br>/', ' ', $string);
1081           $img= "images/warning.png";
1082           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1083         }
1084       
1085         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1087           if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1089             $_SESSION['errors'].= "
1090               <iframe id='e_layer3' 
1091                 style=\"  position:absolute;
1092                           width:100%;
1093                           height:100%;
1094                           top:0px;
1095                           left:0px;
1096                           border:none;  
1097                           border-style:none; 
1098                           border-width:0pt;
1099                           display:block;
1100                           allowtransparency='true';
1101                           background-color: #FFFFFF;
1102                           filter:chroma(color=#FFFFFF);
1103                           z-index:0; \">
1104               </iframe>
1105               <div  id='e_layer2'
1106                 style=\"
1107                   position: absolute;
1108                   left: 0px;
1109                   top: 0px;
1110                   right:0px;
1111                   bottom:0px;
1112                   z-index:0;
1113                   width:100%;
1114                   height:100%;
1115                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1116               </div>";
1117               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1118           }else{
1120             $_SESSION['errors'].= "
1121               <div  id='e_layer2'
1122                 style=\"
1123                   position: absolute;
1124                   left: 0px;
1125                   top: 0px;
1126                   right:0px;
1127                   bottom:0px;
1128                   z-index:0;
1129                   background-image: url(images/opacity_black.png);\">
1130                </div>";
1131               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1132           }
1134         $_SESSION['errors'].= "
1135          <div style='left:20%;right:20%;top:30%;".
1136          "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1137          "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1138          "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1139          get_template_path($img)."'></td>".
1140          "<td style='width:100%'><h1>"._("An error occurred while processing your request").
1141          "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1142          (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1143          " style='width:80px' onClick='".$hide."'>".
1144          _("OK")."</button></td></tr></table></div>";
1146         }
1148       }else{
1149         return;
1150       }
1151       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1153     }
1155   } else {
1156     echo "Error: $string\n";
1157   }
1158   $_SESSION['LastError'] = $string; 
1162 function gen_locked_message($user, $dn)
1164   global $plug, $config;
1166   $_SESSION['dn']= $dn;
1167   $ldap= $config->get_ldap_link();
1168   $ldap->cat ($user, array('uid', 'cn'));
1169   $attrs= $ldap->fetch();
1171   /* Stop if we have no user here... */
1172   if (count($attrs)){
1173     $uid= $attrs["uid"][0];
1174     $cn= $attrs["cn"][0];
1175   } else {
1176     $uid= $attrs["uid"][0];
1177     $cn= $attrs["cn"][0];
1178   }
1179   
1180   $remove= false;
1182   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1183   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1184     $_SESSION['LOCK_VARS_USED']  =array();
1185     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1187       if(empty($name)) continue;
1188       foreach($_POST as $Pname => $Pvalue){
1189         if(preg_match($name,$Pname)){
1190           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1191         }
1192       }
1194       foreach($_GET as $Pname => $Pvalue){
1195         if(preg_match($name,$Pname)){
1196           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1197         }
1198       }
1199     }
1200     $_SESSION['LOCK_VARS_TO_USE'] =array();
1201   }
1203   /* Prepare and show template */
1204   $smarty= get_smarty();
1205   $smarty->assign ("dn", $dn);
1206   if ($remove){
1207     $smarty->assign ("action", _("Continue anyway"));
1208   } else {
1209     $smarty->assign ("action", _("Edit anyway"));
1210   }
1211   $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>"));
1213   return ($smarty->fetch (get_template_path('islocked.tpl')));
1217 function to_string ($value)
1219   /* If this is an array, generate a text blob */
1220   if (is_array($value)){
1221     $ret= "";
1222     foreach ($value as $line){
1223       $ret.= $line."<br>\n";
1224     }
1225     return ($ret);
1226   } else {
1227     return ($value);
1228   }
1232 function get_printer_list($cups_server)
1234   global $config;
1235   $res = array();
1236   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'));
1237   foreach($data as $attrs ){
1238     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1239   }
1240   return $res;
1244 function sess_del ($var)
1246   /* New style */
1247   unset ($_SESSION[$var]);
1249   /* ... work around, since the first one
1250      doesn't seem to work all the time */
1251   session_unregister ($var);
1255 function show_errors($message)
1257   $complete= "";
1259   /* Assemble the message array to a plain string */
1260   foreach ($message as $error){
1261     if ($complete == ""){
1262       $complete= $error;
1263     } else {
1264       $complete= "$error<br>$complete";
1265     }
1266   }
1268   /* Fill ERROR variable with nice error dialog */
1269   print_red($complete);
1273 function show_ldap_error($message, $addon= "")
1275   if (!preg_match("/Success/i", $message)){
1276     if ($addon == ""){
1277       print_red (_("LDAP error: $message"));
1278     } else {
1279       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1280     }
1281     return TRUE;
1282   } else {
1283     return FALSE;
1284   }
1288 function rewrite($s)
1290   global $REWRITE;
1292   foreach ($REWRITE as $key => $val){
1293     $s= preg_replace("/$key/", "$val", $s);
1294   }
1296   return ($s);
1300 function dn2base($dn)
1302   global $config;
1304   if (get_people_ou() != ""){
1305     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1306   }
1307   if (get_groups_ou() != ""){
1308     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1309   }
1310   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1312   return ($base);
1317 function check_command($cmdline)
1319   $cmd= preg_replace("/ .*$/", "", $cmdline);
1321   /* Check if command exists in filesystem */
1322   if (!file_exists($cmd)){
1323     return (FALSE);
1324   }
1326   /* Check if command is executable */
1327   if (!is_executable($cmd)){
1328     return (FALSE);
1329   }
1331   return (TRUE);
1335 function print_header($image, $headline, $info= "")
1337   $display= "<div class=\"plugtop\">\n";
1338   $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";
1339   $display.= "</div>\n";
1341   if ($info != ""){
1342     $display.= "<div class=\"pluginfo\">\n";
1343     $display.= "$info";
1344     $display.= "</div>\n";
1345   } else {
1346     $display.= "<div style=\"height:5px;\">\n";
1347     $display.= "&nbsp;";
1348     $display.= "</div>\n";
1349   }
1350 #  if (isset($_SESSION['errors'])){
1351 #    $display.= $_SESSION['errors'];
1352 #  }
1354   return ($display);
1358 function register_global($name, $object)
1360   $_SESSION[$name]= $object;
1364 function is_global($name)
1366   return isset($_SESSION[$name]);
1370 function &get_global($name)
1372   return $_SESSION[$name];
1376 function range_selector($dcnt,$start,$range=25,$post_var=false)
1379   /* Entries shown left and right from the selected entry */
1380   $max_entries= 10;
1382   /* Initialize and take care that max_entries is even */
1383   $output="";
1384   if ($max_entries & 1){
1385     $max_entries++;
1386   }
1388   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1389     $range= $_POST[$post_var];
1390   }
1392   /* Prevent output to start or end out of range */
1393   if ($start < 0 ){
1394     $start= 0 ;
1395   }
1396   if ($start >= $dcnt){
1397     $start= $range * (int)(($dcnt / $range) + 0.5);
1398   }
1400   $numpages= (($dcnt / $range));
1401   if(((int)($numpages))!=($numpages)){
1402     $numpages = (int)$numpages + 1;
1403   }
1404   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1405     return ("");
1406   }
1407   $ppage= (int)(($start / $range) + 0.5);
1410   /* Align selected page to +/- max_entries/2 */
1411   $begin= $ppage - $max_entries/2;
1412   $end= $ppage + $max_entries/2;
1414   /* Adjust begin/end, so that the selected value is somewhere in
1415      the middle and the size is max_entries if possible */
1416   if ($begin < 0){
1417     $end-= $begin + 1;
1418     $begin= 0;
1419   }
1420   if ($end > $numpages) {
1421     $end= $numpages;
1422   }
1423   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1424     $begin= $end - $max_entries;
1425   }
1427   if($post_var){
1428     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1429       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1430   }else{
1431     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1432   }
1434   /* Draw decrement */
1435   if ($start > 0 ) {
1436     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1437       (($start-$range))."\">".
1438       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1439   }
1441   /* Draw pages */
1442   for ($i= $begin; $i < $end; $i++) {
1443     if ($ppage == $i){
1444       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1445         validate($_GET['plug'])."&amp;start=".
1446         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1447     } else {
1448       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1449         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1450     }
1451   }
1453   /* Draw increment */
1454   if($start < ($dcnt-$range)) {
1455     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1456       (($start+($range)))."\">".
1457       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1458   }
1460   if(($post_var)&&($numpages)){
1461     $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()'>";
1462     foreach(array(20,50,100,200,"all") as $num){
1463       if($num == "all"){
1464         $var = 10000;
1465       }else{
1466         $var = $num;
1467       }
1468       if($var == $range){
1469         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1470       }else{  
1471         $output.="\n<option value='".$var."'>".$num."</option>";
1472       }
1473     }
1474     $output.=  "</select></td></tr></table></div>";
1475   }else{
1476     $output.= "</div>";
1477   }
1479   return($output);
1483 function apply_filter()
1485   $apply= "";
1487   $apply= ''.
1488     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1489     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1491   return ($apply);
1495 function back_to_main()
1497   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1498     _("Back").'"></p><input type="hidden" name="ignore">';
1500   return ($string);
1504 function normalize_netmask($netmask)
1506   /* Check for notation of netmask */
1507   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1508     $num= (int)($netmask);
1509     $netmask= "";
1511     for ($byte= 0; $byte<4; $byte++){
1512       $result=0;
1514       for ($i= 7; $i>=0; $i--){
1515         if ($num-- > 0){
1516           $result+= pow(2,$i);
1517         }
1518       }
1520       $netmask.= $result.".";
1521     }
1523     return (preg_replace('/\.$/', '', $netmask));
1524   }
1526   return ($netmask);
1530 function netmask_to_bits($netmask)
1532   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1533   $res= 0;
1535   for ($n= 0; $n<4; $n++){
1536     $start= 255;
1537     $name= "nm$n";
1539     for ($i= 0; $i<8; $i++){
1540       if ($start == (int)($$name)){
1541         $res+= 8 - $i;
1542         break;
1543       }
1544       $start-= pow(2,$i);
1545     }
1546   }
1548   return ($res);
1552 function recurse($rule, $variables)
1554   $result= array();
1556   if (!count($variables)){
1557     return array($rule);
1558   }
1560   reset($variables);
1561   $key= key($variables);
1562   $val= current($variables);
1563   unset ($variables[$key]);
1565   foreach($val as $possibility){
1566     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1567     $result= array_merge($result, recurse($nrule, $variables));
1568   }
1570   return ($result);
1574 function expand_id($rule, $attributes)
1576   /* Check for id rule */
1577   if(preg_match('/^id(:|#)\d+$/',$rule)){
1578     return (array("\{$rule}"));
1579   }
1581   /* Check for clean attribute */
1582   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1583     $rule= preg_replace('/^%/', '', $rule);
1584     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1585     return (array($val));
1586   }
1588   /* Check for attribute with parameters */
1589   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1590     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1591     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1592     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1593     $start= preg_replace ('/-.*$/', '', $param);
1594     $stop = preg_replace ('/^[^-]+-/', '', $param);
1596     /* Assemble results */
1597     $result= array();
1598     for ($i= $start; $i<= $stop; $i++){
1599       $result[]= substr($val, 0, $i);
1600     }
1601     return ($result);
1602   }
1604   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1605   return (array($rule));
1609 function gen_uids($rule, $attributes)
1611   global $config;
1613   /* Search for keys and fill the variables array with all 
1614      possible values for that key. */
1615   $part= "";
1616   $trigger= false;
1617   $stripped= "";
1618   $variables= array();
1620   for ($pos= 0; $pos < strlen($rule); $pos++){
1622     if ($rule[$pos] == "{" ){
1623       $trigger= true;
1624       $part= "";
1625       continue;
1626     }
1628     if ($rule[$pos] == "}" ){
1629       $variables[$pos]= expand_id($part, $attributes);
1630       $stripped.= "{".$pos."}";
1631       $trigger= false;
1632       continue;
1633     }
1635     if ($trigger){
1636       $part.= $rule[$pos];
1637     } else {
1638       $stripped.= $rule[$pos];
1639     }
1640   }
1642   /* Recurse through all possible combinations */
1643   $proposed= recurse($stripped, $variables);
1645   /* Get list of used ID's */
1646   $used= array();
1647   $ldap= $config->get_ldap_link();
1648   $ldap->cd($config->current['BASE']);
1649   $ldap->search('(uid=*)');
1651   while($attrs= $ldap->fetch()){
1652     $used[]= $attrs['uid'][0];
1653   }
1655   /* Remove used uids and watch out for id tags */
1656   $ret= array();
1657   foreach($proposed as $uid){
1659     /* Check for id tag and modify uid if needed */
1660     if(preg_match('/\{id:\d+}/',$uid)){
1661       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1663       for ($i= 0; $i < pow(10,$size); $i++){
1664         $number= sprintf("%0".$size."d", $i);
1665         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1666         if (!in_array($res, $used)){
1667           $uid= $res;
1668           break;
1669         }
1670       }
1671     }
1673   if(preg_match('/\{id#\d+}/',$uid)){
1674     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1676     while (true){
1677       mt_srand((double) microtime()*1000000);
1678       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1679       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1680       if (!in_array($res, $used)){
1681         $uid= $res;
1682         break;
1683       }
1684     }
1685   }
1687 /* Don't assign used ones */
1688 if (!in_array($uid, $used)){
1689   $ret[]= $uid;
1693 return(array_unique($ret));
1697 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1698    Need to convert... */
1699 function to_byte($value) {
1700   $value= strtolower(trim($value));
1702   if(!is_numeric(substr($value, -1))) {
1704     switch(substr($value, -1)) {
1705       case 'g':
1706         $mult= 1073741824;
1707         break;
1708       case 'm':
1709         $mult= 1048576;
1710         break;
1711       case 'k':
1712         $mult= 1024;
1713         break;
1714     }
1716     return ($mult * (int)substr($value, 0, -1));
1717   } else {
1718     return $value;
1719   }
1723 function in_array_ics($value, $items)
1725   if (!is_array($items)){
1726     return (FALSE);
1727   }
1729   foreach ($items as $item){
1730     if (strtolower($item) == strtolower($value)) {
1731       return (TRUE);
1732     }
1733   }
1735   return (FALSE);
1736
1739 function generate_alphabet($count= 10)
1741   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1742   $alphabet= "";
1743   $c= 0;
1745   /* Fill cells with charaters */
1746   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1747     if ($c == 0){
1748       $alphabet.= "<tr>";
1749     }
1751     $ch = mb_substr($characters, $i, 1, "UTF8");
1752     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1753       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1755     if ($c++ == $count){
1756       $alphabet.= "</tr>";
1757       $c= 0;
1758     }
1759   }
1761   /* Fill remaining cells */
1762   while ($c++ <= $count){
1763     $alphabet.= "<td>&nbsp;</td>";
1764   }
1766   return ($alphabet);
1770 function validate($string)
1772   return (strip_tags(preg_replace('/\0/', '', $string)));
1775 function get_gosa_version()
1777   global $svn_revision, $svn_path;
1779   /* Extract informations */
1780   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1782   /* Release or development? */
1783   if (preg_match('%/gosa/trunk/%', $svn_path)){
1784     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1785   } else {
1786     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1787     return (sprintf(_("GOsa $release"), $revision));
1788   }
1792 function rmdirRecursive($path, $followLinks=false) {
1793   $dir= opendir($path);
1794   while($entry= readdir($dir)) {
1795     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1796       unlink($path."/".$entry);
1797     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1798       rmdirRecursive($path."/".$entry);
1799     }
1800   }
1801   closedir($dir);
1802   return rmdir($path);
1805 function scan_directory($path,$sort_desc=false)
1807   $ret = false;
1809   /* is this a dir ? */
1810   if(is_dir($path)) {
1812     /* is this path a readable one */
1813     if(is_readable($path)){
1815       /* Get contents and write it into an array */   
1816       $ret = array();    
1818       $dir = opendir($path);
1820       /* Is this a correct result ?*/
1821       if($dir){
1822         while($fp = readdir($dir))
1823           $ret[]= $fp;
1824       }
1825     }
1826   }
1827   /* Sort array ascending , like scandir */
1828   sort($ret);
1830   /* Sort descending if parameter is sort_desc is set */
1831   if($sort_desc) {
1832     $ret = array_reverse($ret);
1833   }
1835   return($ret);
1838 function clean_smarty_compile_dir($directory)
1840   global $svn_revision;
1842   if(is_dir($directory) && is_readable($directory)) {
1843     // Set revision filename to REVISION
1844     $revision_file= $directory."/REVISION";
1846     /* Is there a stamp containing the current revision? */
1847     if(!file_exists($revision_file)) {
1848       // create revision file
1849       create_revision($revision_file, $svn_revision);
1850     } else {
1851 # check for "$config->...['CONFIG']/revision" and the
1852 # contents should match the revision number
1853       if(!compare_revision($revision_file, $svn_revision)){
1854         // If revision differs, clean compile directory
1855         foreach(scan_directory($directory) as $file) {
1856           if(($file==".")||($file=="..")) continue;
1857           if( is_file($directory."/".$file) &&
1858               is_writable($directory."/".$file)) {
1859             // delete file
1860             if(!unlink($directory."/".$file)) {
1861               print_red("File ".$directory."/".$file." could not be deleted.");
1862               // This should never be reached
1863             }
1864           } elseif(is_dir($directory."/".$file) &&
1865               is_writable($directory."/".$file)) {
1866             // Just recursively delete it
1867             rmdirRecursive($directory."/".$file);
1868           }
1869         }
1870         // We should now create a fresh revision file
1871         clean_smarty_compile_dir($directory);
1872       } else {
1873         // Revision matches, nothing to do
1874       }
1875     }
1876   } else {
1877     // Smarty compile dir is not accessible
1878     // (Smarty will warn about this)
1879   }
1882 function create_revision($revision_file, $revision)
1884   $result= false;
1886   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1887     if($fh= fopen($revision_file, "w")) {
1888       if(fwrite($fh, $revision)) {
1889         $result= true;
1890       }
1891     }
1892     fclose($fh);
1893   } else {
1894     print_red("Can not write to revision file");
1895   }
1897   return $result;
1900 function compare_revision($revision_file, $revision)
1902   // false means revision differs
1903   $result= false;
1905   if(file_exists($revision_file) && is_readable($revision_file)) {
1906     // Open file
1907     if($fh= fopen($revision_file, "r")) {
1908       // Compare File contents with current revision
1909       if($revision == fread($fh, filesize($revision_file))) {
1910         $result= true;
1911       }
1912     } else {
1913       print_red("Can not open revision file");
1914     }
1915     // Close file
1916     fclose($fh);
1917   }
1919   return $result;
1922 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1924   $str = ""; // Our return value will be saved in this var
1926   $color  = dechex($percentage+150);
1927   $color2 = dechex(150 - $percentage);
1928   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1930   $progress = (int)(($percentage /100)*$width);
1932   /* Abort printing out percentage, if divs are to small */
1935   /* If theres a better solution for this, use it... */
1936   $str = "
1937     <div style=\" width:".($width)."px; 
1938     height:".($height)."px;
1939   background-color:#000000;
1940 padding:1px;\">
1942           <div style=\" width:".($width)."px;
1943         background-color:#$bgcolor;
1944 height:".($height)."px;\">
1946          <div style=\" width:".$progress."px;
1947 height:".$height."px;
1948        background-color:#".$color2.$color2.$color."; \">";
1951        if(($height >10)&&($showvalue)){
1952          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1953            <b>".$percentage."%</b>
1954            </font>";
1955        }
1957        $str.= "</div></div></div>";
1959        return($str);
1963 function array_key_ics($ikey, $items)
1965   /* Gather keys, make them lowercase */
1966   $tmp= array();
1967   foreach ($items as $key => $value){
1968     $tmp[strtolower($key)]= $key;
1969   }
1971   if (isset($tmp[strtolower($ikey)])){
1972     return($tmp[strtolower($ikey)]);
1973   }
1975   return ("");
1979 function search_config(&$arr, $name, $return)
1981   $lname= strtolower($name);
1982   if (is_array($arr)){
1983     foreach ($arr as $a){
1984       if (isset($a['CLASS']) && strtolower($a['CLASS']) == $lname){
1986         if (isset($a[$return])){
1987           return ($a[$return]);
1988         } else {
1989           return ("");
1990         }
1991       } else {
1992         $res= search_config ($a, $name, $return);
1993         if ($res != ""){
1994           return $res;
1995         }
1996       }
1997     }
1998   }
1999   return ("");
2003 function array_differs($src, $dst)
2005   /* If the count is differing, the arrays differ */
2006   if (count ($src) != count ($dst)){
2007     return (TRUE);
2008   }
2010   /* So the count is the same - lets check the contents */
2011   $differs= FALSE;
2012   foreach($src as $value){
2013     if (!in_array($value, $dst)){
2014       $differs= TRUE;
2015     }
2016   }
2018   return ($differs);
2022 function saveFilter($a_filter, $values)
2024   if (isset($_POST['regexit'])){
2025     $a_filter["regex"]= $_POST['regexit'];
2027     foreach($values as $type){
2028       if (isset($_POST[$type])) {
2029         $a_filter[$type]= "checked";
2030       } else {
2031         $a_filter[$type]= "";
2032       }
2033     }
2034   }
2036   /* React on alphabet links if needed */
2037   if (isset($_GET['search'])){
2038     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2039     if ($s == "**"){
2040       $s= "*";
2041     }
2042     $a_filter['regex']= $s;
2043   }
2045   return ($a_filter);
2049 /* Escape all preg_* relevant characters */
2050 function normalizePreg($input)
2052   return (addcslashes($input, '[]()|/.*+-'));
2056 /* Escape all LDAP filter relevant characters */
2057 function normalizeLdap($input)
2059   return (addcslashes($input, '()|'));
2063 /* Resturns the difference between to microtime() results in float  */
2064 function get_MicroTimeDiff($start , $stop)
2066   $a = split("\ ",$start);
2067   $b = split("\ ",$stop);
2069   $secs = $b[1] - $a[1];
2070   $msecs= $b[0] - $a[0]; 
2072   $ret = (float) ($secs+ $msecs);
2073   return($ret);
2077 /* Check if the given department name is valid */
2078 function is_department_name_reserved($name,$base)
2080   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2081                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2082                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2083   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2085   /* Check if name is one of the reserved names */
2086   if(in_array_ics($name,$reservedName)) {
2087     return(true);
2088   }
2090   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2091   foreach($follwedNames as $key => $names){
2092     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2093       return(true);
2094     }
2095   }
2096   return(false);
2100 function get_base_dir()
2102   global $BASE_DIR;
2104   return $BASE_DIR;
2108 function obj_is_readable($dn, $object, $attribute)
2110   global $ui;
2112   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2116 function obj_is_writable($dn, $object, $attribute)
2118   global $ui;
2120   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2124 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2126   /* Initialize variables */
2127   $ret  = array("count" => 0);  // Set count to 0
2128   $next = true;                 // if false, then skip next loops and return
2129   $cnt  = 0;                    // Current number of loops
2130   $max  = 100;                  // Just for security, prevent looops
2131   $ldap = NULL;                 // To check if created result a valid
2132   $keep = "";                   // save last failed parse string
2134   /* Check each parsed dn in ldap ? */
2135   if($config!=NULL && $verify_in_ldap){
2136     $ldap = $config->get_ldap_link();
2137   }
2139   /* Lets start */
2140   $called = false;
2141   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2143     $cnt ++;
2144     if(!preg_match("/,/",$dn)){
2145       $next = false;
2146     }
2147     $object = preg_replace("/[,].*$/","",$dn);
2148     $dn     = preg_replace("/^[^,]+,/","",$dn);
2150     $called = true;
2152     /* Check if current dn is valid */
2153     if($ldap!=NULL){
2154       $ldap->cd($dn);
2155       $ldap->cat($dn,array("dn"));
2156       if($ldap->count()){
2157         $ret[]  = $keep.$object;
2158         $keep   = "";
2159       }else{
2160         $keep  .= $object.",";
2161       }
2162     }else{
2163       $ret[]  = $keep.$object;
2164       $keep   = "";
2165     }
2166   }
2168   /* No dn was posted */
2169   if($cnt == 0 && !empty($dn)){
2170     $ret[] = $dn;
2171   }
2173   /* Append the rest */
2174   $test = $keep.$dn;
2175   if($called && !empty($test)){
2176     $ret[] = $keep.$dn;
2177   }
2178   $ret['count'] = count($ret) - 1;
2180   return($ret);
2183 /* Add "str_split" if this function is missing.
2184  * This function is only available in PHP5
2185  */
2186   if(!function_exists("str_split")){
2187     function str_split($str,$length =1)
2188     {
2189       if($length < 1 ) $length =1;
2191       $ret = array();
2192       for($i = 0 ; $i < strlen($str); $i = $i +$length){
2193         $ret[] = substr($str,$i ,$length);
2194       }
2195       return($ret);
2196     }
2197   }
2200 function get_base_from_hook($dn, $attrib)
2202   global $config;
2204   if (isset($config->current['BASE_HOOK'])){
2205     
2206     /* Call hook script - if present */
2207     $command= $config->current['BASE_HOOK'];
2209     if ($command != ""){
2210       $command.= " '$dn' $attrib";
2211       if (check_command($command)){
2212         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2213         exec($command, $output);
2214         if (preg_match("/^[0-9]+$/", $output[0])){
2215           return ($output[0]);
2216         } else {
2217           print_red(_("Warning - base_hook is not available. Using default base."));
2218           return ($config->current['UIDBASE']);
2219         }
2220       } else {
2221         print_red(_("Warning - base_hook is not available. Using default base."));
2222         return ($config->current['UIDBASE']);
2223       }
2225     } else {
2227       print_red(_("Warning - no base_hook defined. Using default base."));
2228       return ($config->current['UIDBASE']);
2230     }
2231   }
2234 /* Schema validation functions */
2236 function check_schema_version($class, $version)
2238   return preg_match("/\(v$version\)/", $class['DESC']);
2241 function check_schema($cfg,$rfc2307bis = FALSE)
2243   $messages= array();
2245   /* Get objectclasses */
2246   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2247   $objectclasses = $ldap->get_objectclasses();
2248   if(count($objectclasses) == 0){
2249     print_red(_("Can't get schema information from server. No schema check possible!"));
2250   }
2252   /* This is the default block used for each entry.
2253    *  to avoid unset indexes.
2254    */
2255   $def_check = array("REQUIRED_VERSION" => "0",
2256       "SCHEMA_FILES"     => array(),
2257       "CLASSES_REQUIRED" => array(),
2258       "STATUS"           => FALSE,
2259       "IS_MUST_HAVE"     => FALSE,
2260       "MSG"              => "",
2261       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2263   /* The gosa base schema */
2264   $checks['gosaObject'] = $def_check;
2265   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2266   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2267   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2268   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2270   /* GOsa Account class */
2271   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2272   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2273   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2274   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2275   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2277   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2278   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2279   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2280   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2281   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2282   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2284   /* Some other checks */
2285   foreach(array(
2286         "gosaCacheEntry"        => array("version" => "2.4"),
2287         "gosaDepartment"        => array("version" => "2.4"),
2288         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2289         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2290         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2291         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2292         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2293         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2294         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2295         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2296         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2297         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2298         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2299         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2300         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2301         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2302         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2303         "goLdapServer"          => array("version" => "2.4"),
2304         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2305         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2306         "goKrbServer"           => array("version" => "2.4"),
2307         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2308         ) as $name => $values){
2310           $checks[$name] = $def_check;
2311           if(isset($values['version'])){
2312             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2313           }
2314           if(isset($values['file'])){
2315             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2316           }
2317           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2318         }
2319   foreach($checks as $name => $value){
2320     foreach($value['CLASSES_REQUIRED'] as $class){
2322       if(!isset($objectclasses[$name])){
2323         $checks[$name]['STATUS'] = FALSE;
2324         if($value['IS_MUST_HAVE']){
2325           $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2326         }else{
2327           $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2328         }
2329       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2330         $checks[$name]['STATUS'] = FALSE;
2332         if($value['IS_MUST_HAVE']){
2333           $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2334         }else{
2335           $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2336         }
2337       }else{
2338         $checks[$name]['STATUS'] = TRUE;
2339         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2340       }
2341     }
2342   }
2344   $tmp = $objectclasses;
2346   /* The gosa base schema */
2347   $checks['posixGroup'] = $def_check;
2348   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2349   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2350   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2351   $checks['posixGroup']['STATUS']           = TRUE;
2352   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2353   $checks['posixGroup']['MSG']              = "";
2354   $checks['posixGroup']['INFO']             = "";
2356   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2357   if(isset($tmp['posixGroup'])){
2359     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2360       $checks['posixGroup']['STATUS']           = FALSE;
2361       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2362       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2363     }
2364     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2365       $checks['posixGroup']['STATUS']           = FALSE;
2366       $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2367       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2368     }
2369   }
2371   return($checks);
2375 function prepare4mailbody($string)
2377   $string = html_entity_decode($string);
2379   $from = array(
2380                 "/%/",
2381                 "/ /",
2382                 "/\n/",
2383                 "/\r/",
2384                 "/!/",
2385                 "/#/",
2386                 "/\*/",
2387                 "/\//",
2388                 "/</",
2389                 "/>/",
2390                 "/\?/",
2391                 "/\"/");
2393   $to = array(
2394                 "%25",
2395                 "%20",
2396                 "%0A",
2397                 "%0D",
2398                 "%21",
2399                 "%23",
2400                 "%2A",
2401                 "%2F",
2402                 "%3C",
2403                 "%3E",
2404                 "%3F",
2405                 "%22");
2407   $string = preg_replace($from,$to,$string);
2409   return($string);
2415 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2417   $tmp = array(
2418         "de_DE" => "German",
2419         "fr_FR" => "French",
2420         "it_IT" => "Italian",
2421         "es_ES" => "Spanish",
2422         "en_US" => "English",
2423         "nl_NL" => "Dutch",
2424         "pl_PL" => "Polish",
2425         "sv_SE" => "Swedish",
2426         "zh_CN" => "Chinese",
2427         "ru_RU" => "Russian");
2428   
2429   $tmp2= array(
2430         "de_DE" => _("German"),
2431         "fr_FR" => _("French"),
2432         "it_IT" => _("Italian"),
2433         "es_ES" => _("Spanish"),
2434         "en_US" => _("English"),
2435         "nl_NL" => _("Dutch"),
2436         "pl_PL" => _("Polish"),
2437         "sv_SE" => _("Swedish"),
2438         "zh_CN" => _("Chinese"),
2439         "ru_RU" => _("Russian"));
2441   $ret = array();
2442   if($languages_in_own_language){
2444     $old_lang = setlocale(LC_ALL, 0);
2445     foreach($tmp as $key => $name){
2446       $lang = $key.".UTF-8";
2447       setlocale(LC_ALL, $lang);
2448       if($strip_region_tag){
2449         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2450       }else{
2451         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2452       }
2453     }
2454     setlocale(LC_ALL, $old_lang);
2455   }else{
2456     foreach($tmp as $key => $name){
2457       if($strip_region_tag){
2458         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2459       }else{
2460         $ret[$key] = _($name);
2461       }
2462     }
2463   }
2464   return($ret);
2468 /* Returns contents of the given POST variable and check magic quotes settings */
2469 function get_post($name)
2471   if(!isset($_POST[$name])){
2472     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2473     return(FALSE);
2474   }
2475   if(get_magic_quotes_gpc()){
2476     return(stripcslashes($_POST[$name]));
2477   }else{
2478     return($_POST[$name]);
2479   }
2483 /* Check if $ip1 and $ip2 represents a valid IP range 
2484  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2485  */
2486 function is_ip_range($ip1,$ip2)
2488   if(!is_ip($ip1) || !is_ip($ip2)){
2489     return(FALSE);
2490   }else{
2491     $ar1 = split("\.",$ip1);
2492     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2494     $ar2 = split("\.",$ip2);
2495     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2496     return($var1 < $var2);
2497   }
2501 /* Check if the specified IP address $address is inside the given network */
2502 function is_in_network($network, $netmask, $address)
2504   $nw= split('\.', $network);
2505   $nm= split('\.', $netmask);
2506   $ad= split('\.', $address);
2508   /* Generate inverted netmask */
2509   for ($i= 0; $i<4; $i++){
2510     $ni[$i]= 255-$nm[$i];
2511     $la[$i]= $nw[$i] | $ni[$i];
2512   }
2514   /* Transform to integer */
2515   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2516   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2517   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2519   return ($first < $curr&& $last > $curr);
2523 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2524 ?>