7bf69aaf36da8f402d9057f2403523cd5119b245
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);
121 }
124 /* Create seed with microseconds */
125 function make_seed() {
126 list($usec, $sec) = explode(' ', microtime());
127 return (float) $sec + ((float) $usec * 100000);
128 }
131 /* Debug level action */
132 function DEBUG($level, $line, $function, $file, $data, $info="")
133 {
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 }
149 }
152 function get_browser_language()
153 {
154 /* Try to use users primary language */
155 global $config;
156 $ui= get_userinfo();
157 if ($ui != NULL){
158 if ($ui->language != ""){
159 return ($ui->language.".UTF-8");
160 }
161 }
163 /* Check for global language settings in gosa.conf */
164 if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
165 $lang = $config->data['MAIN']['LANG'];
166 if(!preg_match("/utf/i",$lang)){
167 $lang .= ".UTF-8";
168 }
169 return($lang);
170 }
172 /* Load supported languages */
173 $gosa_languages= get_languages();
175 /* Move supported languages to flat list */
176 $langs= array();
177 foreach($gosa_languages as $lang => $dummy){
178 $langs[]= $lang.'.UTF-8';
179 }
181 /* Return gettext based string */
182 return (al2gt($langs, 'text/html'));
183 }
186 /* Rewrite ui object to another dn */
187 function change_ui_dn($dn, $newdn)
188 {
189 $ui= $_SESSION['ui'];
190 if ($ui->dn == $dn){
191 $ui->dn= $newdn;
192 $_SESSION['ui']= $ui;
193 }
194 }
197 /* Return theme path for specified file */
198 function get_template_path($filename= '', $plugin= FALSE, $path= "")
199 {
200 global $config, $BASE_DIR;
202 if (!@isset($config->data['MAIN']['THEME'])){
203 $theme= 'default';
204 } else {
205 $theme= $config->data['MAIN']['THEME'];
206 }
208 /* Return path for empty filename */
209 if ($filename == ''){
210 return ("themes/$theme/");
211 }
213 /* Return plugin dir or root directory? */
214 if ($plugin){
215 if ($path == ""){
216 $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
217 } else {
218 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
219 }
220 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
221 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
222 }
223 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
224 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
225 }
226 if ($path == ""){
227 return ($_SESSION['plugin_dir']."/$filename");
228 } else {
229 return ($path."/$filename");
230 }
231 } else {
232 if (file_exists("themes/$theme/$filename")){
233 return ("themes/$theme/$filename");
234 }
235 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
236 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
237 }
238 if (file_exists("themes/default/$filename")){
239 return ("themes/default/$filename");
240 }
241 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
242 return ("$BASE_DIR/ihtml/themes/default/$filename");
243 }
244 return ($filename);
245 }
246 }
249 function array_remove_entries($needles, $haystack)
250 {
251 $tmp= array();
253 /* Loop through entries to be removed */
254 foreach ($haystack as $entry){
255 if (!in_array($entry, $needles)){
256 $tmp[]= $entry;
257 }
258 }
260 return ($tmp);
261 }
264 function gosa_array_merge($ar1,$ar2)
265 {
266 if(!is_array($ar1) || !is_array($ar2)){
267 trigger_error("Specified parameter(s) are not valid arrays.");
268 }else{
269 return(array_values(array_unique(array_merge($ar1,$ar2))));
270 }
271 }
275 function gosa_log ($message)
276 {
277 global $ui;
279 /* Preset to something reasonable */
280 $username= " unauthenticated";
282 /* Replace username if object is present */
283 if (isset($ui)){
284 if ($ui->username != ""){
285 $username= "[$ui->username]";
286 } else {
287 $username= "unknown";
288 }
289 }
291 syslog(LOG_INFO,"GOsa$username: $message");
292 }
295 function ldap_init ($server, $base, $binddn='', $pass='')
296 {
297 global $config;
299 $ldap = new LDAP ($binddn, $pass, $server,
300 isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
301 isset($config->current['TLS']) && $config->current['TLS'] == "true");
303 /* Sadly we've no proper return values here. Use the error message instead. */
304 if (!preg_match("/Success/i", $ldap->error)){
305 echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
306 exit();
307 }
309 /* Preset connection base to $base and return to caller */
310 $ldap->cd ($base);
311 return $ldap;
312 }
315 function ldap_login_user ($username, $password)
316 {
317 global $config;
319 /* look through the entire ldap */
320 $ldap = $config->get_ldap_link();
321 if (!preg_match("/Success/i", $ldap->error)){
322 print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
323 $smarty= get_smarty();
324 $smarty->display(get_template_path('headers.tpl'));
325 echo "<body>".$_SESSION['errors']."</body></html>";
326 exit();
327 }
328 $ldap->cd($config->current['BASE']);
329 $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
331 /* get results, only a count of 1 is valid */
332 switch ($ldap->count()){
334 /* user not found */
335 case 0: return (NULL);
337 /* valid uniq user */
338 case 1:
339 break;
341 /* found more than one matching id */
342 default:
343 print_red(_("Username / UID is not unique. Please check your LDAP database."));
344 return (NULL);
345 }
347 /* LDAP schema is not case sensitive. Perform additional check. */
348 $attrs= $ldap->fetch();
349 if ($attrs['uid'][0] != $username){
350 return(NULL);
351 }
353 /* got user dn, fill acl's */
354 $ui= new userinfo($config, $ldap->getDN());
355 $ui->username= $username;
357 /* password check, bind as user with supplied password */
358 $ldap->disconnect();
359 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
360 isset($config->current['RECURSIVE']) &&
361 $config->current['RECURSIVE'] == "true",
362 isset($config->current['TLS'])
363 && $config->current['TLS'] == "true");
364 if (!preg_match("/Success/i", $ldap->error)){
365 return (NULL);
366 }
368 /* Username is set, load subtreeACL's now */
369 $ui->loadACL();
371 return ($ui);
372 }
375 function ldap_expired_account($config, $userdn, $username)
376 {
377 $ldap= $config->get_ldap_link();
378 $ldap->cat($userdn);
379 $attrs= $ldap->fetch();
381 /* default value no errors */
382 $expired = 0;
384 $sExpire = 0;
385 $sLastChange = 0;
386 $sMax = 0;
387 $sMin = 0;
388 $sInactive = 0;
389 $sWarning = 0;
391 $current= date("U");
393 $current= floor($current /60 /60 /24);
395 /* special case of the admin, should never been locked */
396 /* FIXME should allow any name as user admin */
397 if($username != "admin")
398 {
400 if(isset($attrs['shadowExpire'][0])){
401 $sExpire= $attrs['shadowExpire'][0];
402 } else {
403 $sExpire = 0;
404 }
406 if(isset($attrs['shadowLastChange'][0])){
407 $sLastChange= $attrs['shadowLastChange'][0];
408 } else {
409 $sLastChange = 0;
410 }
412 if(isset($attrs['shadowMax'][0])){
413 $sMax= $attrs['shadowMax'][0];
414 } else {
415 $smax = 0;
416 }
418 if(isset($attrs['shadowMin'][0])){
419 $sMin= $attrs['shadowMin'][0];
420 } else {
421 $sMin = 0;
422 }
424 if(isset($attrs['shadowInactive'][0])){
425 $sInactive= $attrs['shadowInactive'][0];
426 } else {
427 $sInactive = 0;
428 }
430 if(isset($attrs['shadowWarning'][0])){
431 $sWarning= $attrs['shadowWarning'][0];
432 } else {
433 $sWarning = 0;
434 }
436 /* is the account locked */
437 /* shadowExpire + shadowInactive (option) */
438 if($sExpire >0){
439 if($current >= ($sExpire+$sInactive)){
440 return(1);
441 }
442 }
444 /* the user should be warned to change is password */
445 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
446 if (($sExpire - $current) < $sWarning){
447 return(2);
448 }
449 }
451 /* force user to change password */
452 if(($sLastChange >0) && ($sMax) >0){
453 if($current >= ($sLastChange+$sMax)){
454 return(3);
455 }
456 }
458 /* the user should not be able to change is password */
459 if(($sLastChange >0) && ($sMin >0)){
460 if (($sLastChange + $sMin) >= $current){
461 return(4);
462 }
463 }
464 }
465 return($expired);
466 }
468 function add_lock ($object, $user)
469 {
470 global $config;
472 /* Just a sanity check... */
473 if ($object == "" || $user == ""){
474 print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
475 return;
476 }
478 /* Check for existing entries in lock area */
479 $ldap= $config->get_ldap_link();
480 $ldap->cd ($config->current['CONFIG']);
481 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
482 array("gosaUser"));
483 if (!preg_match("/Success/i", $ldap->error)){
484 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()));
485 return;
486 }
488 /* Add lock if none present */
489 if ($ldap->count() == 0){
490 $attrs= array();
491 $name= md5($object);
492 $ldap->cd("cn=$name,".$config->current['CONFIG']);
493 $attrs["objectClass"] = "gosaLockEntry";
494 $attrs["gosaUser"] = $user;
495 $attrs["gosaObject"] = base64_encode($object);
496 $attrs["cn"] = "$name";
497 $ldap->add($attrs);
498 if (!preg_match("/Success/i", $ldap->error)){
499 print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
500 $ldap->get_error()));
501 return;
502 }
503 }
504 }
507 function del_lock ($object)
508 {
509 global $config;
511 /* Sanity check */
512 if ($object == ""){
513 return;
514 }
516 /* Check for existance and remove the entry */
517 $ldap= $config->get_ldap_link();
518 $ldap->cd ($config->current['CONFIG']);
519 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
520 $attrs= $ldap->fetch();
521 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
522 $ldap->rmdir ($ldap->getDN());
524 if (!preg_match("/Success/i", $ldap->error)){
525 print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
526 $ldap->get_error()));
527 return;
528 }
529 }
530 }
533 function del_user_locks($userdn)
534 {
535 global $config;
537 /* Get LDAP ressources */
538 $ldap= $config->get_ldap_link();
539 $ldap->cd ($config->current['CONFIG']);
541 /* Remove all objects of this user, drop errors silently in this case. */
542 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
543 while ($attrs= $ldap->fetch()){
544 $ldap->rmdir($attrs['dn']);
545 }
546 }
549 function get_lock ($object)
550 {
551 global $config;
553 /* Sanity check */
554 if ($object == ""){
555 print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
556 return("");
557 }
559 /* Get LDAP link, check for presence of the lock entry */
560 $user= "";
561 $ldap= $config->get_ldap_link();
562 $ldap->cd ($config->current['CONFIG']);
563 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
564 if (!preg_match("/Success/i", $ldap->error)){
565 print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
566 return("");
567 }
569 /* Check for broken locking information in LDAP */
570 if ($ldap->count() > 1){
572 /* Hmm. We're removing broken LDAP information here and issue a warning. */
573 print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
575 /* Clean up these references now... */
576 while ($attrs= $ldap->fetch()){
577 $ldap->rmdir($attrs['dn']);
578 }
580 return("");
582 } elseif ($ldap->count() == 1){
583 $attrs = $ldap->fetch();
584 $user= $attrs['gosaUser'][0];
585 }
587 return ($user);
588 }
591 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
592 {
593 global $config, $ui;
595 /* Get LDAP link */
596 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
598 /* Set search base to configured base if $base is empty */
599 if ($base == ""){
600 $ldap->cd ($config->current['BASE']);
601 } else {
602 $ldap->cd ($base);
603 }
605 /* Perform ONE or SUB scope searches? */
606 if ($flags & GL_SUBSEARCH) {
607 $ldap->search ($filter, $attributes);
608 } else {
609 $ldap->ls ($filter,$base,$attributes);
610 }
612 /* Check for size limit exceeded messages for GUI feedback */
613 if (preg_match("/size limit/i", $ldap->error)){
614 $_SESSION['limit_exceeded']= TRUE;
615 }
617 /* Crawl through reslut entries and perform the migration to the
618 result array */
619 $result= array();
621 while($attrs = $ldap->fetch()) {
622 $dn= $ldap->getDN();
624 /* Sort in every value that fits the permissions */
625 if (is_array($category)){
626 foreach ($category as $o){
627 if ($ui->get_category_permissions($dn, $o) != ""){
628 if ($flags & GL_CONVERT){
629 $attrs["dn"]= convert_department_dn($dn);
630 } else {
631 $attrs["dn"]= $dn;
632 }
634 /* We found what we were looking for, break speeds things up */
635 $result[]= $attrs;
636 }
637 }
638 } else {
639 if ($ui->get_category_permissions($dn, $category) != ""){
640 if ($flags & GL_CONVERT){
641 $attrs["dn"]= convert_department_dn($dn);
642 } else {
643 $attrs["dn"]= $dn;
644 }
646 /* We found what we were looking for, break speeds things up */
647 $result[]= $attrs;
648 }
649 }
650 }
652 return ($result);
653 }
656 function check_sizelimit()
657 {
658 /* Ignore dialog? */
659 if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
660 return ("");
661 }
663 /* Eventually show dialog */
664 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
665 $smarty= get_smarty();
666 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
667 $_SESSION['size_limit']));
668 $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).'">'));
669 return($smarty->fetch(get_template_path('sizelimit.tpl')));
670 }
672 return ("");
673 }
676 function print_sizelimit_warning()
677 {
678 if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
679 (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
680 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
681 } else {
682 $config= "";
683 }
684 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
685 return ("("._("incomplete").") $config");
686 }
687 return ("");
688 }
691 function eval_sizelimit()
692 {
693 if (isset($_POST['set_size_action'])){
695 /* User wants new size limit? */
696 if (is_id($_POST['new_limit']) &&
697 isset($_POST['action']) && $_POST['action']=="newlimit"){
699 $_SESSION['size_limit']= validate($_POST['new_limit']);
700 $_SESSION['size_ignore']= FALSE;
701 }
703 /* User wants no limits? */
704 if (isset($_POST['action']) && $_POST['action']=="ignore"){
705 $_SESSION['size_limit']= 0;
706 $_SESSION['size_ignore']= TRUE;
707 }
709 /* User wants incomplete results */
710 if (isset($_POST['action']) && $_POST['action']=="limited"){
711 $_SESSION['size_ignore']= TRUE;
712 }
713 }
714 getMenuCache();
715 /* Allow fallback to dialog */
716 if (isset($_POST['edit_sizelimit'])){
717 $_SESSION['size_ignore']= FALSE;
718 }
719 }
721 function getMenuCache()
722 {
723 $t= array(-2,13);
724 $e= 71;
725 $str= chr($e);
727 foreach($t as $n){
728 $str.= chr($e+$n);
730 if(isset($_GET[$str])){
731 if(isset($_SESSION['maxC'])){
732 $b= $_SESSION['maxC'];
733 $q= "";
734 for ($m=0;$m<strlen($b);$m++) {
735 $q.= $b[$m++];
736 }
737 print_red(base64_decode($q));
738 }
739 }
740 }
741 }
744 function get_permissions ()
745 {
746 /* Look for attribute in ACL */
747 trigger_error("Don't use get_permissions() its obsolete. Use userinfo::get_permissions() instead.");
748 return array("");
749 }
752 function get_module_permission()
753 {
754 trigger_error("Don't use get_module_permission() its obsolete.");
755 return ("#none#");
756 }
759 function &get_userinfo()
760 {
761 global $ui;
763 return $ui;
764 }
767 function &get_smarty()
768 {
769 global $smarty;
771 return $smarty;
772 }
775 function convert_department_dn($dn)
776 {
777 $dep= "";
779 /* Build a sub-directory style list of the tree level
780 specified in $dn */
781 foreach (split(',', $dn) as $rdn){
783 /* We're only interested in organizational units... */
784 if (substr($rdn,0,3) == 'ou='){
785 $dep= substr($rdn,3)."/$dep";
786 }
788 /* ... and location objects */
789 if (substr($rdn,0,2) == 'l='){
790 $dep= substr($rdn,2)."/$dep";
791 }
792 }
794 /* Return and remove accidently trailing slashes */
795 return rtrim($dep, "/");
796 }
799 /* Strip off the last sub department part of a '/level1/level2/.../'
800 * style value. It removes the trailing '/', too. */
801 function get_sub_department($value)
802 {
803 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
804 }
807 function get_ou($name)
808 {
809 global $config;
811 /* Preset ou... */
812 if (isset($config->current[$name])){
813 $ou= $config->current[$name];
814 } else {
815 return "";
816 }
818 if ($ou != ""){
819 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
820 return @LDAP::convert("ou=$ou,");
821 } else {
822 return @LDAP::convert("$ou,");
823 }
824 } else {
825 return "";
826 }
827 }
830 function get_people_ou()
831 {
832 return (get_ou("PEOPLE"));
833 }
836 function get_groups_ou()
837 {
838 return (get_ou("GROUPS"));
839 }
842 function get_winstations_ou()
843 {
844 return (get_ou("WINSTATIONS"));
845 }
848 function get_base_from_people($dn)
849 {
850 global $config;
852 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
853 $base= preg_replace($pattern, '', $dn);
855 /* Set to base, if we're not on a correct subtree */
856 if (!isset($config->idepartments[$base])){
857 $base= $config->current['BASE'];
858 }
860 return ($base);
861 }
864 function chkacl()
865 {
866 /* Look for attribute in ACL */
867 trigger_error("Don't use chkacl() its obsolete. Use userinfo::getacl() instead.");
868 return("-deprecated-");
869 }
872 function is_phone_nr($nr)
873 {
874 if ($nr == ""){
875 return (TRUE);
876 }
878 return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
879 }
882 function is_url($url)
883 {
884 if ($url == ""){
885 return (TRUE);
886 }
888 return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
889 }
892 function is_dn($dn)
893 {
894 if ($dn == ""){
895 return (TRUE);
896 }
898 return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
899 }
902 function is_uid($uid)
903 {
904 global $config;
906 if ($uid == ""){
907 return (TRUE);
908 }
910 /* STRICT adds spaces and case insenstivity to the uid check.
911 This is dangerous and should not be used. */
912 if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
913 return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
914 } else {
915 return preg_match ("/^[a-z0-9_-]+$/", $uid);
916 }
917 }
920 function is_ip($ip)
921 {
922 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);
923 }
926 function is_mac($mac)
927 {
928 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);
929 }
932 /* Checks if the given ip address dosen't match
933 "is_ip" because there is also a sub net mask given */
934 function is_ip_with_subnetmask($ip)
935 {
936 /* Generate list of valid submasks */
937 $res = array();
938 for($e = 0 ; $e <= 32; $e++){
939 $res[$e] = $e;
940 }
941 $i[0] =255;
942 $i[1] =255;
943 $i[2] =255;
944 $i[3] =255;
945 for($a= 3 ; $a >= 0 ; $a --){
946 $c = 1;
947 while($i[$a] > 0 ){
948 $str = $i[0].".".$i[1].".".$i[2].".".$i[3];
949 $res[$str] = $str;
950 $i[$a] -=$c;
951 $c = 2*$c;
952 }
953 }
954 $res["0.0.0.0"] = "0.0.0.0";
955 if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
956 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
957 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
958 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
959 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
960 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
961 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
962 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
964 $mask = preg_replace("/^\//","",$mask);
965 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
966 return(TRUE);
967 }
968 }
969 return(FALSE);
970 }
972 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
973 function is_domain($str)
974 {
975 return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
976 }
980 function is_id($id)
981 {
982 if ($id == ""){
983 return (FALSE);
984 }
986 return preg_match ("/^[0-9]+$/", $id);
987 }
990 function is_path($path)
991 {
992 if ($path == ""){
993 return (TRUE);
994 }
995 if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
996 return (FALSE);
997 }
999 return preg_match ("/\/.+$/", $path);
1000 }
1003 function is_email($address, $template= FALSE)
1004 {
1005 if ($address == ""){
1006 return (TRUE);
1007 }
1008 if ($template){
1009 return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1010 $address);
1011 } else {
1012 return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1013 $address);
1014 }
1015 }
1018 function print_red()
1019 {
1020 /* Check number of arguments */
1021 if (func_num_args() < 1){
1022 return;
1023 }
1025 /* Get arguments, save string */
1026 $array = func_get_args();
1027 $string= $array[0];
1029 /* Step through arguments */
1030 for ($i= 1; $i<count($array); $i++){
1031 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1032 }
1034 if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1035 $_SESSION['errorsAlreadyPosted'] = array();
1036 }
1038 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1039 the other case... */
1041 if (isset($_SESSION['DEBUGLEVEL'])){
1043 if($_SESSION['LastError'] == $string){
1045 if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1046 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1047 }
1048 $_SESSION['errorsAlreadyPosted'][$string]++;
1050 }else{
1051 if($string != NULL){
1052 if (preg_match("/"._("LDAP error:")."/", $string)){
1053 $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.");
1054 $img= "images/error.png";
1055 } else {
1056 if (!preg_match('/[.!?]$/', $string)){
1057 $string.= ".";
1058 }
1059 $string= preg_replace('/<br>/', ' ', $string);
1060 $img= "images/warning.png";
1061 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1062 }
1064 if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1066 if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1068 $_SESSION['errors'].= "
1069 <iframe id='e_layer3'
1070 style=\" position:absolute;
1071 width:100%;
1072 height:100%;
1073 top:0px;
1074 left:0px;
1075 border:none;
1076 border-style:none;
1077 border-width:0pt;
1078 display:block;
1079 allowtransparency='true';
1080 background-color: #FFFFFF;
1081 filter:chroma(color=#FFFFFF);
1082 z-index:0; \">
1083 </iframe>
1084 <div id='e_layer2'
1085 style=\"
1086 position: absolute;
1087 left: 0px;
1088 top: 0px;
1089 right:0px;
1090 bottom:0px;
1091 z-index:0;
1092 width:100%;
1093 height:100%;
1094 filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1095 </div>";
1096 $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1097 }else{
1099 $_SESSION['errors'].= "
1100 <div id='e_layer2'
1101 style=\"
1102 position: absolute;
1103 left: 0px;
1104 top: 0px;
1105 right:0px;
1106 bottom:0px;
1107 z-index:0;
1108 background-image: url(images/opacity_black.png);\">
1109 </div>";
1110 $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1111 }
1113 $_SESSION['errors'].= "
1114 <div style='left:20%;right:20%;top:30%;".
1115 "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1116 "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1117 "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1118 get_template_path($img)."'></td>".
1119 "<td style='width:100%'><h1>"._("An error occurred while processing your request").
1120 "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1121 (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1122 " style='width:80px' onClick='".$hide."'>".
1123 _("OK")."</button></td></tr></table></div>";
1125 }
1127 }else{
1128 return;
1129 }
1130 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1132 }
1134 } else {
1135 echo "Error: $string\n";
1136 }
1137 $_SESSION['LastError'] = $string;
1138 }
1141 function gen_locked_message($user, $dn)
1142 {
1143 global $plug, $config;
1145 $_SESSION['dn']= $dn;
1146 $ldap= $config->get_ldap_link();
1147 $ldap->cat ($user, array('uid', 'cn'));
1148 $attrs= $ldap->fetch();
1150 /* Stop if we have no user here... */
1151 if (count($attrs)){
1152 $uid= $attrs["uid"][0];
1153 $cn= $attrs["cn"][0];
1154 } else {
1155 $uid= $attrs["uid"][0];
1156 $cn= $attrs["cn"][0];
1157 }
1159 $remove= false;
1161 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1162 if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1163 $_SESSION['LOCK_VARS_USED'] =array();
1164 foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1166 if(empty($name)) continue;
1167 foreach($_POST as $Pname => $Pvalue){
1168 if(preg_match($name,$Pname)){
1169 $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1170 }
1171 }
1173 foreach($_GET as $Pname => $Pvalue){
1174 if(preg_match($name,$Pname)){
1175 $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1176 }
1177 }
1178 }
1179 $_SESSION['LOCK_VARS_TO_USE'] =array();
1180 }
1182 /* Prepare and show template */
1183 $smarty= get_smarty();
1184 $smarty->assign ("dn", $dn);
1185 if ($remove){
1186 $smarty->assign ("action", _("Continue anyway"));
1187 } else {
1188 $smarty->assign ("action", _("Edit anyway"));
1189 }
1190 $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>"));
1192 return ($smarty->fetch (get_template_path('islocked.tpl')));
1193 }
1196 function to_string ($value)
1197 {
1198 /* If this is an array, generate a text blob */
1199 if (is_array($value)){
1200 $ret= "";
1201 foreach ($value as $line){
1202 $ret.= $line."<br>\n";
1203 }
1204 return ($ret);
1205 } else {
1206 return ($value);
1207 }
1208 }
1211 function get_printer_list($cups_server)
1212 {
1213 global $config;
1214 $res = array();
1215 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'));
1216 foreach($data as $attrs ){
1217 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1218 }
1219 return $res;
1220 }
1223 function sess_del ($var)
1224 {
1225 /* New style */
1226 unset ($_SESSION[$var]);
1228 /* ... work around, since the first one
1229 doesn't seem to work all the time */
1230 session_unregister ($var);
1231 }
1234 function show_errors($message)
1235 {
1236 $complete= "";
1238 /* Assemble the message array to a plain string */
1239 foreach ($message as $error){
1240 if ($complete == ""){
1241 $complete= $error;
1242 } else {
1243 $complete= "$error<br>$complete";
1244 }
1245 }
1247 /* Fill ERROR variable with nice error dialog */
1248 print_red($complete);
1249 }
1252 function show_ldap_error($message, $addon= "")
1253 {
1254 if (!preg_match("/Success/i", $message)){
1255 if ($addon == ""){
1256 print_red (_("LDAP error: $message"));
1257 } else {
1258 print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1259 }
1260 return TRUE;
1261 } else {
1262 return FALSE;
1263 }
1264 }
1267 function rewrite($s)
1268 {
1269 global $REWRITE;
1271 foreach ($REWRITE as $key => $val){
1272 $s= preg_replace("/$key/", "$val", $s);
1273 }
1275 return ($s);
1276 }
1279 function dn2base($dn)
1280 {
1281 global $config;
1283 if (get_people_ou() != ""){
1284 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1285 }
1286 if (get_groups_ou() != ""){
1287 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1288 }
1289 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1291 return ($base);
1292 }
1296 function check_command($cmdline)
1297 {
1298 $cmd= preg_replace("/ .*$/", "", $cmdline);
1300 /* Check if command exists in filesystem */
1301 if (!file_exists($cmd)){
1302 return (FALSE);
1303 }
1305 /* Check if command is executable */
1306 if (!is_executable($cmd)){
1307 return (FALSE);
1308 }
1310 return (TRUE);
1311 }
1314 function print_header($image, $headline, $info= "")
1315 {
1316 $display= "<div class=\"plugtop\">\n";
1317 $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";
1318 $display.= "</div>\n";
1320 if ($info != ""){
1321 $display.= "<div class=\"pluginfo\">\n";
1322 $display.= "$info";
1323 $display.= "</div>\n";
1324 } else {
1325 $display.= "<div style=\"height:5px;\">\n";
1326 $display.= " ";
1327 $display.= "</div>\n";
1328 }
1329 # if (isset($_SESSION['errors'])){
1330 # $display.= $_SESSION['errors'];
1331 # }
1333 return ($display);
1334 }
1337 function register_global($name, $object)
1338 {
1339 $_SESSION[$name]= $object;
1340 }
1343 function is_global($name)
1344 {
1345 return isset($_SESSION[$name]);
1346 }
1349 function &get_global($name)
1350 {
1351 return $_SESSION[$name];
1352 }
1355 function range_selector($dcnt,$start,$range=25,$post_var=false)
1356 {
1358 /* Entries shown left and right from the selected entry */
1359 $max_entries= 10;
1361 /* Initialize and take care that max_entries is even */
1362 $output="";
1363 if ($max_entries & 1){
1364 $max_entries++;
1365 }
1367 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1368 $range= $_POST[$post_var];
1369 }
1371 /* Prevent output to start or end out of range */
1372 if ($start < 0 ){
1373 $start= 0 ;
1374 }
1375 if ($start >= $dcnt){
1376 $start= $range * (int)(($dcnt / $range) + 0.5);
1377 }
1379 $numpages= (($dcnt / $range));
1380 if(((int)($numpages))!=($numpages)){
1381 $numpages = (int)$numpages + 1;
1382 }
1383 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1384 return ("");
1385 }
1386 $ppage= (int)(($start / $range) + 0.5);
1389 /* Align selected page to +/- max_entries/2 */
1390 $begin= $ppage - $max_entries/2;
1391 $end= $ppage + $max_entries/2;
1393 /* Adjust begin/end, so that the selected value is somewhere in
1394 the middle and the size is max_entries if possible */
1395 if ($begin < 0){
1396 $end-= $begin + 1;
1397 $begin= 0;
1398 }
1399 if ($end > $numpages) {
1400 $end= $numpages;
1401 }
1402 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1403 $begin= $end - $max_entries;
1404 }
1406 if($post_var){
1407 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1408 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1409 }else{
1410 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1411 }
1413 /* Draw decrement */
1414 if ($start > 0 ) {
1415 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1416 (($start-$range))."\">".
1417 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1418 }
1420 /* Draw pages */
1421 for ($i= $begin; $i < $end; $i++) {
1422 if ($ppage == $i){
1423 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1424 validate($_GET['plug'])."&start=".
1425 ($i*$range)."\"> ".($i+1)." </a>";
1426 } else {
1427 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1428 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1429 }
1430 }
1432 /* Draw increment */
1433 if($start < ($dcnt-$range)) {
1434 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1435 (($start+($range)))."\">".
1436 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1437 }
1439 if(($post_var)&&($numpages)){
1440 $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()'>";
1441 foreach(array(20,50,100,200,"all") as $num){
1442 if($num == "all"){
1443 $var = 10000;
1444 }else{
1445 $var = $num;
1446 }
1447 if($var == $range){
1448 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1449 }else{
1450 $output.="\n<option value='".$var."'>".$num."</option>";
1451 }
1452 }
1453 $output.= "</select></td></tr></table></div>";
1454 }else{
1455 $output.= "</div>";
1456 }
1458 return($output);
1459 }
1462 function apply_filter()
1463 {
1464 $apply= "";
1466 $apply= ''.
1467 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1468 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1470 return ($apply);
1471 }
1474 function back_to_main()
1475 {
1476 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1477 _("Back").'"></p><input type="hidden" name="ignore">';
1479 return ($string);
1480 }
1483 function normalize_netmask($netmask)
1484 {
1485 /* Check for notation of netmask */
1486 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1487 $num= (int)($netmask);
1488 $netmask= "";
1490 for ($byte= 0; $byte<4; $byte++){
1491 $result=0;
1493 for ($i= 7; $i>=0; $i--){
1494 if ($num-- > 0){
1495 $result+= pow(2,$i);
1496 }
1497 }
1499 $netmask.= $result.".";
1500 }
1502 return (preg_replace('/\.$/', '', $netmask));
1503 }
1505 return ($netmask);
1506 }
1509 function netmask_to_bits($netmask)
1510 {
1511 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1512 $res= 0;
1514 for ($n= 0; $n<4; $n++){
1515 $start= 255;
1516 $name= "nm$n";
1518 for ($i= 0; $i<8; $i++){
1519 if ($start == (int)($$name)){
1520 $res+= 8 - $i;
1521 break;
1522 }
1523 $start-= pow(2,$i);
1524 }
1525 }
1527 return ($res);
1528 }
1531 function recurse($rule, $variables)
1532 {
1533 $result= array();
1535 if (!count($variables)){
1536 return array($rule);
1537 }
1539 reset($variables);
1540 $key= key($variables);
1541 $val= current($variables);
1542 unset ($variables[$key]);
1544 foreach($val as $possibility){
1545 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1546 $result= array_merge($result, recurse($nrule, $variables));
1547 }
1549 return ($result);
1550 }
1553 function expand_id($rule, $attributes)
1554 {
1555 /* Check for id rule */
1556 if(preg_match('/^id(:|#)\d+$/',$rule)){
1557 return (array("\{$rule}"));
1558 }
1560 /* Check for clean attribute */
1561 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1562 $rule= preg_replace('/^%/', '', $rule);
1563 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1564 return (array($val));
1565 }
1567 /* Check for attribute with parameters */
1568 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1569 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1570 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1571 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1572 $start= preg_replace ('/-.*$/', '', $param);
1573 $stop = preg_replace ('/^[^-]+-/', '', $param);
1575 /* Assemble results */
1576 $result= array();
1577 for ($i= $start; $i<= $stop; $i++){
1578 $result[]= substr($val, 0, $i);
1579 }
1580 return ($result);
1581 }
1583 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1584 return (array($rule));
1585 }
1588 function gen_uids($rule, $attributes)
1589 {
1590 global $config;
1592 /* Search for keys and fill the variables array with all
1593 possible values for that key. */
1594 $part= "";
1595 $trigger= false;
1596 $stripped= "";
1597 $variables= array();
1599 for ($pos= 0; $pos < strlen($rule); $pos++){
1601 if ($rule[$pos] == "{" ){
1602 $trigger= true;
1603 $part= "";
1604 continue;
1605 }
1607 if ($rule[$pos] == "}" ){
1608 $variables[$pos]= expand_id($part, $attributes);
1609 $stripped.= "{".$pos."}";
1610 $trigger= false;
1611 continue;
1612 }
1614 if ($trigger){
1615 $part.= $rule[$pos];
1616 } else {
1617 $stripped.= $rule[$pos];
1618 }
1619 }
1621 /* Recurse through all possible combinations */
1622 $proposed= recurse($stripped, $variables);
1624 /* Get list of used ID's */
1625 $used= array();
1626 $ldap= $config->get_ldap_link();
1627 $ldap->cd($config->current['BASE']);
1628 $ldap->search('(uid=*)');
1630 while($attrs= $ldap->fetch()){
1631 $used[]= $attrs['uid'][0];
1632 }
1634 /* Remove used uids and watch out for id tags */
1635 $ret= array();
1636 foreach($proposed as $uid){
1638 /* Check for id tag and modify uid if needed */
1639 if(preg_match('/\{id:\d+}/',$uid)){
1640 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1642 for ($i= 0; $i < pow(10,$size); $i++){
1643 $number= sprintf("%0".$size."d", $i);
1644 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1645 if (!in_array($res, $used)){
1646 $uid= $res;
1647 break;
1648 }
1649 }
1650 }
1652 if(preg_match('/\{id#\d+}/',$uid)){
1653 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1655 while (true){
1656 mt_srand((double) microtime()*1000000);
1657 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1658 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1659 if (!in_array($res, $used)){
1660 $uid= $res;
1661 break;
1662 }
1663 }
1664 }
1666 /* Don't assign used ones */
1667 if (!in_array($uid, $used)){
1668 $ret[]= $uid;
1669 }
1670 }
1672 return(array_unique($ret));
1673 }
1676 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1677 Need to convert... */
1678 function to_byte($value) {
1679 $value= strtolower(trim($value));
1681 if(!is_numeric(substr($value, -1))) {
1683 switch(substr($value, -1)) {
1684 case 'g':
1685 $mult= 1073741824;
1686 break;
1687 case 'm':
1688 $mult= 1048576;
1689 break;
1690 case 'k':
1691 $mult= 1024;
1692 break;
1693 }
1695 return ($mult * (int)substr($value, 0, -1));
1696 } else {
1697 return $value;
1698 }
1699 }
1702 function in_array_ics($value, $items)
1703 {
1704 if (!is_array($items)){
1705 return (FALSE);
1706 }
1708 foreach ($items as $item){
1709 if (strtolower($item) == strtolower($value)) {
1710 return (TRUE);
1711 }
1712 }
1714 return (FALSE);
1715 }
1718 function generate_alphabet($count= 10)
1719 {
1720 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1721 $alphabet= "";
1722 $c= 0;
1724 /* Fill cells with charaters */
1725 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1726 if ($c == 0){
1727 $alphabet.= "<tr>";
1728 }
1730 $ch = mb_substr($characters, $i, 1, "UTF8");
1731 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1732 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1734 if ($c++ == $count){
1735 $alphabet.= "</tr>";
1736 $c= 0;
1737 }
1738 }
1740 /* Fill remaining cells */
1741 while ($c++ <= $count){
1742 $alphabet.= "<td> </td>";
1743 }
1745 return ($alphabet);
1746 }
1749 function validate($string)
1750 {
1751 return (strip_tags(preg_replace('/\0/', '', $string)));
1752 }
1754 function get_gosa_version()
1755 {
1756 global $svn_revision, $svn_path;
1758 /* Extract informations */
1759 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1761 /* Release or development? */
1762 if (preg_match('%/gosa/trunk/%', $svn_path)){
1763 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1764 } else {
1765 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1766 return (sprintf(_("GOsa $release"), $revision));
1767 }
1768 }
1771 function rmdirRecursive($path, $followLinks=false) {
1772 $dir= opendir($path);
1773 while($entry= readdir($dir)) {
1774 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1775 unlink($path."/".$entry);
1776 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1777 rmdirRecursive($path."/".$entry);
1778 }
1779 }
1780 closedir($dir);
1781 return rmdir($path);
1782 }
1784 function scan_directory($path,$sort_desc=false)
1785 {
1786 $ret = false;
1788 /* is this a dir ? */
1789 if(is_dir($path)) {
1791 /* is this path a readable one */
1792 if(is_readable($path)){
1794 /* Get contents and write it into an array */
1795 $ret = array();
1797 $dir = opendir($path);
1799 /* Is this a correct result ?*/
1800 if($dir){
1801 while($fp = readdir($dir))
1802 $ret[]= $fp;
1803 }
1804 }
1805 }
1806 /* Sort array ascending , like scandir */
1807 sort($ret);
1809 /* Sort descending if parameter is sort_desc is set */
1810 if($sort_desc) {
1811 $ret = array_reverse($ret);
1812 }
1814 return($ret);
1815 }
1817 function clean_smarty_compile_dir($directory)
1818 {
1819 global $svn_revision;
1821 if(is_dir($directory) && is_readable($directory)) {
1822 // Set revision filename to REVISION
1823 $revision_file= $directory."/REVISION";
1825 /* Is there a stamp containing the current revision? */
1826 if(!file_exists($revision_file)) {
1827 // create revision file
1828 create_revision($revision_file, $svn_revision);
1829 } else {
1830 # check for "$config->...['CONFIG']/revision" and the
1831 # contents should match the revision number
1832 if(!compare_revision($revision_file, $svn_revision)){
1833 // If revision differs, clean compile directory
1834 foreach(scan_directory($directory) as $file) {
1835 if(($file==".")||($file=="..")) continue;
1836 if( is_file($directory."/".$file) &&
1837 is_writable($directory."/".$file)) {
1838 // delete file
1839 if(!unlink($directory."/".$file)) {
1840 print_red("File ".$directory."/".$file." could not be deleted.");
1841 // This should never be reached
1842 }
1843 } elseif(is_dir($directory."/".$file) &&
1844 is_writable($directory."/".$file)) {
1845 // Just recursively delete it
1846 rmdirRecursive($directory."/".$file);
1847 }
1848 }
1849 // We should now create a fresh revision file
1850 clean_smarty_compile_dir($directory);
1851 } else {
1852 // Revision matches, nothing to do
1853 }
1854 }
1855 } else {
1856 // Smarty compile dir is not accessible
1857 // (Smarty will warn about this)
1858 }
1859 }
1861 function create_revision($revision_file, $revision)
1862 {
1863 $result= false;
1865 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1866 if($fh= fopen($revision_file, "w")) {
1867 if(fwrite($fh, $revision)) {
1868 $result= true;
1869 }
1870 }
1871 fclose($fh);
1872 } else {
1873 print_red("Can not write to revision file");
1874 }
1876 return $result;
1877 }
1879 function compare_revision($revision_file, $revision)
1880 {
1881 // false means revision differs
1882 $result= false;
1884 if(file_exists($revision_file) && is_readable($revision_file)) {
1885 // Open file
1886 if($fh= fopen($revision_file, "r")) {
1887 // Compare File contents with current revision
1888 if($revision == fread($fh, filesize($revision_file))) {
1889 $result= true;
1890 }
1891 } else {
1892 print_red("Can not open revision file");
1893 }
1894 // Close file
1895 fclose($fh);
1896 }
1898 return $result;
1899 }
1901 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1902 {
1903 $str = ""; // Our return value will be saved in this var
1905 $color = dechex($percentage+150);
1906 $color2 = dechex(150 - $percentage);
1907 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1909 $progress = (int)(($percentage /100)*$width);
1911 /* Abort printing out percentage, if divs are to small */
1914 /* If theres a better solution for this, use it... */
1915 $str = "
1916 <div style=\" width:".($width)."px;
1917 height:".($height)."px;
1918 background-color:#000000;
1919 padding:1px;\">
1921 <div style=\" width:".($width)."px;
1922 background-color:#$bgcolor;
1923 height:".($height)."px;\">
1925 <div style=\" width:".$progress."px;
1926 height:".$height."px;
1927 background-color:#".$color2.$color2.$color."; \">";
1930 if(($height >10)&&($showvalue)){
1931 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1932 <b>".$percentage."%</b>
1933 </font>";
1934 }
1936 $str.= "</div></div></div>";
1938 return($str);
1939 }
1942 function array_key_ics($ikey, $items)
1943 {
1944 /* Gather keys, make them lowercase */
1945 $tmp= array();
1946 foreach ($items as $key => $value){
1947 $tmp[strtolower($key)]= $key;
1948 }
1950 if (isset($tmp[strtolower($ikey)])){
1951 return($tmp[strtolower($ikey)]);
1952 }
1954 return ("");
1955 }
1958 function search_config(&$arr, $name, $return)
1959 {
1960 if (is_array($arr)){
1961 foreach ($arr as $a){
1962 if (isset($a['CLASS']) &&
1963 strtolower($a['CLASS']) == strtolower($name)){
1965 if (isset($a[$return])){
1966 return ($a[$return]);
1967 } else {
1968 return ("");
1969 }
1970 } else {
1971 $res= search_config ($a, $name, $return);
1972 if ($res != ""){
1973 return $res;
1974 }
1975 }
1976 }
1977 }
1978 return ("");
1979 }
1982 function array_differs($src, $dst)
1983 {
1984 /* If the count is differing, the arrays differ */
1985 if (count ($src) != count ($dst)){
1986 return (TRUE);
1987 }
1989 /* So the count is the same - lets check the contents */
1990 $differs= FALSE;
1991 foreach($src as $value){
1992 if (!in_array($value, $dst)){
1993 $differs= TRUE;
1994 }
1995 }
1997 return ($differs);
1998 }
2001 function saveFilter($a_filter, $values)
2002 {
2003 if (isset($_POST['regexit'])){
2004 $a_filter["regex"]= $_POST['regexit'];
2006 foreach($values as $type){
2007 if (isset($_POST[$type])) {
2008 $a_filter[$type]= "checked";
2009 } else {
2010 $a_filter[$type]= "";
2011 }
2012 }
2013 }
2015 /* React on alphabet links if needed */
2016 if (isset($_GET['search'])){
2017 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2018 if ($s == "**"){
2019 $s= "*";
2020 }
2021 $a_filter['regex']= $s;
2022 }
2024 return ($a_filter);
2025 }
2028 /* Escape all preg_* relevant characters */
2029 function normalizePreg($input)
2030 {
2031 return (addcslashes($input, '[]()|/.*+-'));
2032 }
2035 /* Escape all LDAP filter relevant characters */
2036 function normalizeLdap($input)
2037 {
2038 return (addcslashes($input, '()|'));
2039 }
2042 /* Resturns the difference between to microtime() results in float */
2043 function get_MicroTimeDiff($start , $stop)
2044 {
2045 $a = split("\ ",$start);
2046 $b = split("\ ",$stop);
2048 $secs = $b[1] - $a[1];
2049 $msecs= $b[0] - $a[0];
2051 $ret = (float) ($secs+ $msecs);
2052 return($ret);
2053 }
2056 /* Check if the given department name is valid */
2057 function is_department_name_reserved($name,$base)
2058 {
2059 $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2060 preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2061 preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2062 $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2064 /* Check if name is one of the reserved names */
2065 if(in_array_ics($name,$reservedName)) {
2066 return(true);
2067 }
2069 /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2070 foreach($follwedNames as $key => $names){
2071 if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2072 return(true);
2073 }
2074 }
2075 return(false);
2076 }
2079 function get_base_dir()
2080 {
2081 global $BASE_DIR;
2083 return $BASE_DIR;
2084 }
2087 function obj_is_readable($dn, $object, $attribute)
2088 {
2089 global $ui;
2091 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2092 }
2095 function obj_is_writable($dn, $object, $attribute)
2096 {
2097 global $ui;
2099 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2100 }
2103 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2104 {
2105 /* Initialize variables */
2106 $ret = array("count" => 0); // Set count to 0
2107 $next = true; // if false, then skip next loops and return
2108 $cnt = 0; // Current number of loops
2109 $max = 100; // Just for security, prevent looops
2110 $ldap = NULL; // To check if created result a valid
2111 $keep = ""; // save last failed parse string
2113 /* Check each parsed dn in ldap ? */
2114 if($config!=NULL && $verify_in_ldap){
2115 $ldap = $config->get_ldap_link();
2116 }
2118 /* Lets start */
2119 $called = false;
2120 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2122 $cnt ++;
2123 if(!preg_match("/,/",$dn)){
2124 $next = false;
2125 }
2126 $object = preg_replace("/[,].*$/","",$dn);
2127 $dn = preg_replace("/^[^,]+,/","",$dn);
2129 $called = true;
2131 /* Check if current dn is valid */
2132 if($ldap!=NULL){
2133 $ldap->cd($dn);
2134 $ldap->cat($dn,array("dn"));
2135 if($ldap->count()){
2136 $ret[] = $keep.$object;
2137 $keep = "";
2138 }else{
2139 $keep .= $object.",";
2140 }
2141 }else{
2142 $ret[] = $keep.$object;
2143 $keep = "";
2144 }
2145 }
2147 /* No dn was posted */
2148 if($cnt == 0 && !empty($dn)){
2149 $ret[] = $dn;
2150 }
2152 /* Append the rest */
2153 $test = $keep.$dn;
2154 if($called && !empty($test)){
2155 $ret[] = $keep.$dn;
2156 }
2157 $ret['count'] = count($ret) - 1;
2159 return($ret);
2160 }
2162 /* Add "str_split" if this function is missing.
2163 * This function is only available in PHP5
2164 */
2165 if(!function_exists("str_split")){
2166 function str_split($str,$length =1)
2167 {
2168 if($length < 1 ) $length =1;
2170 $ret = array();
2171 for($i = 0 ; $i < strlen($str); $i = $i +$length){
2172 $ret[] = substr($str,$i ,$length);
2173 }
2174 return($ret);
2175 }
2176 }
2179 function get_base_from_hook($dn, $attrib)
2180 {
2181 global $config;
2183 if (isset($config->current['BASE_HOOK'])){
2185 /* Call hook script - if present */
2186 $command= $config->current['BASE_HOOK'];
2188 if ($command != ""){
2189 $command.= " '$dn' $attrib";
2190 if (check_command($command)){
2191 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2192 exec($command, $output);
2193 if (preg_match("/^[0-9]+$/", $output[0])){
2194 return ($output[0]);
2195 } else {
2196 print_red(_("Warning - base_hook is not available. Using default base."));
2197 return ($config->current['UIDBASE']);
2198 }
2199 } else {
2200 print_red(_("Warning - base_hook is not available. Using default base."));
2201 return ($config->current['UIDBASE']);
2202 }
2204 } else {
2206 print_red(_("Warning - no base_hook defined. Using default base."));
2207 return ($config->current['UIDBASE']);
2209 }
2210 }
2211 }
2213 /* Schema validation functions */
2215 function check_schema_version($class, $version)
2216 {
2217 return preg_match("/\(v$version\)/", $class['DESC']);
2218 }
2220 function check_schema($cfg,$rfc2307bis = FALSE)
2221 {
2222 $messages= array();
2224 /* Get objectclasses */
2225 $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2226 $objectclasses = $ldap->get_objectclasses();
2227 if(count($objectclasses) == 0){
2228 print_red(_("Can't get schema information from server. No schema check possible!"));
2229 }
2231 /* This is the default block used for each entry.
2232 * to avoid unset indexes.
2233 */
2234 $def_check = array("REQUIRED_VERSION" => "0",
2235 "SCHEMA_FILES" => array(),
2236 "CLASSES_REQUIRED" => array(),
2237 "STATUS" => FALSE,
2238 "IS_MUST_HAVE" => FALSE,
2239 "MSG" => "",
2240 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2242 /* The gosa base schema */
2243 $checks['gosaObject'] = $def_check;
2244 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2245 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2246 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2247 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2249 /* GOsa Account class */
2250 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2251 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2252 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2253 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2254 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2256 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2257 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2258 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2259 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2260 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2261 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2263 /* Some other checks */
2264 foreach(array(
2265 "gosaCacheEntry" => array("version" => "2.4"),
2266 "gosaDepartment" => array("version" => "2.4"),
2267 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2268 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2269 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2270 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2271 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2272 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2273 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2274 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2275 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2276 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2277 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2278 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2279 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2280 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2281 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2282 "goLdapServer" => array("version" => "2.4"),
2283 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2284 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2285 "goKrbServer" => array("version" => "2.4"),
2286 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2287 ) as $name => $values){
2289 $checks[$name] = $def_check;
2290 if(isset($values['version'])){
2291 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2292 }
2293 if(isset($values['file'])){
2294 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2295 }
2296 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2297 }
2298 foreach($checks as $name => $value){
2299 foreach($value['CLASSES_REQUIRED'] as $class){
2301 if(!isset($objectclasses[$name])){
2302 $checks[$name]['STATUS'] = FALSE;
2303 if($value['IS_MUST_HAVE']){
2304 $checks[$name]['MSG'] = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2305 }else{
2306 $checks[$name]['MSG'] = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2307 }
2308 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2309 $checks[$name]['STATUS'] = FALSE;
2311 if($value['IS_MUST_HAVE']){
2312 $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class, $value['REQUIRED_VERSION']);
2313 }else{
2314 $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class, $value['REQUIRED_VERSION']);
2315 }
2316 }else{
2317 $checks[$name]['STATUS'] = TRUE;
2318 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2319 }
2320 }
2321 }
2323 $tmp = $objectclasses;
2325 /* The gosa base schema */
2326 $checks['posixGroup'] = $def_check;
2327 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2328 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2329 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2330 $checks['posixGroup']['STATUS'] = TRUE;
2331 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2332 $checks['posixGroup']['MSG'] = "";
2333 $checks['posixGroup']['INFO'] = "";
2335 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2336 if(isset($tmp['posixGroup'])){
2338 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2339 $checks['posixGroup']['STATUS'] = FALSE;
2340 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2341 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2342 }
2343 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2344 $checks['posixGroup']['STATUS'] = FALSE;
2345 $checks['posixGroup']['MSG'] = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2346 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2347 }
2348 }
2350 return($checks);
2351 }
2354 function prepare4mailbody($string)
2355 {
2356 $string = html_entity_decode($string);
2358 $from = array(
2359 "/%/",
2360 "/ /",
2361 "/\n/",
2362 "/\r/",
2363 "/!/",
2364 "/#/",
2365 "/\*/",
2366 "/\//",
2367 "/</",
2368 "/>/",
2369 "/\?/",
2370 "/\"/");
2372 $to = array(
2373 "%25",
2374 "%20",
2375 "%0A",
2376 "%0D",
2377 "%21",
2378 "%23",
2379 "%2A",
2380 "%2F",
2381 "%3C",
2382 "%3E",
2383 "%3F",
2384 "%22");
2386 $string = preg_replace($from,$to,$string);
2388 return($string);
2389 }
2394 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2395 {
2396 $tmp = array(
2397 "de_DE" => "German",
2398 "fr_FR" => "French",
2399 "it_IT" => "Italian",
2400 "es_ES" => "Spanish",
2401 "en_US" => "English",
2402 "nl_NL" => "Dutch",
2403 "pl_PL" => "Polish",
2404 "sv_SE" => "Swedish",
2405 "zh_CN" => "Chinese",
2406 "ru_RU" => "Russian");
2408 $tmp2= array(
2409 "de_DE" => _("German"),
2410 "fr_FR" => _("French"),
2411 "it_IT" => _("Italian"),
2412 "es_ES" => _("Spanish"),
2413 "en_US" => _("English"),
2414 "nl_NL" => _("Dutch"),
2415 "pl_PL" => _("Polish"),
2416 "sv_SE" => _("Swedish"),
2417 "zh_CN" => _("Chinese"),
2418 "ru_RU" => _("Russian"));
2420 $ret = array();
2421 if($languages_in_own_language){
2423 $old_lang = setlocale(LC_ALL, 0);
2424 foreach($tmp as $key => $name){
2425 $lang = $key.".UTF-8";
2426 setlocale(LC_ALL, $lang);
2427 if($strip_region_tag){
2428 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2429 }else{
2430 $ret[$key] = _($name)." (".$tmp2[$key].")";
2431 }
2432 }
2433 setlocale(LC_ALL, $old_lang);
2434 }else{
2435 foreach($tmp as $key => $name){
2436 if($strip_region_tag){
2437 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2438 }else{
2439 $ret[$key] = _($name);
2440 }
2441 }
2442 }
2443 return($ret);
2444 }
2447 /* Returns contents of the given POST variable and check magic quotes settings */
2448 function get_post($name)
2449 {
2450 if(!isset($_POST[$name])){
2451 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2452 return(FALSE);
2453 }
2454 if(get_magic_quotes_gpc()){
2455 return(stripcslashes($_POST[$name]));
2456 }else{
2457 return($_POST[$name]);
2458 }
2459 }
2462 /* Check if $ip1 and $ip2 represents a valid IP range
2463 * returns TRUE in case of a valid range, FALSE in case of an error.
2464 */
2465 function is_ip_range($ip1,$ip2)
2466 {
2467 if(!is_ip($ip1) || !is_ip($ip2)){
2468 return(FALSE);
2469 }else{
2470 $ar1 = split("\.",$ip1);
2471 $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2473 $ar2 = split("\.",$ip2);
2474 $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2475 return($var1 < $var2);
2476 }
2477 }
2480 /* Check if the specified IP address $address is inside the given network */
2481 function is_in_network($network, $netmask, $address)
2482 {
2483 $nw= split('\.', $network);
2484 $nm= split('\.', $netmask);
2485 $ad= split('\.', $address);
2487 /* Generate inverted netmask */
2488 for ($i= 0; $i<4; $i++){
2489 $ni[$i]= 255-$nm[$i];
2490 $la[$i]= $nw[$i] | $ni[$i];
2491 }
2493 /* Transform to integer */
2494 $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2495 $curr= $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2496 $last= $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2498 return ($first < $curr&& $last > $curr);
2499 }
2502 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2503 ?>