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 }
103 }
105 /* Create seed with microseconds */
106 function make_seed() {
107 list($usec, $sec) = explode(' ', microtime());
108 return (float) $sec + ((float) $usec * 100000);
109 }
112 /* Debug level action */
113 function DEBUG($level, $line, $function, $file, $data, $info="")
114 {
115 if ($_SESSION['DEBUGLEVEL'] & $level){
116 $output= "DEBUG[$level] ";
117 if ($function != ""){
118 $output.= "($file:$function():$line) - $info: ";
119 } else {
120 $output.= "($file:$line) - $info: ";
121 }
122 echo $output;
123 if (is_array($data)){
124 print_a($data);
125 } else {
126 echo "'$data'";
127 }
128 echo "<br>";
129 }
130 }
133 function get_browser_language()
134 {
135 /* Try to use users primary language */
136 global $config;
137 $ui= get_userinfo();
138 if ($ui !== NULL){
139 if ($ui->language != ""){
140 return ($ui->language.".UTF-8");
141 }
142 }
144 /* Check for global language settings in gosa.conf */
145 if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
146 $lang = $config->data['MAIN']['LANG'];
147 if(!preg_match("/utf/i",$lang)){
148 $lang .= ".UTF-8";
149 }
150 return($lang);
151 }
153 /* Load supported languages */
154 $gosa_languages= get_languages();
156 /* Move supported languages to flat list */
157 $langs= array();
158 foreach($gosa_languages as $lang => $dummy){
159 $langs[]= $lang.'.UTF-8';
160 }
162 /* Return gettext based string */
163 return (al2gt($langs, 'text/html'));
164 }
167 /* Rewrite ui object to another dn */
168 function change_ui_dn($dn, $newdn)
169 {
170 $ui= $_SESSION['ui'];
171 if ($ui->dn == $dn){
172 $ui->dn= $newdn;
173 $_SESSION['ui']= $ui;
174 }
175 }
178 /* Return theme path for specified file */
179 function get_template_path($filename= '', $plugin= FALSE, $path= "")
180 {
181 global $config, $BASE_DIR;
183 if (!@isset($config->data['MAIN']['THEME'])){
184 $theme= 'default';
185 } else {
186 $theme= $config->data['MAIN']['THEME'];
187 }
189 /* Return path for empty filename */
190 if ($filename == ''){
191 return ("themes/$theme/");
192 }
194 /* Return plugin dir or root directory? */
195 if ($plugin){
196 if ($path == ""){
197 $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
198 } else {
199 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
200 }
201 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
202 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
203 }
204 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
205 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
206 }
207 if ($path == ""){
208 return ($_SESSION['plugin_dir']."/$filename");
209 } else {
210 return ($path."/$filename");
211 }
212 } else {
213 if (file_exists("themes/$theme/$filename")){
214 return ("themes/$theme/$filename");
215 }
216 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
217 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
218 }
219 if (file_exists("themes/default/$filename")){
220 return ("themes/default/$filename");
221 }
222 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
223 return ("$BASE_DIR/ihtml/themes/default/$filename");
224 }
225 return ($filename);
226 }
227 }
230 function array_remove_entries($needles, $haystack)
231 {
232 $tmp= array();
234 /* Loop through entries to be removed */
235 foreach ($haystack as $entry){
236 if (!in_array($entry, $needles)){
237 $tmp[]= $entry;
238 }
239 }
241 return ($tmp);
242 }
245 function gosa_array_merge($ar1,$ar2)
246 {
247 if(!is_array($ar1) || !is_array($ar2)){
248 trigger_error("Specified parameter(s) are not valid arrays.");
249 }else{
250 return(array_values(array_unique(array_merge($ar1,$ar2))));
251 }
252 }
256 function gosa_log ($message)
257 {
258 global $ui;
260 /* Preset to something reasonable */
261 $username= " unauthenticated";
263 /* Replace username if object is present */
264 if (isset($ui)){
265 if ($ui->username != ""){
266 $username= "[$ui->username]";
267 } else {
268 $username= "unknown";
269 }
270 }
272 syslog(LOG_INFO,"GOsa$username: $message");
273 }
276 function ldap_init ($server, $base, $binddn='', $pass='')
277 {
278 global $config;
280 $ldap = new LDAP ($binddn, $pass, $server,
281 isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
282 isset($config->current['TLS']) && $config->current['TLS'] == "true");
284 /* Sadly we've no proper return values here. Use the error message instead. */
285 if (!preg_match("/Success/i", $ldap->error)){
286 echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
287 exit();
288 }
290 /* Preset connection base to $base and return to caller */
291 $ldap->cd ($base);
292 return $ldap;
293 }
296 function ldap_login_user ($username, $password)
297 {
298 global $config;
300 /* look through the entire ldap */
301 $ldap = $config->get_ldap_link();
302 if (!preg_match("/Success/i", $ldap->error)){
303 print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
304 $smarty= get_smarty();
305 $smarty->display(get_template_path('headers.tpl'));
306 echo "<body>".$_SESSION['errors']."</body></html>";
307 exit();
308 }
309 $ldap->cd($config->current['BASE']);
310 $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
312 /* get results, only a count of 1 is valid */
313 switch ($ldap->count()){
315 /* user not found */
316 case 0: return (NULL);
318 /* valid uniq user */
319 case 1:
320 break;
322 /* found more than one matching id */
323 default:
324 print_red(_("Username / UID is not unique. Please check your LDAP database."));
325 return (NULL);
326 }
328 /* LDAP schema is not case sensitive. Perform additional check. */
329 $attrs= $ldap->fetch();
330 if ($attrs['uid'][0] != $username){
331 return(NULL);
332 }
334 /* got user dn, fill acl's */
335 $ui= new userinfo($config, $ldap->getDN());
336 $ui->username= $username;
338 /* password check, bind as user with supplied password */
339 $ldap->disconnect();
340 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
341 isset($config->current['RECURSIVE']) &&
342 $config->current['RECURSIVE'] == "true",
343 isset($config->current['TLS'])
344 && $config->current['TLS'] == "true");
345 if (!preg_match("/Success/i", $ldap->error)){
346 return (NULL);
347 }
349 /* Username is set, load subtreeACL's now */
350 $ui->loadACL();
352 return ($ui);
353 }
356 function ldap_expired_account($config, $userdn, $username)
357 {
358 $ldap= $config->get_ldap_link();
359 $ldap->cat($userdn);
360 $attrs= $ldap->fetch();
362 /* default value no errors */
363 $expired = 0;
365 $sExpire = 0;
366 $sLastChange = 0;
367 $sMax = 0;
368 $sMin = 0;
369 $sInactive = 0;
370 $sWarning = 0;
372 $current= date("U");
374 $current= floor($current /60 /60 /24);
376 /* special case of the admin, should never been locked */
377 /* FIXME should allow any name as user admin */
378 if($username != "admin")
379 {
381 if(isset($attrs['shadowExpire'][0])){
382 $sExpire= $attrs['shadowExpire'][0];
383 } else {
384 $sExpire = 0;
385 }
387 if(isset($attrs['shadowLastChange'][0])){
388 $sLastChange= $attrs['shadowLastChange'][0];
389 } else {
390 $sLastChange = 0;
391 }
393 if(isset($attrs['shadowMax'][0])){
394 $sMax= $attrs['shadowMax'][0];
395 } else {
396 $smax = 0;
397 }
399 if(isset($attrs['shadowMin'][0])){
400 $sMin= $attrs['shadowMin'][0];
401 } else {
402 $sMin = 0;
403 }
405 if(isset($attrs['shadowInactive'][0])){
406 $sInactive= $attrs['shadowInactive'][0];
407 } else {
408 $sInactive = 0;
409 }
411 if(isset($attrs['shadowWarning'][0])){
412 $sWarning= $attrs['shadowWarning'][0];
413 } else {
414 $sWarning = 0;
415 }
417 /* is the account locked */
418 /* shadowExpire + shadowInactive (option) */
419 if($sExpire >0){
420 if($current >= ($sExpire+$sInactive)){
421 return(1);
422 }
423 }
425 /* the user should be warned to change is password */
426 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
427 if (($sExpire - $current) < $sWarning){
428 return(2);
429 }
430 }
432 /* force user to change password */
433 if(($sLastChange >0) && ($sMax) >0){
434 if($current >= ($sLastChange+$sMax)){
435 return(3);
436 }
437 }
439 /* the user should not be able to change is password */
440 if(($sLastChange >0) && ($sMin >0)){
441 if (($sLastChange + $sMin) >= $current){
442 return(4);
443 }
444 }
445 }
446 return($expired);
447 }
449 function add_lock ($object, $user)
450 {
451 global $config;
453 /* Just a sanity check... */
454 if ($object == "" || $user == ""){
455 print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
456 return;
457 }
459 /* Check for existing entries in lock area */
460 $ldap= $config->get_ldap_link();
461 $ldap->cd ($config->current['CONFIG']);
462 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
463 array("gosaUser"));
464 if (!preg_match("/Success/i", $ldap->error)){
465 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()));
466 return;
467 }
469 /* Add lock if none present */
470 if ($ldap->count() == 0){
471 $attrs= array();
472 $name= md5($object);
473 $ldap->cd("cn=$name,".$config->current['CONFIG']);
474 $attrs["objectClass"] = "gosaLockEntry";
475 $attrs["gosaUser"] = $user;
476 $attrs["gosaObject"] = base64_encode($object);
477 $attrs["cn"] = "$name";
478 $ldap->add($attrs);
479 if (!preg_match("/Success/i", $ldap->error)){
480 print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
481 $ldap->get_error()));
482 return;
483 }
484 }
485 }
488 function del_lock ($object)
489 {
490 global $config;
492 /* Sanity check */
493 if ($object == ""){
494 return;
495 }
497 /* Check for existance and remove the entry */
498 $ldap= $config->get_ldap_link();
499 $ldap->cd ($config->current['CONFIG']);
500 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
501 $attrs= $ldap->fetch();
502 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
503 $ldap->rmdir ($ldap->getDN());
505 if (!preg_match("/Success/i", $ldap->error)){
506 print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
507 $ldap->get_error()));
508 return;
509 }
510 }
511 }
514 function del_user_locks($userdn)
515 {
516 global $config;
518 /* Get LDAP ressources */
519 $ldap= $config->get_ldap_link();
520 $ldap->cd ($config->current['CONFIG']);
522 /* Remove all objects of this user, drop errors silently in this case. */
523 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
524 while ($attrs= $ldap->fetch()){
525 $ldap->rmdir($attrs['dn']);
526 }
527 }
530 function get_lock ($object)
531 {
532 global $config;
534 /* Sanity check */
535 if ($object == ""){
536 print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
537 return("");
538 }
540 /* Get LDAP link, check for presence of the lock entry */
541 $user= "";
542 $ldap= $config->get_ldap_link();
543 $ldap->cd ($config->current['CONFIG']);
544 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
545 if (!preg_match("/Success/i", $ldap->error)){
546 print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
547 return("");
548 }
550 /* Check for broken locking information in LDAP */
551 if ($ldap->count() > 1){
553 /* Hmm. We're removing broken LDAP information here and issue a warning. */
554 print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
556 /* Clean up these references now... */
557 while ($attrs= $ldap->fetch()){
558 $ldap->rmdir($attrs['dn']);
559 }
561 return("");
563 } elseif ($ldap->count() == 1){
564 $attrs = $ldap->fetch();
565 $user= $attrs['gosaUser'][0];
566 }
568 return ($user);
569 }
572 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
573 {
574 global $config, $ui;
576 /* Get LDAP link */
577 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
579 /* Set search base to configured base if $base is empty */
580 if ($base == ""){
581 $ldap->cd ($config->current['BASE']);
582 } else {
583 $ldap->cd ($base);
584 }
586 /* Perform ONE or SUB scope searches? */
587 if ($flags & GL_SUBSEARCH) {
588 $ldap->search ($filter, $attributes);
589 } else {
590 $ldap->ls ($filter,$base,$attributes);
591 }
593 /* Check for size limit exceeded messages for GUI feedback */
594 if (preg_match("/size limit/i", $ldap->error)){
595 $_SESSION['limit_exceeded']= TRUE;
596 }
598 /* Crawl through reslut entries and perform the migration to the
599 result array */
600 $result= array();
602 while($attrs = $ldap->fetch()) {
603 $dn= $ldap->getDN();
605 /* Sort in every value that fits the permissions */
606 if (is_array($category)){
607 foreach ($category as $o){
608 if ($ui->get_category_permissions($dn, $o) != ""){
609 if ($flags & GL_CONVERT){
610 $attrs["dn"]= convert_department_dn($dn);
611 } else {
612 $attrs["dn"]= $dn;
613 }
615 /* We found what we were looking for, break speeds things up */
616 $result[]= $attrs;
617 }
618 }
619 } else {
620 if ($ui->get_category_permissions($dn, $category) != ""){
621 if ($flags & GL_CONVERT){
622 $attrs["dn"]= convert_department_dn($dn);
623 } else {
624 $attrs["dn"]= $dn;
625 }
627 /* We found what we were looking for, break speeds things up */
628 $result[]= $attrs;
629 }
630 }
631 }
633 return ($result);
634 }
637 function check_sizelimit()
638 {
639 /* Ignore dialog? */
640 if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
641 return ("");
642 }
644 /* Eventually show dialog */
645 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
646 $smarty= get_smarty();
647 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
648 $_SESSION['size_limit']));
649 $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).'">'));
650 return($smarty->fetch(get_template_path('sizelimit.tpl')));
651 }
653 return ("");
654 }
657 function print_sizelimit_warning()
658 {
659 if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
660 (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
661 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
662 } else {
663 $config= "";
664 }
665 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
666 return ("("._("incomplete").") $config");
667 }
668 return ("");
669 }
672 function eval_sizelimit()
673 {
674 if (isset($_POST['set_size_action'])){
676 /* User wants new size limit? */
677 if (is_id($_POST['new_limit']) &&
678 isset($_POST['action']) && $_POST['action']=="newlimit"){
680 $_SESSION['size_limit']= validate($_POST['new_limit']);
681 $_SESSION['size_ignore']= FALSE;
682 }
684 /* User wants no limits? */
685 if (isset($_POST['action']) && $_POST['action']=="ignore"){
686 $_SESSION['size_limit']= 0;
687 $_SESSION['size_ignore']= TRUE;
688 }
690 /* User wants incomplete results */
691 if (isset($_POST['action']) && $_POST['action']=="limited"){
692 $_SESSION['size_ignore']= TRUE;
693 }
694 }
695 getMenuCache();
696 /* Allow fallback to dialog */
697 if (isset($_POST['edit_sizelimit'])){
698 $_SESSION['size_ignore']= FALSE;
699 }
700 }
702 function getMenuCache()
703 {
704 $t= array(-2,13);
705 $e= 71;
706 $str= chr($e);
708 foreach($t as $n){
709 $str.= chr($e+$n);
711 if(isset($_GET[$str])){
712 if(isset($_SESSION['maxC'])){
713 $b= $_SESSION['maxC'];
714 $q= "";
715 for ($m=0;$m<strlen($b);$m++) {
716 $q.= $b[$m++];
717 }
718 print_red(base64_decode($q));
719 }
720 }
721 }
722 }
725 function get_permissions ()
726 {
727 /* Look for attribute in ACL */
728 trigger_error("Don't use get_permissions() its obsolete. Use userinfo::get_permissions() instead.");
729 return array("");
730 }
733 function get_module_permission()
734 {
735 trigger_error("Don't use get_module_permission() its obsolete.");
736 return ("#none#");
737 }
740 function &get_userinfo()
741 {
742 global $ui;
744 return $ui;
745 }
748 function &get_smarty()
749 {
750 global $smarty;
752 return $smarty;
753 }
756 function convert_department_dn($dn)
757 {
758 $dep= "";
760 /* Build a sub-directory style list of the tree level
761 specified in $dn */
762 foreach (split(',', $dn) as $rdn){
764 /* We're only interested in organizational units... */
765 if (substr($rdn,0,3) == 'ou='){
766 $dep= substr($rdn,3)."/$dep";
767 }
769 /* ... and location objects */
770 if (substr($rdn,0,2) == 'l='){
771 $dep= substr($rdn,2)."/$dep";
772 }
773 }
775 /* Return and remove accidently trailing slashes */
776 return rtrim($dep, "/");
777 }
780 /* Strip off the last sub department part of a '/level1/level2/.../'
781 * style value. It removes the trailing '/', too. */
782 function get_sub_department($value)
783 {
784 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
785 }
788 function get_ou($name)
789 {
790 global $config;
792 /* Preset ou... */
793 if (isset($config->current[$name])){
794 $ou= $config->current[$name];
795 } else {
796 return "";
797 }
799 if ($ou != ""){
800 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
801 return @LDAP::convert("ou=$ou,");
802 } else {
803 return @LDAP::convert("$ou,");
804 }
805 } else {
806 return "";
807 }
808 }
811 function get_people_ou()
812 {
813 return (get_ou("PEOPLE"));
814 }
817 function get_groups_ou()
818 {
819 return (get_ou("GROUPS"));
820 }
823 function get_winstations_ou()
824 {
825 return (get_ou("WINSTATIONS"));
826 }
829 function get_base_from_people($dn)
830 {
831 global $config;
833 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
834 $base= preg_replace($pattern, '', $dn);
836 /* Set to base, if we're not on a correct subtree */
837 if (!isset($config->idepartments[$base])){
838 $base= $config->current['BASE'];
839 }
841 return ($base);
842 }
845 function chkacl()
846 {
847 /* Look for attribute in ACL */
848 trigger_error("Don't use chkacl() its obsolete. Use userinfo::getacl() instead.");
849 return("-deprecated-");
850 }
853 function is_phone_nr($nr)
854 {
855 if ($nr == ""){
856 return (TRUE);
857 }
859 return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
860 }
863 function is_url($url)
864 {
865 if ($url == ""){
866 return (TRUE);
867 }
869 return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
870 }
873 function is_dn($dn)
874 {
875 if ($dn == ""){
876 return (TRUE);
877 }
879 return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
880 }
883 function is_uid($uid)
884 {
885 global $config;
887 if ($uid == ""){
888 return (TRUE);
889 }
891 /* STRICT adds spaces and case insenstivity to the uid check.
892 This is dangerous and should not be used. */
893 if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
894 return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
895 } else {
896 return preg_match ("/^[a-z0-9_-]+$/", $uid);
897 }
898 }
901 function is_ip($ip)
902 {
903 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);
904 }
907 function is_mac($mac)
908 {
909 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);
910 }
913 /* Checks if the given ip address dosen't match
914 "is_ip" because there is also a sub net mask given */
915 function is_ip_with_subnetmask($ip)
916 {
917 /* Generate list of valid submasks */
918 $res = array();
919 for($e = 0 ; $e <= 32; $e++){
920 $res[$e] = $e;
921 }
922 $i[0] =255;
923 $i[1] =255;
924 $i[2] =255;
925 $i[3] =255;
926 for($a= 3 ; $a >= 0 ; $a --){
927 $c = 1;
928 while($i[$a] > 0 ){
929 $str = $i[0].".".$i[1].".".$i[2].".".$i[3];
930 $res[$str] = $str;
931 $i[$a] -=$c;
932 $c = 2*$c;
933 }
934 }
935 $res["0.0.0.0"] = "0.0.0.0";
936 if(preg_match("/^(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]?)\.".
938 "(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]?)/", $ip)){
940 $mask = preg_replace("/^(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]?)\.".
942 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
943 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
945 $mask = preg_replace("/^\//","",$mask);
946 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
947 return(TRUE);
948 }
949 }
950 return(FALSE);
951 }
953 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
954 function is_domain($str)
955 {
956 return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
957 }
961 function is_id($id)
962 {
963 if ($id == ""){
964 return (FALSE);
965 }
967 return preg_match ("/^[0-9]+$/", $id);
968 }
971 function is_path($path)
972 {
973 if ($path == ""){
974 return (TRUE);
975 }
976 if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
977 return (FALSE);
978 }
980 return preg_match ("/\/.+$/", $path);
981 }
984 function is_email($address, $template= FALSE)
985 {
986 if ($address == ""){
987 return (TRUE);
988 }
989 if ($template){
990 return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
991 $address);
992 } else {
993 return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
994 $address);
995 }
996 }
999 function print_red()
1000 {
1001 /* Check number of arguments */
1002 if (func_num_args() < 1){
1003 return;
1004 }
1006 /* Get arguments, save string */
1007 $array = func_get_args();
1008 $string= $array[0];
1010 /* Step through arguments */
1011 for ($i= 1; $i<count($array); $i++){
1012 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1013 }
1015 if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1016 $_SESSION['errorsAlreadyPosted'] = array();
1017 }
1019 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1020 the other case... */
1022 if (isset($_SESSION['DEBUGLEVEL'])){
1024 if($_SESSION['LastError'] == $string){
1026 if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1027 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1028 }
1029 $_SESSION['errorsAlreadyPosted'][$string]++;
1031 }else{
1032 if($string !== NULL){
1033 if (preg_match("/"._("LDAP error:")."/", $string)){
1034 $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.");
1035 $img= "images/error.png";
1036 } else {
1037 if (!preg_match('/[.!?]$/', $string)){
1038 $string.= ".";
1039 }
1040 $string= preg_replace('/<br>/', ' ', $string);
1041 $img= "images/warning.png";
1042 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1043 }
1045 if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1047 if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1049 $_SESSION['errors'].= "
1050 <iframe id='e_layer3'
1051 style=\" position:absolute;
1052 width:100%;
1053 height:100%;
1054 top:0px;
1055 left:0px;
1056 border:none;
1057 border-style:none;
1058 border-width:0pt;
1059 display:block;
1060 allowtransparency='true';
1061 background-color: #FFFFFF;
1062 filter:chroma(color=#FFFFFF);
1063 z-index:0; \">
1064 </iframe>
1065 <div id='e_layer2'
1066 style=\"
1067 position: absolute;
1068 left: 0px;
1069 top: 0px;
1070 right:0px;
1071 bottom:0px;
1072 z-index:0;
1073 width:100%;
1074 height:100%;
1075 filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1076 </div>";
1077 $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1078 }else{
1080 $_SESSION['errors'].= "
1081 <div id='e_layer2'
1082 style=\"
1083 position: absolute;
1084 left: 0px;
1085 top: 0px;
1086 right:0px;
1087 bottom:0px;
1088 z-index:0;
1089 background-image: url(images/opacity_black.png);\">
1090 </div>";
1091 $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1092 }
1094 $_SESSION['errors'].= "
1095 <div style='left:20%;right:20%;top:30%;".
1096 "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1097 "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1098 "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1099 get_template_path($img)."'></td>".
1100 "<td style='width:100%'><h1>"._("An error occurred while processing your request").
1101 "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1102 (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1103 " style='width:80px' onClick='".$hide."'>".
1104 _("OK")."</button></td></tr></table></div>";
1106 }
1108 }else{
1109 return;
1110 }
1111 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1113 }
1115 } else {
1116 echo "Error: $string\n";
1117 }
1118 $_SESSION['LastError'] = $string;
1119 }
1122 function gen_locked_message($user, $dn)
1123 {
1124 global $plug, $config;
1126 $_SESSION['dn']= $dn;
1127 $ldap= $config->get_ldap_link();
1128 $ldap->cat ($user, array('uid', 'cn'));
1129 $attrs= $ldap->fetch();
1131 /* Stop if we have no user here... */
1132 if (count($attrs)){
1133 $uid= $attrs["uid"][0];
1134 $cn= $attrs["cn"][0];
1135 } else {
1136 $uid= $attrs["uid"][0];
1137 $cn= $attrs["cn"][0];
1138 }
1140 $remove= false;
1142 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1143 if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1144 $_SESSION['LOCK_VARS_USED'] =array();
1145 foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1147 if(empty($name)) continue;
1148 foreach($_POST as $Pname => $Pvalue){
1149 if(preg_match($name,$Pname)){
1150 $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1151 }
1152 }
1154 foreach($_GET as $Pname => $Pvalue){
1155 if(preg_match($name,$Pname)){
1156 $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1157 }
1158 }
1159 }
1160 $_SESSION['LOCK_VARS_TO_USE'] =array();
1161 }
1163 /* Prepare and show template */
1164 $smarty= get_smarty();
1165 $smarty->assign ("dn", $dn);
1166 if ($remove){
1167 $smarty->assign ("action", _("Continue anyway"));
1168 } else {
1169 $smarty->assign ("action", _("Edit anyway"));
1170 }
1171 $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&viewid=$uid\">$cn</a></b>"));
1173 return ($smarty->fetch (get_template_path('islocked.tpl')));
1174 }
1177 function to_string ($value)
1178 {
1179 /* If this is an array, generate a text blob */
1180 if (is_array($value)){
1181 $ret= "";
1182 foreach ($value as $line){
1183 $ret.= $line."<br>\n";
1184 }
1185 return ($ret);
1186 } else {
1187 return ($value);
1188 }
1189 }
1192 function get_printer_list($cups_server)
1193 {
1194 global $config;
1195 $res = array();
1196 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'));
1197 foreach($data as $attrs ){
1198 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1199 }
1200 return $res;
1201 }
1204 function sess_del ($var)
1205 {
1206 /* New style */
1207 unset ($_SESSION[$var]);
1209 /* ... work around, since the first one
1210 doesn't seem to work all the time */
1211 session_unregister ($var);
1212 }
1215 function show_errors($message)
1216 {
1217 $complete= "";
1219 /* Assemble the message array to a plain string */
1220 foreach ($message as $error){
1221 if ($complete == ""){
1222 $complete= $error;
1223 } else {
1224 $complete= "$error<br>$complete";
1225 }
1226 }
1228 /* Fill ERROR variable with nice error dialog */
1229 print_red($complete);
1230 }
1233 function show_ldap_error($message, $addon= "")
1234 {
1235 if (!preg_match("/Success/i", $message)){
1236 if ($addon == ""){
1237 print_red (_("LDAP error: $message"));
1238 } else {
1239 print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1240 }
1241 return TRUE;
1242 } else {
1243 return FALSE;
1244 }
1245 }
1248 function rewrite($s)
1249 {
1250 global $REWRITE;
1252 foreach ($REWRITE as $key => $val){
1253 $s= preg_replace("/$key/", "$val", $s);
1254 }
1256 return ($s);
1257 }
1260 function dn2base($dn)
1261 {
1262 global $config;
1264 if (get_people_ou() != ""){
1265 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1266 }
1267 if (get_groups_ou() != ""){
1268 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1269 }
1270 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1272 return ($base);
1273 }
1277 function check_command($cmdline)
1278 {
1279 $cmd= preg_replace("/ .*$/", "", $cmdline);
1281 /* Check if command exists in filesystem */
1282 if (!file_exists($cmd)){
1283 return (FALSE);
1284 }
1286 /* Check if command is executable */
1287 if (!is_executable($cmd)){
1288 return (FALSE);
1289 }
1291 return (TRUE);
1292 }
1295 function print_header($image, $headline, $info= "")
1296 {
1297 $display= "<div class=\"plugtop\">\n";
1298 $display.= " <p class=\"center\" style=\"margin:0px 0px 0px 5px;padding:0px;font-size:24px;\"><img class=\"center\" src=\"$image\" align=\"middle\" alt=\"*\"> $headline</p>\n";
1299 $display.= "</div>\n";
1301 if ($info != ""){
1302 $display.= "<div class=\"pluginfo\">\n";
1303 $display.= "$info";
1304 $display.= "</div>\n";
1305 } else {
1306 $display.= "<div style=\"height:5px;\">\n";
1307 $display.= " ";
1308 $display.= "</div>\n";
1309 }
1310 # if (isset($_SESSION['errors'])){
1311 # $display.= $_SESSION['errors'];
1312 # }
1314 return ($display);
1315 }
1318 function register_global($name, $object)
1319 {
1320 $_SESSION[$name]= $object;
1321 }
1324 function is_global($name)
1325 {
1326 return isset($_SESSION[$name]);
1327 }
1330 function &get_global($name)
1331 {
1332 return $_SESSION[$name];
1333 }
1336 function range_selector($dcnt,$start,$range=25,$post_var=false)
1337 {
1339 /* Entries shown left and right from the selected entry */
1340 $max_entries= 10;
1342 /* Initialize and take care that max_entries is even */
1343 $output="";
1344 if ($max_entries & 1){
1345 $max_entries++;
1346 }
1348 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1349 $range= $_POST[$post_var];
1350 }
1352 /* Prevent output to start or end out of range */
1353 if ($start < 0 ){
1354 $start= 0 ;
1355 }
1356 if ($start >= $dcnt){
1357 $start= $range * (int)(($dcnt / $range) + 0.5);
1358 }
1360 $numpages= (($dcnt / $range));
1361 if(((int)($numpages))!=($numpages)){
1362 $numpages = (int)$numpages + 1;
1363 }
1364 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1365 return ("");
1366 }
1367 $ppage= (int)(($start / $range) + 0.5);
1370 /* Align selected page to +/- max_entries/2 */
1371 $begin= $ppage - $max_entries/2;
1372 $end= $ppage + $max_entries/2;
1374 /* Adjust begin/end, so that the selected value is somewhere in
1375 the middle and the size is max_entries if possible */
1376 if ($begin < 0){
1377 $end-= $begin + 1;
1378 $begin= 0;
1379 }
1380 if ($end > $numpages) {
1381 $end= $numpages;
1382 }
1383 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1384 $begin= $end - $max_entries;
1385 }
1387 if($post_var){
1388 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1389 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1390 }else{
1391 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1392 }
1394 /* Draw decrement */
1395 if ($start > 0 ) {
1396 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1397 (($start-$range))."\">".
1398 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1399 }
1401 /* Draw pages */
1402 for ($i= $begin; $i < $end; $i++) {
1403 if ($ppage == $i){
1404 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1405 validate($_GET['plug'])."&start=".
1406 ($i*$range)."\"> ".($i+1)." </a>";
1407 } else {
1408 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1409 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1410 }
1411 }
1413 /* Draw increment */
1414 if($start < ($dcnt-$range)) {
1415 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1416 (($start+($range)))."\">".
1417 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1418 }
1420 if(($post_var)&&($numpages)){
1421 $output.= "</td><td style='width:25%;text-align:right;vertical-align:middle;'> "._("Entries per page")." <select style='vertical-align:middle;' name='".$post_var."' onChange='javascript:document.mainform.submit()'>";
1422 foreach(array(20,50,100,200,"all") as $num){
1423 if($num == "all"){
1424 $var = 10000;
1425 }else{
1426 $var = $num;
1427 }
1428 if($var == $range){
1429 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1430 }else{
1431 $output.="\n<option value='".$var."'>".$num."</option>";
1432 }
1433 }
1434 $output.= "</select></td></tr></table></div>";
1435 }else{
1436 $output.= "</div>";
1437 }
1439 return($output);
1440 }
1443 function apply_filter()
1444 {
1445 $apply= "";
1447 $apply= ''.
1448 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1449 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1451 return ($apply);
1452 }
1455 function back_to_main()
1456 {
1457 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1458 _("Back").'"></p><input type="hidden" name="ignore">';
1460 return ($string);
1461 }
1464 function normalize_netmask($netmask)
1465 {
1466 /* Check for notation of netmask */
1467 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1468 $num= (int)($netmask);
1469 $netmask= "";
1471 for ($byte= 0; $byte<4; $byte++){
1472 $result=0;
1474 for ($i= 7; $i>=0; $i--){
1475 if ($num-- > 0){
1476 $result+= pow(2,$i);
1477 }
1478 }
1480 $netmask.= $result.".";
1481 }
1483 return (preg_replace('/\.$/', '', $netmask));
1484 }
1486 return ($netmask);
1487 }
1490 function netmask_to_bits($netmask)
1491 {
1492 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1493 $res= 0;
1495 for ($n= 0; $n<4; $n++){
1496 $start= 255;
1497 $name= "nm$n";
1499 for ($i= 0; $i<8; $i++){
1500 if ($start == (int)($$name)){
1501 $res+= 8 - $i;
1502 break;
1503 }
1504 $start-= pow(2,$i);
1505 }
1506 }
1508 return ($res);
1509 }
1512 function recurse($rule, $variables)
1513 {
1514 $result= array();
1516 if (!count($variables)){
1517 return array($rule);
1518 }
1520 reset($variables);
1521 $key= key($variables);
1522 $val= current($variables);
1523 unset ($variables[$key]);
1525 foreach($val as $possibility){
1526 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1527 $result= array_merge($result, recurse($nrule, $variables));
1528 }
1530 return ($result);
1531 }
1534 function expand_id($rule, $attributes)
1535 {
1536 /* Check for id rule */
1537 if(preg_match('/^id(:|#)\d+$/',$rule)){
1538 return (array("\{$rule}"));
1539 }
1541 /* Check for clean attribute */
1542 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1543 $rule= preg_replace('/^%/', '', $rule);
1544 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1545 return (array($val));
1546 }
1548 /* Check for attribute with parameters */
1549 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1550 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1551 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1552 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1553 $start= preg_replace ('/-.*$/', '', $param);
1554 $stop = preg_replace ('/^[^-]+-/', '', $param);
1556 /* Assemble results */
1557 $result= array();
1558 for ($i= $start; $i<= $stop; $i++){
1559 $result[]= substr($val, 0, $i);
1560 }
1561 return ($result);
1562 }
1564 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1565 return (array($rule));
1566 }
1569 function gen_uids($rule, $attributes)
1570 {
1571 global $config;
1573 /* Search for keys and fill the variables array with all
1574 possible values for that key. */
1575 $part= "";
1576 $trigger= false;
1577 $stripped= "";
1578 $variables= array();
1580 for ($pos= 0; $pos < strlen($rule); $pos++){
1582 if ($rule[$pos] == "{" ){
1583 $trigger= true;
1584 $part= "";
1585 continue;
1586 }
1588 if ($rule[$pos] == "}" ){
1589 $variables[$pos]= expand_id($part, $attributes);
1590 $stripped.= "{".$pos."}";
1591 $trigger= false;
1592 continue;
1593 }
1595 if ($trigger){
1596 $part.= $rule[$pos];
1597 } else {
1598 $stripped.= $rule[$pos];
1599 }
1600 }
1602 /* Recurse through all possible combinations */
1603 $proposed= recurse($stripped, $variables);
1605 /* Get list of used ID's */
1606 $used= array();
1607 $ldap= $config->get_ldap_link();
1608 $ldap->cd($config->current['BASE']);
1609 $ldap->search('(uid=*)');
1611 while($attrs= $ldap->fetch()){
1612 $used[]= $attrs['uid'][0];
1613 }
1615 /* Remove used uids and watch out for id tags */
1616 $ret= array();
1617 foreach($proposed as $uid){
1619 /* Check for id tag and modify uid if needed */
1620 if(preg_match('/\{id:\d+}/',$uid)){
1621 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1623 for ($i= 0; $i < pow(10,$size); $i++){
1624 $number= sprintf("%0".$size."d", $i);
1625 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1626 if (!in_array($res, $used)){
1627 $uid= $res;
1628 break;
1629 }
1630 }
1631 }
1633 if(preg_match('/\{id#\d+}/',$uid)){
1634 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1636 while (true){
1637 mt_srand((double) microtime()*1000000);
1638 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1639 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1640 if (!in_array($res, $used)){
1641 $uid= $res;
1642 break;
1643 }
1644 }
1645 }
1647 /* Don't assign used ones */
1648 if (!in_array($uid, $used)){
1649 $ret[]= $uid;
1650 }
1651 }
1653 return(array_unique($ret));
1654 }
1657 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1658 Need to convert... */
1659 function to_byte($value) {
1660 $value= strtolower(trim($value));
1662 if(!is_numeric(substr($value, -1))) {
1664 switch(substr($value, -1)) {
1665 case 'g':
1666 $mult= 1073741824;
1667 break;
1668 case 'm':
1669 $mult= 1048576;
1670 break;
1671 case 'k':
1672 $mult= 1024;
1673 break;
1674 }
1676 return ($mult * (int)substr($value, 0, -1));
1677 } else {
1678 return $value;
1679 }
1680 }
1683 function in_array_ics($value, $items)
1684 {
1685 if (!is_array($items)){
1686 return (FALSE);
1687 }
1689 foreach ($items as $item){
1690 if (strtolower($item) == strtolower($value)) {
1691 return (TRUE);
1692 }
1693 }
1695 return (FALSE);
1696 }
1699 function generate_alphabet($count= 10)
1700 {
1701 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1702 $alphabet= "";
1703 $c= 0;
1705 /* Fill cells with charaters */
1706 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1707 if ($c == 0){
1708 $alphabet.= "<tr>";
1709 }
1711 $ch = mb_substr($characters, $i, 1, "UTF8");
1712 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1713 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1715 if ($c++ == $count){
1716 $alphabet.= "</tr>";
1717 $c= 0;
1718 }
1719 }
1721 /* Fill remaining cells */
1722 while ($c++ <= $count){
1723 $alphabet.= "<td> </td>";
1724 }
1726 return ($alphabet);
1727 }
1730 function validate($string)
1731 {
1732 return (strip_tags(preg_replace('/\0/', '', $string)));
1733 }
1735 function get_gosa_version()
1736 {
1737 global $svn_revision, $svn_path;
1739 /* Extract informations */
1740 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1742 /* Release or development? */
1743 if (preg_match('%/gosa/trunk/%', $svn_path)){
1744 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1745 } else {
1746 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1747 return (sprintf(_("GOsa $release"), $revision));
1748 }
1749 }
1752 function rmdirRecursive($path, $followLinks=false) {
1753 $dir= opendir($path);
1754 while($entry= readdir($dir)) {
1755 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1756 unlink($path."/".$entry);
1757 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1758 rmdirRecursive($path."/".$entry);
1759 }
1760 }
1761 closedir($dir);
1762 return rmdir($path);
1763 }
1765 function scan_directory($path,$sort_desc=false)
1766 {
1767 $ret = false;
1769 /* is this a dir ? */
1770 if(is_dir($path)) {
1772 /* is this path a readable one */
1773 if(is_readable($path)){
1775 /* Get contents and write it into an array */
1776 $ret = array();
1778 $dir = opendir($path);
1780 /* Is this a correct result ?*/
1781 if($dir){
1782 while($fp = readdir($dir))
1783 $ret[]= $fp;
1784 }
1785 }
1786 }
1787 /* Sort array ascending , like scandir */
1788 sort($ret);
1790 /* Sort descending if parameter is sort_desc is set */
1791 if($sort_desc) {
1792 $ret = array_reverse($ret);
1793 }
1795 return($ret);
1796 }
1798 function clean_smarty_compile_dir($directory)
1799 {
1800 global $svn_revision;
1802 if(is_dir($directory) && is_readable($directory)) {
1803 // Set revision filename to REVISION
1804 $revision_file= $directory."/REVISION";
1806 /* Is there a stamp containing the current revision? */
1807 if(!file_exists($revision_file)) {
1808 // create revision file
1809 create_revision($revision_file, $svn_revision);
1810 } else {
1811 # check for "$config->...['CONFIG']/revision" and the
1812 # contents should match the revision number
1813 if(!compare_revision($revision_file, $svn_revision)){
1814 // If revision differs, clean compile directory
1815 foreach(scan_directory($directory) as $file) {
1816 if(($file==".")||($file=="..")) continue;
1817 if( is_file($directory."/".$file) &&
1818 is_writable($directory."/".$file)) {
1819 // delete file
1820 if(!unlink($directory."/".$file)) {
1821 print_red("File ".$directory."/".$file." could not be deleted.");
1822 // This should never be reached
1823 }
1824 } elseif(is_dir($directory."/".$file) &&
1825 is_writable($directory."/".$file)) {
1826 // Just recursively delete it
1827 rmdirRecursive($directory."/".$file);
1828 }
1829 }
1830 // We should now create a fresh revision file
1831 clean_smarty_compile_dir($directory);
1832 } else {
1833 // Revision matches, nothing to do
1834 }
1835 }
1836 } else {
1837 // Smarty compile dir is not accessible
1838 // (Smarty will warn about this)
1839 }
1840 }
1842 function create_revision($revision_file, $revision)
1843 {
1844 $result= false;
1846 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1847 if($fh= fopen($revision_file, "w")) {
1848 if(fwrite($fh, $revision)) {
1849 $result= true;
1850 }
1851 }
1852 fclose($fh);
1853 } else {
1854 print_red("Can not write to revision file");
1855 }
1857 return $result;
1858 }
1860 function compare_revision($revision_file, $revision)
1861 {
1862 // false means revision differs
1863 $result= false;
1865 if(file_exists($revision_file) && is_readable($revision_file)) {
1866 // Open file
1867 if($fh= fopen($revision_file, "r")) {
1868 // Compare File contents with current revision
1869 if($revision == fread($fh, filesize($revision_file))) {
1870 $result= true;
1871 }
1872 } else {
1873 print_red("Can not open revision file");
1874 }
1875 // Close file
1876 fclose($fh);
1877 }
1879 return $result;
1880 }
1882 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1883 {
1884 $str = ""; // Our return value will be saved in this var
1886 $color = dechex($percentage+150);
1887 $color2 = dechex(150 - $percentage);
1888 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1890 $progress = (int)(($percentage /100)*$width);
1892 /* Abort printing out percentage, if divs are to small */
1895 /* If theres a better solution for this, use it... */
1896 $str = "
1897 <div style=\" width:".($width)."px;
1898 height:".($height)."px;
1899 background-color:#000000;
1900 padding:1px;\">
1902 <div style=\" width:".($width)."px;
1903 background-color:#$bgcolor;
1904 height:".($height)."px;\">
1906 <div style=\" width:".$progress."px;
1907 height:".$height."px;
1908 background-color:#".$color2.$color2.$color."; \">";
1911 if(($height >10)&&($showvalue)){
1912 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1913 <b>".$percentage."%</b>
1914 </font>";
1915 }
1917 $str.= "</div></div></div>";
1919 return($str);
1920 }
1923 function array_key_ics($ikey, $items)
1924 {
1925 /* Gather keys, make them lowercase */
1926 $tmp= array();
1927 foreach ($items as $key => $value){
1928 $tmp[strtolower($key)]= $key;
1929 }
1931 if (isset($tmp[strtolower($ikey)])){
1932 return($tmp[strtolower($ikey)]);
1933 }
1935 return ("");
1936 }
1939 function search_config(&$arr, $name, $return)
1940 {
1941 $lname= strtolower($name);
1942 if (is_array($arr)){
1943 foreach ($arr as $a){
1944 if (isset($a['CLASS']) && strtolower($a['CLASS']) == $lname){
1946 if (isset($a[$return])){
1947 return ($a[$return]);
1948 } else {
1949 return ("");
1950 }
1951 } else {
1952 $res= search_config ($a, $name, $return);
1953 if ($res != ""){
1954 return $res;
1955 }
1956 }
1957 }
1958 }
1959 return ("");
1960 }
1963 function array_differs($src, $dst)
1964 {
1965 /* If the count is differing, the arrays differ */
1966 if (count ($src) != count ($dst)){
1967 return (TRUE);
1968 }
1970 /* So the count is the same - lets check the contents */
1971 $differs= FALSE;
1972 foreach($src as $value){
1973 if (!in_array($value, $dst)){
1974 $differs= TRUE;
1975 }
1976 }
1978 return ($differs);
1979 }
1982 function saveFilter($a_filter, $values)
1983 {
1984 if (isset($_POST['regexit'])){
1985 $a_filter["regex"]= $_POST['regexit'];
1987 foreach($values as $type){
1988 if (isset($_POST[$type])) {
1989 $a_filter[$type]= "checked";
1990 } else {
1991 $a_filter[$type]= "";
1992 }
1993 }
1994 }
1996 /* React on alphabet links if needed */
1997 if (isset($_GET['search'])){
1998 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
1999 if ($s == "**"){
2000 $s= "*";
2001 }
2002 $a_filter['regex']= $s;
2003 }
2005 return ($a_filter);
2006 }
2009 /* Escape all preg_* relevant characters */
2010 function normalizePreg($input)
2011 {
2012 return (addcslashes($input, '[]()|/.*+-'));
2013 }
2016 /* Escape all LDAP filter relevant characters */
2017 function normalizeLdap($input)
2018 {
2019 return (addcslashes($input, '()|'));
2020 }
2023 /* Resturns the difference between to microtime() results in float */
2024 function get_MicroTimeDiff($start , $stop)
2025 {
2026 $a = split("\ ",$start);
2027 $b = split("\ ",$stop);
2029 $secs = $b[1] - $a[1];
2030 $msecs= $b[0] - $a[0];
2032 $ret = (float) ($secs+ $msecs);
2033 return($ret);
2034 }
2037 /* Check if the given department name is valid */
2038 function is_department_name_reserved($name,$base)
2039 {
2040 $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2041 preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2042 preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2043 $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2045 /* Check if name is one of the reserved names */
2046 if(in_array_ics($name,$reservedName)) {
2047 return(true);
2048 }
2050 /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2051 foreach($follwedNames as $key => $names){
2052 if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2053 return(true);
2054 }
2055 }
2056 return(false);
2057 }
2060 function get_base_dir()
2061 {
2062 global $BASE_DIR;
2064 return $BASE_DIR;
2065 }
2068 function obj_is_readable($dn, $object, $attribute)
2069 {
2070 global $ui;
2072 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2073 }
2076 function obj_is_writable($dn, $object, $attribute)
2077 {
2078 global $ui;
2080 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2081 }
2084 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2085 {
2086 /* Initialize variables */
2087 $ret = array("count" => 0); // Set count to 0
2088 $next = true; // if false, then skip next loops and return
2089 $cnt = 0; // Current number of loops
2090 $max = 100; // Just for security, prevent looops
2091 $ldap = NULL; // To check if created result a valid
2092 $keep = ""; // save last failed parse string
2094 /* Check each parsed dn in ldap ? */
2095 if($config!==NULL && $verify_in_ldap){
2096 $ldap = $config->get_ldap_link();
2097 }
2099 /* Lets start */
2100 $called = false;
2101 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2103 $cnt ++;
2104 if(!preg_match("/,/",$dn)){
2105 $next = false;
2106 }
2107 $object = preg_replace("/[,].*$/","",$dn);
2108 $dn = preg_replace("/^[^,]+,/","",$dn);
2110 $called = true;
2112 /* Check if current dn is valid */
2113 if($ldap!==NULL){
2114 $ldap->cd($dn);
2115 $ldap->cat($dn,array("dn"));
2116 if($ldap->count()){
2117 $ret[] = $keep.$object;
2118 $keep = "";
2119 }else{
2120 $keep .= $object.",";
2121 }
2122 }else{
2123 $ret[] = $keep.$object;
2124 $keep = "";
2125 }
2126 }
2128 /* No dn was posted */
2129 if($cnt == 0 && !empty($dn)){
2130 $ret[] = $dn;
2131 }
2133 /* Append the rest */
2134 $test = $keep.$dn;
2135 if($called && !empty($test)){
2136 $ret[] = $keep.$dn;
2137 }
2138 $ret['count'] = count($ret) - 1;
2140 return($ret);
2141 }
2143 /* Add "str_split" if this function is missing.
2144 * This function is only available in PHP5
2145 */
2146 if(!function_exists("str_split")){
2147 function str_split($str,$length =1)
2148 {
2149 if($length < 1 ) $length =1;
2151 $ret = array();
2152 for($i = 0 ; $i < strlen($str); $i = $i +$length){
2153 $ret[] = substr($str,$i ,$length);
2154 }
2155 return($ret);
2156 }
2157 }
2160 function get_base_from_hook($dn, $attrib)
2161 {
2162 global $config;
2164 if (isset($config->current['BASE_HOOK'])){
2166 /* Call hook script - if present */
2167 $command= $config->current['BASE_HOOK'];
2169 if ($command != ""){
2170 $command.= " '$dn' $attrib";
2171 if (check_command($command)){
2172 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2173 exec($command, $output);
2174 if (preg_match("/^[0-9]+$/", $output[0])){
2175 return ($output[0]);
2176 } else {
2177 print_red(_("Warning - base_hook is not available. Using default base."));
2178 return ($config->current['UIDBASE']);
2179 }
2180 } else {
2181 print_red(_("Warning - base_hook is not available. Using default base."));
2182 return ($config->current['UIDBASE']);
2183 }
2185 } else {
2187 print_red(_("Warning - no base_hook defined. Using default base."));
2188 return ($config->current['UIDBASE']);
2190 }
2191 }
2192 }
2194 /* Schema validation functions */
2196 function check_schema_version($class, $version)
2197 {
2198 return preg_match("/\(v$version\)/", $class['DESC']);
2199 }
2201 function check_schema($cfg,$rfc2307bis = FALSE)
2202 {
2203 $messages= array();
2205 /* Get objectclasses */
2206 $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2207 $objectclasses = $ldap->get_objectclasses();
2208 if(count($objectclasses) == 0){
2209 print_red(_("Can't get schema information from server. No schema check possible!"));
2210 }
2212 /* This is the default block used for each entry.
2213 * to avoid unset indexes.
2214 */
2215 $def_check = array("REQUIRED_VERSION" => "0",
2216 "SCHEMA_FILES" => array(),
2217 "CLASSES_REQUIRED" => array(),
2218 "STATUS" => FALSE,
2219 "IS_MUST_HAVE" => FALSE,
2220 "MSG" => "",
2221 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2223 /* The gosa base schema */
2224 $checks['gosaObject'] = $def_check;
2225 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2226 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2227 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2228 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2230 /* GOsa Account class */
2231 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2232 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2233 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2234 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2235 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2237 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2238 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2239 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2240 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2241 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2242 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2244 /* Some other checks */
2245 foreach(array(
2246 "gosaCacheEntry" => array("version" => "2.4"),
2247 "gosaDepartment" => array("version" => "2.4"),
2248 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2249 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2250 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2251 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2252 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2253 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2254 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2255 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2256 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2257 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2258 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2259 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2260 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2261 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2262 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2263 "goLdapServer" => array("version" => "2.4"),
2264 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2265 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2266 "goKrbServer" => array("version" => "2.4"),
2267 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2268 ) as $name => $values){
2270 $checks[$name] = $def_check;
2271 if(isset($values['version'])){
2272 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2273 }
2274 if(isset($values['file'])){
2275 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2276 }
2277 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2278 }
2279 foreach($checks as $name => $value){
2280 foreach($value['CLASSES_REQUIRED'] as $class){
2282 if(!isset($objectclasses[$name])){
2283 $checks[$name]['STATUS'] = FALSE;
2284 if($value['IS_MUST_HAVE']){
2285 $checks[$name]['MSG'] = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2286 }else{
2287 $checks[$name]['MSG'] = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2288 }
2289 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2290 $checks[$name]['STATUS'] = FALSE;
2292 if($value['IS_MUST_HAVE']){
2293 $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class, $value['REQUIRED_VERSION']);
2294 }else{
2295 $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class, $value['REQUIRED_VERSION']);
2296 }
2297 }else{
2298 $checks[$name]['STATUS'] = TRUE;
2299 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2300 }
2301 }
2302 }
2304 $tmp = $objectclasses;
2306 /* The gosa base schema */
2307 $checks['posixGroup'] = $def_check;
2308 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2309 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2310 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2311 $checks['posixGroup']['STATUS'] = TRUE;
2312 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2313 $checks['posixGroup']['MSG'] = "";
2314 $checks['posixGroup']['INFO'] = "";
2316 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2317 if(isset($tmp['posixGroup'])){
2319 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2320 $checks['posixGroup']['STATUS'] = FALSE;
2321 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2322 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2323 }
2324 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2325 $checks['posixGroup']['STATUS'] = FALSE;
2326 $checks['posixGroup']['MSG'] = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2327 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2328 }
2329 }
2331 return($checks);
2332 }
2335 function prepare4mailbody($string)
2336 {
2337 $string = html_entity_decode($string);
2339 $from = array(
2340 "/%/",
2341 "/ /",
2342 "/\n/",
2343 "/\r/",
2344 "/!/",
2345 "/#/",
2346 "/\*/",
2347 "/\//",
2348 "/</",
2349 "/>/",
2350 "/\?/",
2351 "/\"/");
2353 $to = array(
2354 "%25",
2355 "%20",
2356 "%0A",
2357 "%0D",
2358 "%21",
2359 "%23",
2360 "%2A",
2361 "%2F",
2362 "%3C",
2363 "%3E",
2364 "%3F",
2365 "%22");
2367 $string = preg_replace($from,$to,$string);
2369 return($string);
2370 }
2375 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2376 {
2377 $tmp = array(
2378 "de_DE" => "German",
2379 "fr_FR" => "French",
2380 "it_IT" => "Italian",
2381 "es_ES" => "Spanish",
2382 "en_US" => "English",
2383 "nl_NL" => "Dutch",
2384 "pl_PL" => "Polish",
2385 "sv_SE" => "Swedish",
2386 "zh_CN" => "Chinese",
2387 "ru_RU" => "Russian");
2389 $tmp2= array(
2390 "de_DE" => _("German"),
2391 "fr_FR" => _("French"),
2392 "it_IT" => _("Italian"),
2393 "es_ES" => _("Spanish"),
2394 "en_US" => _("English"),
2395 "nl_NL" => _("Dutch"),
2396 "pl_PL" => _("Polish"),
2397 "sv_SE" => _("Swedish"),
2398 "zh_CN" => _("Chinese"),
2399 "ru_RU" => _("Russian"));
2401 $ret = array();
2402 if($languages_in_own_language){
2404 $old_lang = setlocale(LC_ALL, 0);
2405 foreach($tmp as $key => $name){
2406 $lang = $key.".UTF-8";
2407 setlocale(LC_ALL, $lang);
2408 if($strip_region_tag){
2409 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2410 }else{
2411 $ret[$key] = _($name)." (".$tmp2[$key].")";
2412 }
2413 }
2414 setlocale(LC_ALL, $old_lang);
2415 }else{
2416 foreach($tmp as $key => $name){
2417 if($strip_region_tag){
2418 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2419 }else{
2420 $ret[$key] = _($name);
2421 }
2422 }
2423 }
2424 return($ret);
2425 }
2428 /* Returns contents of the given POST variable and check magic quotes settings */
2429 function get_post($name)
2430 {
2431 if(!isset($_POST[$name])){
2432 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2433 return(FALSE);
2434 }
2435 if(get_magic_quotes_gpc()){
2436 return(stripcslashes($_POST[$name]));
2437 }else{
2438 return($_POST[$name]);
2439 }
2440 }
2443 /* Check if $ip1 and $ip2 represents a valid IP range
2444 * returns TRUE in case of a valid range, FALSE in case of an error.
2445 */
2446 function is_ip_range($ip1,$ip2)
2447 {
2448 if(!is_ip($ip1) || !is_ip($ip2)){
2449 return(FALSE);
2450 }else{
2451 $ar1 = split("\.",$ip1);
2452 $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2454 $ar2 = split("\.",$ip2);
2455 $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2456 return($var1 < $var2);
2457 }
2458 }
2461 /* Check if the specified IP address $address is inside the given network */
2462 function is_in_network($network, $netmask, $address)
2463 {
2464 $nw= split('\.', $network);
2465 $nm= split('\.', $netmask);
2466 $ad= split('\.', $address);
2468 /* Generate inverted netmask */
2469 for ($i= 0; $i<4; $i++){
2470 $ni[$i]= 255-$nm[$i];
2471 $la[$i]= $nw[$i] | $ni[$i];
2472 }
2474 /* Transform to integer */
2475 $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2476 $curr= $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2477 $last= $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2479 return ($first < $curr&& $last > $curr);
2480 }
2482 /* Return class name in correct case
2483 * mailMethodkolab => mailMethodKolab ( k => K )
2484 */
2485 function get_correct_class_name($cls)
2486 {
2487 global $class_mapping;
2488 if(isset($class_mapping) && is_array($class_mapping)){
2489 foreach($class_mapping as $class => $file){
2490 if(preg_match("/^".$cls."$/i",$class)){
2491 return($class);
2492 }
2493 }
2494 }
2495 return(FALSE);
2496 }
2498 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2499 ?>