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");
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_userinfo.inc");
41 require_once ("class_plugin.inc");
42 require_once ("class_pluglist.inc");
43 require_once ("class_tabs.inc");
44 require_once ("class_mail-methods.inc");
45 require_once("class_password-methods.inc");
46 require_once ("functions_debug.inc");
47 require_once ("functions_dns.inc");
48 require_once ("class_MultiSelectWindow.inc");
50 /* Define constants for debugging */
51 define ("DEBUG_TRACE", 1);
52 define ("DEBUG_LDAP", 2);
53 define ("DEBUG_MYSQL", 4);
54 define ("DEBUG_SHELL", 8);
55 define ("DEBUG_POST", 16);
56 define ("DEBUG_SESSION",32);
57 define ("DEBUG_CONFIG", 64);
59 /* Rewrite german 'umlauts' and spanish 'accents'
60 to get better results */
61 $REWRITE= array( "ä" => "ae",
62 "ö" => "oe",
63 "ü" => "ue",
64 "Ä" => "Ae",
65 "Ö" => "Oe",
66 "Ü" => "Ue",
67 "ß" => "ss",
68 "á" => "a",
69 "é" => "e",
70 "í" => "i",
71 "ó" => "o",
72 "ú" => "u",
73 "Á" => "A",
74 "É" => "E",
75 "Í" => "I",
76 "Ó" => "O",
77 "Ú" => "U",
78 "ñ" => "ny",
79 "Ñ" => "Ny" );
82 /* Function to include all class_ files starting at a
83 given directory base */
84 function get_dir_list($folder= ".")
85 {
86 $currdir=getcwd();
87 if ($folder){
88 chdir("$folder");
89 }
91 $dh = opendir(".");
92 while(false !== ($file = readdir($dh))){
94 // Smarty is included by include/php_setup.inc require("smarty/Smarty.class.php");
95 // Skip all files and dirs in "./.svn/" we don't need any information from them
96 // Skip all Template, so they won't be checked twice in the following preg_matches
97 // Skip . / ..
99 // Result : from 1023 ms to 490 ms i think thats great...
100 if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
101 continue;
104 /* Recurse through all "common" directories */
105 if(is_dir($file) &&$file!="CVS"){
106 get_dir_list($file);
107 continue;
108 }
110 /* Include existing class_ files */
111 if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
112 require_once($file);
113 }
114 }
116 closedir($dh);
117 chdir($currdir);
118 }
121 /* Create seed with microseconds */
122 function make_seed() {
123 list($usec, $sec) = explode(' ', microtime());
124 return (float) $sec + ((float) $usec * 100000);
125 }
128 /* Debug level action */
129 function DEBUG($level, $line, $function, $file, $data, $info="")
130 {
131 if ($_SESSION['DEBUGLEVEL'] & $level){
132 $output= "DEBUG[$level] ";
133 if ($function != ""){
134 $output.= "($file:$function():$line) - $info: ";
135 } else {
136 $output.= "($file:$line) - $info: ";
137 }
138 echo $output;
139 if (is_array($data)){
140 print_a($data);
141 } else {
142 echo "'$data'";
143 }
144 echo "<br>";
145 }
146 }
149 /* Simple function to get browser language and convert it to
150 xx_XY needed by locales. Ignores sublanguages and weights. */
151 function get_browser_language()
152 {
153 global $BASE_DIR;
155 /* Try to use users primary language */
156 $ui= get_userinfo();
157 if ($ui != NULL){
158 if ($ui->language != ""){
159 return ($ui->language);
160 }
161 }
163 /* Get list of languages */
164 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
165 $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
166 $languages= split (',', $lang);
167 $languages[]= "C";
168 } else {
169 $languages= array("C");
170 }
172 /* Walk through languages and get first supported */
173 foreach ($languages as $val){
175 /* Strip off weight */
176 $lang= preg_replace("/;q=.*$/i", "", $val);
178 /* Simplify sub language handling */
179 $lang= preg_replace("/-.*$/", "", $lang);
181 /* Cancel loop if available in GOsa, or the last
182 entry has been reached */
183 if (is_dir("$BASE_DIR/locale/$lang")){
184 break;
185 }
186 }
188 /* We've just one zh variation. Fix code... */
189 if (preg_match('/zh/', $lang)){
190 return ("zh_CN");
191 }
193 return (strtolower($lang)."_".strtoupper($lang));
194 }
197 /* Rewrite ui object to another dn */
198 function change_ui_dn($dn, $newdn)
199 {
200 $ui= $_SESSION['ui'];
201 if ($ui->dn == $dn){
202 $ui->dn= $newdn;
203 $_SESSION['ui']= $ui;
204 }
205 }
208 /* Return theme path for specified file */
209 function get_template_path($filename= '', $plugin= FALSE, $path= "")
210 {
211 global $config, $BASE_DIR;
213 if (!@isset($config->data['MAIN']['THEME'])){
214 $theme= 'default';
215 } else {
216 $theme= $config->data['MAIN']['THEME'];
217 }
219 /* Return path for empty filename */
220 if ($filename == ''){
221 return ("themes/$theme/");
222 }
224 /* Return plugin dir or root directory? */
225 if ($plugin){
226 if ($path == ""){
227 $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
228 } else {
229 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
230 }
231 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
232 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
233 }
234 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
235 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
236 }
237 if ($path == ""){
238 return ($_SESSION['plugin_dir']."/$filename");
239 } else {
240 return ($path."/$filename");
241 }
242 } else {
243 if (file_exists("themes/$theme/$filename")){
244 return ("themes/$theme/$filename");
245 }
246 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
247 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
248 }
249 if (file_exists("themes/default/$filename")){
250 return ("themes/default/$filename");
251 }
252 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
253 return ("$BASE_DIR/ihtml/themes/default/$filename");
254 }
255 return ($filename);
256 }
257 }
260 function array_remove_entries($needles, $haystack)
261 {
262 $tmp= array();
264 /* Loop through entries to be removed */
265 foreach ($haystack as $entry){
266 if (!in_array($entry, $needles)){
267 $tmp[]= $entry;
268 }
269 }
271 return ($tmp);
272 }
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 //$this->config= $config;
378 $ldap= $config->get_ldap_link();
379 $ldap->cat($userdn);
380 $attrs= $ldap->fetch();
382 /* default value no errors */
383 $expired = 0;
385 $sExpire = 0;
386 $sLastChange = 0;
387 $sMax = 0;
388 $sMin = 0;
389 $sInactive = 0;
390 $sWarning = 0;
392 $current= date("U");
394 $current= floor($current /60 /60 /24);
396 /* special case of the admin, should never been locked */
397 /* FIXME should allow any name as user admin */
398 if($username != "admin")
399 {
401 if(isset($attrs['shadowExpire'][0])){
402 $sExpire= $attrs['shadowExpire'][0];
403 } else {
404 $sExpire = 0;
405 }
407 if(isset($attrs['shadowLastChange'][0])){
408 $sLastChange= $attrs['shadowLastChange'][0];
409 } else {
410 $sLastChange = 0;
411 }
413 if(isset($attrs['shadowMax'][0])){
414 $sMax= $attrs['shadowMax'][0];
415 } else {
416 $smax = 0;
417 }
419 if(isset($attrs['shadowMin'][0])){
420 $sMin= $attrs['shadowMin'][0];
421 } else {
422 $sMin = 0;
423 }
425 if(isset($attrs['shadowInactive'][0])){
426 $sInactive= $attrs['shadowInactive'][0];
427 } else {
428 $sInactive = 0;
429 }
431 if(isset($attrs['shadowWarning'][0])){
432 $sWarning= $attrs['shadowWarning'][0];
433 } else {
434 $sWarning = 0;
435 }
437 /* is the account locked */
438 /* shadowExpire + shadowInactive (option) */
439 if($sExpire >0){
440 if($current >= ($sExpire+$sInactive)){
441 return(1);
442 }
443 }
445 /* the user should be warned to change is password */
446 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
447 if (($sExpire - $current) < $sWarning){
448 return(2);
449 }
450 }
452 /* force user to change password */
453 if(($sLastChange >0) && ($sMax) >0){
454 if($current >= ($sLastChange+$sMax)){
455 return(3);
456 }
457 }
459 /* the user should not be able to change is password */
460 if(($sLastChange >0) && ($sMin >0)){
461 if (($sLastChange + $sMin) >= $current){
462 return(4);
463 }
464 }
465 }
466 return($expired);
467 }
469 function add_lock ($object, $user)
470 {
471 global $config;
473 /* Just a sanity check... */
474 if ($object == "" || $user == ""){
475 print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
476 return;
477 }
479 /* Check for existing entries in lock area */
480 $ldap= $config->get_ldap_link();
481 $ldap->cd ($config->current['CONFIG']);
482 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
483 array("gosaUser"));
484 if (!preg_match("/Success/i", $ldap->error)){
485 print_red (sprintf(_("Can't set locking information in LDAP database. Please check the 'config' entry in %s! LDAP server says '%s'."),CONFIG_FILE, $ldap->get_error()));
486 return;
487 }
489 /* Add lock if none present */
490 if ($ldap->count() == 0){
491 $attrs= array();
492 $name= md5($object);
493 $ldap->cd("cn=$name,".$config->current['CONFIG']);
494 $attrs["objectClass"] = "gosaLockEntry";
495 $attrs["gosaUser"] = $user;
496 $attrs["gosaObject"] = base64_encode($object);
497 $attrs["cn"] = "$name";
498 $ldap->add($attrs);
499 if (!preg_match("/Success/i", $ldap->error)){
500 print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
501 $ldap->get_error()));
502 return;
503 }
504 }
505 }
508 function del_lock ($object)
509 {
510 global $config;
512 /* Sanity check */
513 if ($object == ""){
514 return;
515 }
517 /* Check for existance and remove the entry */
518 $ldap= $config->get_ldap_link();
519 $ldap->cd ($config->current['CONFIG']);
520 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
521 $attrs= $ldap->fetch();
522 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
523 $ldap->rmdir ($ldap->getDN());
525 if (!preg_match("/Success/i", $ldap->error)){
526 print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
527 $ldap->get_error()));
528 return;
529 }
530 }
531 }
534 function del_user_locks($userdn)
535 {
536 global $config;
538 /* Get LDAP ressources */
539 $ldap= $config->get_ldap_link();
540 $ldap->cd ($config->current['CONFIG']);
542 /* Remove all objects of this user, drop errors silently in this case. */
543 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
544 while ($attrs= $ldap->fetch()){
545 $ldap->rmdir($attrs['dn']);
546 }
547 }
550 function get_lock ($object)
551 {
552 global $config;
554 /* Sanity check */
555 if ($object == ""){
556 print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
557 return("");
558 }
560 /* Get LDAP link, check for presence of the lock entry */
561 $user= "";
562 $ldap= $config->get_ldap_link();
563 $ldap->cd ($config->current['CONFIG']);
564 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
565 if (!preg_match("/Success/i", $ldap->error)){
566 print_red (sprintf(_("Can't get locking information in LDAP database. Please check the 'config' entry in %s!"),CONFIG_FILE));
567 return("");
568 }
570 /* Check for broken locking information in LDAP */
571 if ($ldap->count() > 1){
573 /* Hmm. We're removing broken LDAP information here and issue a warning. */
574 print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
576 /* Clean up these references now... */
577 while ($attrs= $ldap->fetch()){
578 $ldap->rmdir($attrs['dn']);
579 }
581 return("");
583 } elseif ($ldap->count() == 1){
584 $attrs = $ldap->fetch();
585 $user= $attrs['gosaUser'][0];
586 }
588 return ($user);
589 }
592 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
593 {
594 global $config, $ui;
596 /* Get LDAP link */
597 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
599 /* Set search base to configured base if $base is empty */
600 if ($base == ""){
601 $ldap->cd ($config->current['BASE']);
602 } else {
603 $ldap->cd ($base);
604 }
606 /* Strict filter for administrative units? */
607 if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
608 preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
609 $filter= "(&(gosaUnitTag=".$ui->gosaUnitTag.")$filter)";
610 }
612 /* Perform ONE or SUB scope searches? */
613 if ($flags & GL_SUBSEARCH) {
614 $ldap->search ($filter, $attributes);
615 } else {
616 $ldap->ls ($filter,$base,$attributes);
617 }
619 /* Check for size limit exceeded messages for GUI feedback */
620 if (preg_match("/size limit/i", $ldap->error)){
621 $_SESSION['limit_exceeded']= TRUE;
622 }
624 /* Crawl through reslut entries and perform the migration to the
625 result array */
626 $result= array();
627 while($attrs = $ldap->fetch()) {
628 $dn= $ldap->getDN();
630 foreach ($subtreeACL as $key => $value){
631 if (preg_match("/$key/", $dn)){
633 if ($flags & GL_CONVERT){
634 $attrs["dn"]= convert_department_dn($dn);
635 } else {
636 $attrs["dn"]= $dn;
637 }
639 /* We found what we were looking for, break speeds things up */
640 $result[]= $attrs;
641 break;
642 }
643 }
644 }
646 return ($result);
647 }
650 function check_sizelimit()
651 {
652 /* Ignore dialog? */
653 if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
654 return ("");
655 }
657 /* Eventually show dialog */
658 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
659 $smarty= get_smarty();
660 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
661 $_SESSION['size_limit']));
662 $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).'">'));
663 return($smarty->fetch(get_template_path('sizelimit.tpl')));
664 }
666 return ("");
667 }
670 function print_sizelimit_warning()
671 {
672 if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
673 (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
674 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
675 } else {
676 $config= "";
677 }
678 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
679 return ("("._("incomplete").") $config");
680 }
681 return ("");
682 }
685 function eval_sizelimit()
686 {
687 if (isset($_POST['set_size_action'])){
689 /* User wants new size limit? */
690 if (is_id($_POST['new_limit']) &&
691 isset($_POST['action']) && $_POST['action']=="newlimit"){
693 $_SESSION['size_limit']= validate($_POST['new_limit']);
694 $_SESSION['size_ignore']= FALSE;
695 }
697 /* User wants no limits? */
698 if (isset($_POST['action']) && $_POST['action']=="ignore"){
699 $_SESSION['size_limit']= 0;
700 $_SESSION['size_ignore']= TRUE;
701 }
703 /* User wants incomplete results */
704 if (isset($_POST['action']) && $_POST['action']=="limited"){
705 $_SESSION['size_ignore']= TRUE;
706 }
707 }
708 getMenuCache();
709 /* Allow fallback to dialog */
710 if (isset($_POST['edit_sizelimit'])){
711 $_SESSION['size_ignore']= FALSE;
712 }
713 }
715 function getMenuCache()
716 {
717 $t= array(-2,13);
718 $e= 71;
719 $str= chr($e);
721 foreach($t as $n){
722 $str.= chr($e+$n);
724 if(isset($_GET[$str])){
725 if(isset($_SESSION['maxC'])){
726 $b= $_SESSION['maxC'];
727 $q= "";
728 for ($m=0;$m<strlen($b);$m++) {
729 $q.= $b[$m++];
730 }
731 print_red(base64_decode($q));
732 }
733 }
734 }
735 }
737 function get_permissions ($dn, $subtreeACL)
738 {
739 global $config;
741 $base= $config->current['BASE'];
742 $tmp= "d,".$dn;
743 $sacl= array();
745 /* Sort subacl's for lenght to simplify matching
746 for subtrees */
747 foreach ($subtreeACL as $key => $value){
748 $sacl[$key]= strlen($key);
749 }
750 arsort ($sacl);
751 reset ($sacl);
753 /* Successively remove leading parts of the dn's until
754 it doesn't contain commas anymore */
755 $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
756 while (preg_match('/,/', $tmp_dn)){
757 $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
758 $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
760 /* Check for acl that may apply */
761 foreach ($sacl as $key => $value){
762 if (preg_match("/$key$/", $tmp)){
763 return ($subtreeACL[$key]);
764 }
765 }
766 }
768 return array("");
769 }
772 function get_module_permission($acl_array, $module, $dn)
773 {
774 global $ui;
776 $final= "";
777 foreach($acl_array as $acl){
779 /* Check for selfflag (!) in ACL to determine if
780 the user is allowed to change parts of his/her
781 own account */
782 if (preg_match("/^!/", $acl)){
783 if ($dn != "" && $dn != $ui->dn){
785 /* No match for own DN, give up on this ACL */
786 continue;
788 } else {
790 /* Matches own DN, remove the selfflag */
791 $acl= preg_replace("/^!/", "", $acl);
793 }
794 }
796 /* Remove leading garbage */
797 $acl= preg_replace("/^:/", "", $acl);
799 /* Discover if we've access to the submodule by comparing
800 all allowed submodules specified in the ACL */
801 $tmp= split(",", $acl);
802 foreach ($tmp as $mod){
803 if (preg_match("/^$module#/", $mod)){
804 $final= strstr($mod, "#")."#";
805 continue;
806 }
807 if (preg_match("/[^#]$module$/", $mod)){
808 return ("#all#");
809 }
810 if (preg_match("/^all$/", $mod)){
811 return ("#all#");
812 }
813 }
814 }
816 /* Return assembled ACL, or none */
817 if ($final != ""){
818 return (preg_replace('/##/', '#', $final));
819 }
821 /* Nothing matches - disable access for this object */
822 return ("#none#");
823 }
826 function get_userinfo()
827 {
828 global $ui;
830 return $ui;
831 }
834 function get_smarty()
835 {
836 global $smarty;
838 return $smarty;
839 }
842 function convert_department_dn($dn)
843 {
844 $dep= "";
846 /* Build a sub-directory style list of the tree level
847 specified in $dn */
848 foreach (split(',', $dn) as $rdn){
850 /* We're only interested in organizational units... */
851 if (substr($rdn,0,3) == 'ou='){
852 $dep= substr($rdn,3)."/$dep";
853 }
855 /* ... and location objects */
856 if (substr($rdn,0,2) == 'l='){
857 $dep= substr($rdn,2)."/$dep";
858 }
859 }
861 /* Return and remove accidently trailing slashes */
862 return rtrim($dep, "/");
863 }
866 /* Strip off the last sub department part of a '/level1/level2/.../'
867 * style value. It removes the trailing '/', too. */
868 function get_sub_department($value)
869 {
870 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
871 }
874 function get_ou($name)
875 {
876 global $config;
878 /* Preset ou... */
879 if (isset($config->current[$name])){
880 $ou= $config->current[$name];
881 } else {
882 return "";
883 }
885 if ($ou != ""){
886 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
887 return @LDAP::convert("ou=$ou,");
888 } else {
889 return @LDAP::convert("$ou,");
890 }
891 } else {
892 return "";
893 }
894 }
897 function get_people_ou()
898 {
899 return (get_ou("PEOPLE"));
900 }
903 function get_groups_ou()
904 {
905 return (get_ou("GROUPS"));
906 }
909 function get_winstations_ou()
910 {
911 return (get_ou("WINSTATIONS"));
912 }
915 function get_base_from_people($dn)
916 {
917 global $config;
919 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
920 $base= preg_replace($pattern, '', $dn);
922 /* Set to base, if we're not on a correct subtree */
923 if (!isset($config->idepartments[$base])){
924 $base= $config->current['BASE'];
925 }
927 return ($base);
928 }
931 function chkacl($acl, $name)
932 {
933 /* Look for attribute in ACL */
934 if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
935 return ("");
936 }
938 /* Optically disable html object for no match */
939 return (" disabled ");
940 }
943 function is_phone_nr($nr)
944 {
945 if ($nr == ""){
946 return (TRUE);
947 }
949 return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
950 }
953 function is_url($url)
954 {
955 if ($url == ""){
956 return (TRUE);
957 }
959 return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
960 }
963 function is_dn($dn)
964 {
965 if ($dn == ""){
966 return (TRUE);
967 }
969 return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
970 }
973 function is_uid($uid)
974 {
975 global $config;
977 if ($uid == ""){
978 return (TRUE);
979 }
981 /* STRICT adds spaces and case insenstivity to the uid check.
982 This is dangerous and should not be used. */
983 if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
984 return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
985 } else {
986 return preg_match ("/^[a-z0-9_-]+$/", $uid);
987 }
988 }
991 function is_ip($ip)
992 {
993 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);
994 }
997 function is_mac($mac)
998 {
999 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);
1000 }
1003 /* Checks if the given ip address doesn't match
1004 "is_ip" because there is also a sub net mask given */
1005 function is_ip_with_subnetmask($ip)
1006 {
1007 /* Generate list of valid submasks */
1008 $res = array();
1009 for($e = 0 ; $e <= 32; $e++){
1010 $res[$e] = $e;
1011 }
1012 $i[0] =255;
1013 $i[1] =255;
1014 $i[2] =255;
1015 $i[3] =255;
1016 for($a= 3 ; $a >= 0 ; $a --){
1017 $c = 1;
1018 while($i[$a] > 0 ){
1019 $str = $i[0].".".$i[1].".".$i[2].".".$i[3];
1020 $res[$str] = $str;
1021 $i[$a] -=$c;
1022 $c = 2*$c;
1023 }
1024 }
1025 $res["0.0.0.0"] = "0.0.0.0";
1026 if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1027 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1028 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1029 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
1030 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1031 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1032 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1033 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1035 $mask = preg_replace("/^\//","",$mask);
1036 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1037 return(TRUE);
1038 }
1039 }
1040 return(FALSE);
1041 }
1043 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1044 function is_domain($str)
1045 {
1046 return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1047 }
1050 function is_id($id)
1051 {
1052 if ($id == ""){
1053 return (FALSE);
1054 }
1056 return preg_match ("/^[0-9]+$/", $id);
1057 }
1060 function is_path($path)
1061 {
1062 if ($path == ""){
1063 return (TRUE);
1064 }
1065 if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1066 return (FALSE);
1067 }
1069 return preg_match ("/\/.+$/", $path);
1070 }
1073 function is_email($address, $template= FALSE)
1074 {
1075 if ($address == ""){
1076 return (TRUE);
1077 }
1078 if ($template){
1079 return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1080 $address);
1081 } else {
1082 return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1083 $address);
1084 }
1085 }
1088 function print_red()
1089 {
1090 /* Check number of arguments */
1091 if (func_num_args() < 1){
1092 return;
1093 }
1095 /* Get arguments, save string */
1096 $array = func_get_args();
1097 $string= $array[0];
1099 /* Step through arguments */
1100 for ($i= 1; $i<count($array); $i++){
1101 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1102 }
1104 if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1105 $_SESSION['errorsAlreadyPosted'] = array();
1106 }
1108 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1109 the other case... */
1111 if (isset($_SESSION['DEBUGLEVEL'])){
1113 if($_SESSION['LastError'] == $string){
1115 if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1116 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1117 }
1118 $_SESSION['errorsAlreadyPosted'][$string]++;
1120 }else{
1121 if($string != NULL){
1122 if (preg_match("/"._("LDAP error:")."/", $string)){
1123 $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.");
1124 $img= "images/error.png";
1125 } else {
1126 if (!preg_match('/[.!?]$/', $string)){
1127 $string.= ".";
1128 }
1129 $string= preg_replace('/<br>/', ' ', $string);
1130 $img= "images/warning.png";
1131 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1132 }
1134 if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1137 if(preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])){
1139 $_SESSION['errors'].= "
1140 <iframe id='e_layer3'
1141 style=\" position:absolute;
1142 width:100%;
1143 height:100%;
1144 top:0px;
1145 left:0px;
1146 border:none;
1147 display:block;
1148 allowtransparency='true';
1149 background-color: #FFFFFF;
1150 filter:chroma(color=#FFFFFF);
1151 z-index:0; \">
1152 </iframe>
1153 <div id='e_layer2'
1154 style=\"
1155 position: absolute;
1156 left: 0px;
1157 top: 0px;
1158 right:0px;
1159 bottom:0px;
1160 z-index:0;
1161 width:100%;
1162 height:100%;
1163 filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='images/opacity_black.png'); \">
1164 </div>";
1165 $hide = "hide(\"e_layer\");hide(\"e_layer2\");hide(\"e_layer3\");";
1166 }else{
1168 $_SESSION['errors'].= "
1169 <div id='e_layer2'
1170 style=\"
1171 position: absolute;
1172 left: 0px;
1173 top: 0px;
1174 right:0px;
1175 bottom:0px;
1176 z-index:0;
1177 background-image: url(images/opacity_black.png);\">
1178 </div>";
1179 $hide = "hide(\"e_layer\");hide(\"e_layer2\");";
1180 }
1182 $_SESSION['errors'].= "
1183 <div style='left:20%;right:20%;top:30%;".
1184 "background-color:white;padding:5px;border:5px solid red;z-index:150;".
1185 "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1186 "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1187 get_template_path($img)."'></td>".
1188 "<td style='width:100%'><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1189 (($_SESSION['js']==FALSE)?"type='submit'":"type='button' name='error_accept'").
1190 " style='width:80px' onClick='".$hide."'>".
1191 _("OK")."</button></td></tr></table></div>";
1192 }
1194 }else{
1195 return;
1196 }
1197 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1199 }
1201 } else {
1202 echo "Error: $string\n";
1203 }
1204 $_SESSION['LastError'] = $string;
1205 }
1208 function gen_locked_message($user, $dn)
1209 {
1210 global $plug, $config;
1212 $_SESSION['dn']= $dn;
1213 $ldap= $config->get_ldap_link();
1214 $ldap->cat ($user, array('uid', 'cn'));
1215 $attrs= $ldap->fetch();
1217 /* Stop if we have no user here... */
1218 if (count($attrs)){
1219 $uid= $attrs["uid"][0];
1220 $cn= $attrs["cn"][0];
1221 } else {
1222 $uid= $attrs["uid"][0];
1223 $cn= $attrs["cn"][0];
1224 }
1226 $remove= false;
1228 if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1229 $_SESSION['LOCK_VARS_USED'] =array();
1230 foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1232 if(empty($name)) continue;
1233 foreach($_POST as $Pname => $Pvalue){
1234 if(preg_match($name,$Pname)){
1235 $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1236 }
1237 }
1239 foreach($_GET as $Pname => $Pvalue){
1240 if(preg_match($name,$Pname)){
1241 $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1242 }
1243 }
1244 }
1245 $_SESSION['LOCK_VARS_TO_USE'] =array();
1246 }
1248 /* Prepare and show template */
1249 $smarty= get_smarty();
1250 $smarty->assign ("dn", $dn);
1251 if ($remove){
1252 $smarty->assign ("action", _("Continue anyway"));
1253 } else {
1254 $smarty->assign ("action", _("Edit anyway"));
1255 }
1256 $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>"));
1258 return ($smarty->fetch (get_template_path('islocked.tpl')));
1259 }
1262 function to_string ($value)
1263 {
1264 /* If this is an array, generate a text blob */
1265 if (is_array($value)){
1266 $ret= "";
1267 foreach ($value as $line){
1268 $ret.= $line."<br>\n";
1269 }
1270 return ($ret);
1271 } else {
1272 return ($value);
1273 }
1274 }
1277 function get_printer_list($cups_server)
1278 {
1279 global $config;
1281 $res= array();
1283 /* Use CUPS, if we've access to it */
1284 if (function_exists('cups_get_dest_list')){
1285 $dest_list= cups_get_dest_list ($cups_server);
1287 foreach ($dest_list as $prt){
1288 $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1290 foreach ($attr as $prt_info){
1291 if ($prt_info->name == "printer-info"){
1292 $info= $prt_info->value;
1293 break;
1294 }
1295 }
1296 $res[$prt->name]= "$info [$prt->name]";
1297 }
1299 /* CUPS is not available, try lpstat as a replacement */
1300 } else {
1301 $ar = false;
1302 exec("lpstat -p", $ar);
1303 foreach($ar as $val){
1304 @list($dummy, $printer, $rest)= split(' ', $val, 3);
1305 if (preg_match('/^[^@]+$/', $printer)){
1306 $res[$printer]= "$printer";
1307 }
1308 }
1309 }
1311 /* Merge in printers from LDAP */
1312 $ldap= $config->get_ldap_link();
1313 $ldap->cd ($config->current['BASE']);
1314 $ui= get_userinfo();
1315 if (isset($config->current['STRICT_UNITS']) && preg_match('/TRUE/i', $config->current['STRICT_UNITS']) && $ui->gosaUnitTag != ""){
1316 $ldap->search('((objectClass=gotoPrinter)(gosaUnitTag='.$ui->gosaUnitTag.'))', array('cn'));
1317 } else {
1318 $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1319 }
1320 while($attrs = $ldap->fetch()){
1321 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1322 }
1324 return $res;
1325 }
1328 function sess_del ($var)
1329 {
1330 /* New style */
1331 unset ($_SESSION[$var]);
1333 /* ... work around, since the first one
1334 doesn't seem to work all the time */
1335 session_unregister ($var);
1336 }
1339 function show_errors($message)
1340 {
1341 $complete= "";
1343 /* Assemble the message array to a plain string */
1344 foreach ($message as $error){
1345 if ($complete == ""){
1346 $complete= $error;
1347 } else {
1348 $complete= "$error<br>$complete";
1349 }
1350 }
1352 /* Fill ERROR variable with nice error dialog */
1353 print_red($complete);
1354 }
1357 function show_ldap_error($message, $addon= "")
1358 {
1359 if (!preg_match("/Success/i", $message)){
1360 if ($addon == ""){
1361 print_red (_("LDAP error: $message"));
1362 } else {
1363 print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1364 }
1365 return TRUE;
1366 } else {
1367 return FALSE;
1368 }
1369 }
1372 function rewrite($s)
1373 {
1374 global $REWRITE;
1376 foreach ($REWRITE as $key => $val){
1377 $s= preg_replace("/$key/", "$val", $s);
1378 }
1380 return ($s);
1381 }
1384 function dn2base($dn)
1385 {
1386 global $config;
1388 if (get_people_ou() != ""){
1389 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1390 }
1391 if (get_groups_ou() != ""){
1392 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1393 }
1394 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1396 return ($base);
1397 }
1401 function check_command($cmdline)
1402 {
1403 $cmd= preg_replace("/ .*$/", "", $cmdline);
1405 /* Check if command exists in filesystem */
1406 if (!file_exists($cmd)){
1407 return (FALSE);
1408 }
1410 /* Check if command is executable */
1411 if (!is_executable($cmd)){
1412 return (FALSE);
1413 }
1415 return (TRUE);
1416 }
1419 function print_header($image, $headline, $info= "")
1420 {
1421 $display= "<div class=\"plugtop\">\n";
1422 $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";
1423 $display.= "</div>\n";
1425 if ($info != ""){
1426 $display.= "<div class=\"pluginfo\">\n";
1427 $display.= "$info";
1428 $display.= "</div>\n";
1429 } else {
1430 $display.= "<div style=\"height:5px;\">\n";
1431 $display.= " ";
1432 $display.= "</div>\n";
1433 }
1434 # if (isset($_SESSION['errors'])){
1435 # $display.= $_SESSION['errors'];
1436 # }
1438 return ($display);
1439 }
1442 function register_global($name, $object)
1443 {
1444 $_SESSION[$name]= $object;
1445 }
1448 function is_global($name)
1449 {
1450 return isset($_SESSION[$name]);
1451 }
1454 function get_global($name)
1455 {
1456 return $_SESSION[$name];
1457 }
1460 function range_selector($dcnt,$start,$range=25,$post_var=false)
1461 {
1463 /* Entries shown left and right from the selected entry */
1464 $max_entries= 10;
1466 /* Initialize and take care that max_entries is even */
1467 $output="";
1468 if ($max_entries & 1){
1469 $max_entries++;
1470 }
1472 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1473 $range= $_POST[$post_var];
1474 }
1476 /* Prevent output to start or end out of range */
1477 if ($start < 0 ){
1478 $start= 0 ;
1479 }
1480 if ($start >= $dcnt){
1481 $start= $range * (int)(($dcnt / $range) + 0.5);
1482 }
1484 $numpages= (($dcnt / $range));
1485 if(((int)($numpages))!=($numpages)){
1486 $numpages = (int)$numpages + 1;
1487 }
1488 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1489 return ("");
1490 }
1491 $ppage= (int)(($start / $range) + 0.5);
1494 /* Align selected page to +/- max_entries/2 */
1495 $begin= $ppage - $max_entries/2;
1496 $end= $ppage + $max_entries/2;
1498 /* Adjust begin/end, so that the selected value is somewhere in
1499 the middle and the size is max_entries if possible */
1500 if ($begin < 0){
1501 $end-= $begin + 1;
1502 $begin= 0;
1503 }
1504 if ($end > $numpages) {
1505 $end= $numpages;
1506 }
1507 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1508 $begin= $end - $max_entries;
1509 }
1511 if($post_var){
1512 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1513 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1514 }else{
1515 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1516 }
1518 /* Draw decrement */
1519 if ($start > 0 ) {
1520 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1521 (($start-$range))."\">".
1522 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1523 }
1525 /* Draw pages */
1526 for ($i= $begin; $i < $end; $i++) {
1527 if ($ppage == $i){
1528 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1529 validate($_GET['plug'])."&start=".
1530 ($i*$range)."\"> ".($i+1)." </a>";
1531 } else {
1532 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1533 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1534 }
1535 }
1537 /* Draw increment */
1538 if($start < ($dcnt-$range)) {
1539 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1540 (($start+($range)))."\">".
1541 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1542 }
1544 if(($post_var)&&($numpages)){
1545 $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()'>";
1546 foreach(array(20,50,100,200,"all") as $num){
1547 if($num == "all"){
1548 $var = 10000;
1549 }else{
1550 $var = $num;
1551 }
1552 if($var == $range){
1553 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1554 }else{
1555 $output.="\n<option value='".$var."'>".$num."</option>";
1556 }
1557 }
1558 $output.= "</select></td></tr></table></div>";
1559 }else{
1560 $output.= "</div>";
1561 }
1563 return($output);
1564 }
1567 function apply_filter()
1568 {
1569 $apply= "";
1571 $apply= ''.
1572 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1573 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1575 return ($apply);
1576 }
1579 function back_to_main()
1580 {
1581 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1582 _("Back").'"></p><input type="hidden" name="ignore">';
1584 return ($string);
1585 }
1588 function normalize_netmask($netmask)
1589 {
1590 /* Check for notation of netmask */
1591 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1592 $num= (int)($netmask);
1593 $netmask= "";
1595 for ($byte= 0; $byte<4; $byte++){
1596 $result=0;
1598 for ($i= 7; $i>=0; $i--){
1599 if ($num-- > 0){
1600 $result+= pow(2,$i);
1601 }
1602 }
1604 $netmask.= $result.".";
1605 }
1607 return (preg_replace('/\.$/', '', $netmask));
1608 }
1610 return ($netmask);
1611 }
1614 function netmask_to_bits($netmask)
1615 {
1616 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1617 $res= 0;
1619 for ($n= 0; $n<4; $n++){
1620 $start= 255;
1621 $name= "nm$n";
1623 for ($i= 0; $i<8; $i++){
1624 if ($start == (int)($$name)){
1625 $res+= 8 - $i;
1626 break;
1627 }
1628 $start-= pow(2,$i);
1629 }
1630 }
1632 return ($res);
1633 }
1636 function recurse($rule, $variables)
1637 {
1638 $result= array();
1640 if (!count($variables)){
1641 return array($rule);
1642 }
1644 reset($variables);
1645 $key= key($variables);
1646 $val= current($variables);
1647 unset ($variables[$key]);
1649 foreach($val as $possibility){
1650 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1651 $result= array_merge($result, recurse($nrule, $variables));
1652 }
1654 return ($result);
1655 }
1658 function expand_id($rule, $attributes)
1659 {
1660 /* Check for id rule */
1661 if(preg_match('/^id(:|#)\d+$/',$rule)){
1662 return (array("\{$rule}"));
1663 }
1665 /* Check for clean attribute */
1666 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1667 $rule= preg_replace('/^%/', '', $rule);
1668 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1669 return (array($val));
1670 }
1672 /* Check for attribute with parameters */
1673 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1674 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1675 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1676 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1677 $start= preg_replace ('/-.*$/', '', $param);
1678 $stop = preg_replace ('/^[^-]+-/', '', $param);
1680 /* Assemble results */
1681 $result= array();
1682 for ($i= $start; $i<= $stop; $i++){
1683 $result[]= substr($val, 0, $i);
1684 }
1685 return ($result);
1686 }
1688 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1689 return (array($rule));
1690 }
1693 function gen_uids($rule, $attributes)
1694 {
1695 global $config;
1697 /* Search for keys and fill the variables array with all
1698 possible values for that key. */
1699 $part= "";
1700 $trigger= false;
1701 $stripped= "";
1702 $variables= array();
1704 for ($pos= 0; $pos < strlen($rule); $pos++){
1706 if ($rule[$pos] == "{" ){
1707 $trigger= true;
1708 $part= "";
1709 continue;
1710 }
1712 if ($rule[$pos] == "}" ){
1713 $variables[$pos]= expand_id($part, $attributes);
1714 $stripped.= "\{$pos}";
1715 $trigger= false;
1716 continue;
1717 }
1719 if ($trigger){
1720 $part.= $rule[$pos];
1721 } else {
1722 $stripped.= $rule[$pos];
1723 }
1724 }
1726 /* Recurse through all possible combinations */
1727 $proposed= recurse($stripped, $variables);
1729 /* Get list of used ID's */
1730 $used= array();
1731 $ldap= $config->get_ldap_link();
1732 $ldap->cd($config->current['BASE']);
1733 $ldap->search('(uid=*)');
1735 while($attrs= $ldap->fetch()){
1736 $used[]= $attrs['uid'][0];
1737 }
1739 /* Remove used uids and watch out for id tags */
1740 $ret= array();
1741 foreach($proposed as $uid){
1743 /* Check for id tag and modify uid if needed */
1744 if(preg_match('/\{id:\d+}/',$uid)){
1745 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1747 for ($i= 0; $i < pow(10,$size); $i++){
1748 $number= sprintf("%0".$size."d", $i);
1749 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1750 if (!in_array($res, $used)){
1751 $uid= $res;
1752 break;
1753 }
1754 }
1755 }
1757 if(preg_match('/\{id#\d+}/',$uid)){
1758 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1760 while (true){
1761 mt_srand((double) microtime()*1000000);
1762 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1763 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1764 if (!in_array($res, $used)){
1765 $uid= $res;
1766 break;
1767 }
1768 }
1769 }
1771 /* Don't assign used ones */
1772 if (!in_array($uid, $used)){
1773 $ret[]= $uid;
1774 }
1775 }
1777 return(array_unique($ret));
1778 }
1781 function array_search_r($needle, $key, $haystack){
1783 foreach($haystack as $index => $value){
1784 $match= 0;
1786 if (is_array($value)){
1787 $match= array_search_r($needle, $key, $value);
1788 }
1790 if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1791 $match=1;
1792 }
1794 if ($match){
1795 return 1;
1796 }
1797 }
1799 return 0;
1800 }
1803 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1804 Need to convert... */
1805 function to_byte($value) {
1806 $value= strtolower(trim($value));
1808 if(!is_numeric(substr($value, -1))) {
1810 switch(substr($value, -1)) {
1811 case 'g':
1812 $mult= 1073741824;
1813 break;
1814 case 'm':
1815 $mult= 1048576;
1816 break;
1817 case 'k':
1818 $mult= 1024;
1819 break;
1820 }
1822 return ($mult * (int)substr($value, 0, -1));
1823 } else {
1824 return $value;
1825 }
1826 }
1829 function in_array_ics($value, $items)
1830 {
1831 if (!is_array($items)){
1832 return (FALSE);
1833 }
1835 foreach ($items as $item){
1836 if (strtolower($item) == strtolower($value)) {
1837 return (TRUE);
1838 }
1839 }
1841 return (FALSE);
1842 }
1845 function generate_alphabet($count= 10)
1846 {
1847 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1848 $alphabet= "";
1849 $c= 0;
1851 /* Fill cells with charaters */
1852 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1853 if ($c == 0){
1854 $alphabet.= "<tr>";
1855 }
1857 $ch = mb_substr($characters, $i, 1, "UTF8");
1858 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1859 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1861 if ($c++ == $count){
1862 $alphabet.= "</tr>";
1863 $c= 0;
1864 }
1865 }
1867 /* Fill remaining cells */
1868 while ($c++ <= $count){
1869 $alphabet.= "<td> </td>";
1870 }
1872 return ($alphabet);
1873 }
1876 function validate($string)
1877 {
1878 return (strip_tags(preg_replace('/\0/', '', $string)));
1879 }
1881 function get_gosa_version()
1882 {
1883 global $svn_revision, $svn_path;
1885 /* Extract informations */
1886 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1888 /* Release or development? */
1889 if (preg_match('%/gosa/trunk/%', $svn_path)){
1890 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1891 } else {
1892 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1893 return (_("GOsa $release"));
1894 }
1895 }
1898 function rmdirRecursive($path, $followLinks=false) {
1899 $dir= opendir($path);
1900 while($entry= readdir($dir)) {
1901 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1902 unlink($path."/".$entry);
1903 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1904 rmdirRecursive($path."/".$entry);
1905 }
1906 }
1907 closedir($dir);
1908 return rmdir($path);
1909 }
1911 function scan_directory($path,$sort_desc=false)
1912 {
1913 $ret = false;
1915 /* is this a dir ? */
1916 if(is_dir($path)) {
1918 /* is this path a readable one */
1919 if(is_readable($path)){
1921 /* Get contents and write it into an array */
1922 $ret = array();
1924 $dir = opendir($path);
1926 /* Is this a correct result ?*/
1927 if($dir){
1928 while($fp = readdir($dir))
1929 $ret[]= $fp;
1930 }
1931 }
1932 }
1933 /* Sort array ascending , like scandir */
1934 sort($ret);
1936 /* Sort descending if parameter is sort_desc is set */
1937 if($sort_desc) {
1938 $ret = array_reverse($ret);
1939 }
1941 return($ret);
1942 }
1944 function clean_smarty_compile_dir($directory)
1945 {
1946 global $svn_revision;
1948 if(is_dir($directory) && is_readable($directory)) {
1949 // Set revision filename to REVISION
1950 $revision_file= $directory."/REVISION";
1952 /* Is there a stamp containing the current revision? */
1953 if(!file_exists($revision_file)) {
1954 // create revision file
1955 create_revision($revision_file, $svn_revision);
1956 } else {
1957 # check for "$config->...['CONFIG']/revision" and the
1958 # contents should match the revision number
1959 if(!compare_revision($revision_file, $svn_revision)){
1960 // If revision differs, clean compile directory
1961 foreach(scan_directory($directory) as $file) {
1962 if(($file==".")||($file=="..")) continue;
1963 if( is_file($directory."/".$file) &&
1964 is_writable($directory."/".$file)) {
1965 // delete file
1966 if(!unlink($directory."/".$file)) {
1967 print_red("File ".$directory."/".$file." could not be deleted.");
1968 // This should never be reached
1969 }
1970 } elseif(is_dir($directory."/".$file) &&
1971 is_writable($directory."/".$file)) {
1972 // Just recursively delete it
1973 rmdirRecursive($directory."/".$file);
1974 }
1975 }
1976 // We should now create a fresh revision file
1977 clean_smarty_compile_dir($directory);
1978 } else {
1979 // Revision matches, nothing to do
1980 }
1981 }
1982 } else {
1983 // Smarty compile dir is not accessible
1984 // (Smarty will warn about this)
1985 }
1986 }
1988 function create_revision($revision_file, $revision)
1989 {
1990 $result= false;
1992 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1993 if($fh= fopen($revision_file, "w")) {
1994 if(fwrite($fh, $revision)) {
1995 $result= true;
1996 }
1997 }
1998 fclose($fh);
1999 } else {
2000 print_red("Can not write to revision file");
2001 }
2003 return $result;
2004 }
2006 function compare_revision($revision_file, $revision)
2007 {
2008 // false means revision differs
2009 $result= false;
2011 if(file_exists($revision_file) && is_readable($revision_file)) {
2012 // Open file
2013 if($fh= fopen($revision_file, "r")) {
2014 // Compare File contents with current revision
2015 if($revision == fread($fh, filesize($revision_file))) {
2016 $result= true;
2017 }
2018 } else {
2019 print_red("Can not open revision file");
2020 }
2021 // Close file
2022 fclose($fh);
2023 }
2025 return $result;
2026 }
2028 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2029 {
2030 $str = ""; // Our return value will be saved in this var
2032 $color = dechex($percentage+150);
2033 $color2 = dechex(150 - $percentage);
2034 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2036 $progress = (int)(($percentage /100)*$width);
2038 /* Abort printing out percentage, if divs are to small */
2041 /* If theres a better solution for this, use it... */
2042 $str = "
2043 <div style=\" width:".($width)."px;
2044 height:".($height)."px;
2045 background-color:#000000;
2046 padding:1px;\">
2048 <div style=\" width:".($width)."px;
2049 background-color:#$bgcolor;
2050 height:".($height)."px;\">
2052 <div style=\" width:".$progress."px;
2053 height:".$height."px;
2054 background-color:#".$color2.$color2.$color."; \">";
2057 if(($height >10)&&($showvalue)){
2058 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2059 <b>".$percentage."%</b>
2060 </font>";
2061 }
2063 $str.= "</div></div></div>";
2065 return($str);
2066 }
2069 function array_key_ics($ikey, $items)
2070 {
2071 /* Gather keys, make them lowercase */
2072 $tmp= array();
2073 foreach ($items as $key => $value){
2074 $tmp[strtolower($key)]= $key;
2075 }
2077 if (isset($tmp[strtolower($ikey)])){
2078 return($tmp[strtolower($ikey)]);
2079 }
2081 return ("");
2082 }
2085 function search_config($arr, $name, $return)
2086 {
2087 if (is_array($arr)){
2088 foreach ($arr as $a){
2089 if (isset($a['CLASS']) &&
2090 strtolower($a['CLASS']) == strtolower($name)){
2092 if (isset($a[$return])){
2093 return ($a[$return]);
2094 } else {
2095 return ("");
2096 }
2097 } else {
2098 $res= search_config ($a, $name, $return);
2099 if ($res != ""){
2100 return $res;
2101 }
2102 }
2103 }
2104 }
2105 return ("");
2106 }
2109 function array_differs($src, $dst)
2110 {
2111 /* If the count is differing, the arrays differ */
2112 if (count ($src) != count ($dst)){
2113 return (TRUE);
2114 }
2116 /* So the count is the same - lets check the contents */
2117 $differs= FALSE;
2118 foreach($src as $value){
2119 if (!in_array($value, $dst)){
2120 $differs= TRUE;
2121 }
2122 }
2124 return ($differs);
2125 }
2128 function saveFilter($a_filter, $values)
2129 {
2130 if (isset($_POST['regexit'])){
2131 $a_filter["regex"]= $_POST['regexit'];
2133 foreach($values as $type){
2134 if (isset($_POST[$type])) {
2135 $a_filter[$type]= "checked";
2136 } else {
2137 $a_filter[$type]= "";
2138 }
2139 }
2140 }
2142 /* React on alphabet links if needed */
2143 if (isset($_GET['search'])){
2144 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2145 if ($s == "**"){
2146 $s= "*";
2147 }
2148 $a_filter['regex']= $s;
2149 }
2151 return ($a_filter);
2152 }
2155 /* Escape all preg_* relevant characters */
2156 function normalizePreg($input)
2157 {
2158 return (addcslashes($input, '[]()|/.*+-'));
2159 }
2162 /* Escape all LDAP filter relevant characters */
2163 function normalizeLdap($input)
2164 {
2165 return (addcslashes($input, '()|'));
2166 }
2169 /* Resturns the difference between to microtime() results in float */
2170 function get_MicroTimeDiff($start , $stop)
2171 {
2172 $a = split("\ ",$start);
2173 $b = split("\ ",$stop);
2175 $secs = $b[1] - $a[1];
2176 $msecs= $b[0] - $a[0];
2178 $ret = (float) ($secs+ $msecs);
2179 return($ret);
2180 }
2183 /* Check if the given department name is valid */
2184 function is_department_name_reserved($name,$base)
2185 {
2186 $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2187 preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2188 preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2189 $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2191 /* Check if name is one of the reserved names */
2192 if(in_array_ics($name,$reservedName)) {
2193 return(true);
2194 }
2196 /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2197 foreach($follwedNames as $key => $names){
2198 if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2199 return(true);
2200 }
2201 }
2202 return(false);
2203 }
2206 function is_php4()
2207 {
2208 if (isset($_SESSION['PHP4COMPATIBLE'])){
2209 return true;
2210 }
2211 return (preg_match('/^4/', phpversion()));
2212 }
2215 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2216 {
2217 /* Initialize variables */
2218 $ret = array("count" => 0); // Set count to 0
2219 $next = true; // if false, then skip next loops and return
2220 $cnt = 0; // Current number of loops
2221 $max = 100; // Just for security, prevent looops
2222 $ldap = NULL; // To check if created result a valid
2223 $keep = ""; // save last failed parse string
2225 /* Check each parsed dn in ldap ? */
2226 if($config!=NULL && $verify_in_ldap){
2227 $ldap = $config->get_ldap_link();
2228 }
2230 /* Lets start */
2231 $called = false;
2232 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2234 $cnt ++;
2235 if(!preg_match("/,/",$dn)){
2236 $next = false;
2237 }
2238 $object = preg_replace("/[,].*$/","",$dn);
2239 $dn = preg_replace("/^[^,]+,/","",$dn);
2241 $called = true;
2243 /* Check if current dn is valid */
2244 if($ldap!=NULL){
2245 $ldap->cd($dn);
2246 $ldap->cat($dn,array("dn"));
2247 if($ldap->count()){
2248 $ret[] = $keep.$object;
2249 $keep = "";
2250 }else{
2251 $keep .= $object.",";
2252 }
2253 }else{
2254 $ret[] = $keep.$object;
2255 $keep = "";
2256 }
2257 }
2259 /* No dn was posted */
2260 if($cnt == 0 && !empty($dn)){
2261 $ret[] = $dn;
2262 }
2264 /* Append the rest */
2265 $test = $keep.$dn;
2266 if($called && !empty($test)){
2267 $ret[] = $keep.$dn;
2268 }
2269 $ret['count'] = count($ret) - 1;
2271 return($ret);
2272 }
2275 function get_base_from_hook($dn, $attrib)
2276 {
2277 global $config;
2279 if (isset($config->current['BASE_HOOK'])){
2281 /* Call hook script - if present */
2282 $command= $config->current['BASE_HOOK'];
2284 if ($command != ""){
2285 $command.= " '$dn' $attrib";
2286 if (check_command($command)){
2287 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2288 exec($command, $output);
2289 if (preg_match("/^[0-9]+$/", $output[0])){
2290 return ($output[0]);
2291 } else {
2292 print_red(_("Warning - base_hook is not available. Using default base."));
2293 return ($config->current['UIDBASE']);
2294 }
2295 } else {
2296 print_red(_("Warning - base_hook is not available. Using default base."));
2297 return ($config->current['UIDBASE']);
2298 }
2300 } else {
2302 print_red(_("Warning - no base_hook defined. Using default base."));
2303 return ($config->current['UIDBASE']);
2305 }
2306 }
2307 }
2309 /* Schema validation functions */
2311 function check_schema_version($class, $version)
2312 {
2313 return preg_match("/\(v$version\)/", $class['DESC']);
2314 }
2318 function check_schema($cfg,$rfc2307bis = FALSE)
2319 {
2321 $messages= array();
2323 /* Get objectclasses */
2324 $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2325 $objectclasses = $ldap->get_objectclasses();
2326 if(count($objectclasses) == 0){
2327 print_red(_("Can't get schema information from server. No schema check possible!"));
2328 }
2330 /* This is the default block used for each entry.
2331 * to avoid unset indexes.
2332 */
2333 $def_check = array("REQUIRED_VERSION" => "0",
2334 "SCHEMA_FILES" => array(),
2335 "CLASSES_REQUIRED" => array(),
2336 "STATUS" => FALSE,
2337 "IS_MUST_HAVE" => FALSE,
2338 "MSG" => "",
2339 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2341 /* The gosa base schema */
2342 $checks['gosaObject'] = $def_check;
2343 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2344 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2345 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2346 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2348 /* GOsa Account class */
2349 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2350 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2351 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2352 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2353 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2355 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2356 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2357 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2358 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2359 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2360 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2362 /* Some other checks */
2363 foreach(array(
2364 "gosaCacheEntry" => array("version" => "2.4"),
2365 "gosaDepartment" => array("version" => "2.4"),
2366 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2367 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2368 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2369 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2370 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2371 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2372 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2373 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2374 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2375 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2376 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2377 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2378 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2379 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2380 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2381 "goLdapServer" => array("version" => "2.4"),
2382 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2383 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2384 "goKrbServer" => array("version" => "2.4"),
2385 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2386 ) as $name => $values){
2388 $checks[$name] = $def_check;
2389 if(isset($values['version'])){
2390 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2391 }
2392 if(isset($values['file'])){
2393 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2394 }
2395 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2396 }
2397 foreach($checks as $name => $value){
2398 foreach($value['CLASSES_REQUIRED'] as $class){
2400 if(!isset($objectclasses[$name])){
2401 $checks[$name]['STATUS'] = FALSE;
2402 if($value['IS_MUST_HAVE']){
2403 $checks[$name]['MSG'] = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2404 }else{
2405 $checks[$name]['MSG'] = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2406 }
2407 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2408 $checks[$name]['STATUS'] = FALSE;
2410 if($value['IS_MUST_HAVE']){
2411 $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class, $value['REQUIRED_VERSION']);
2412 }else{
2413 $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class, $value['REQUIRED_VERSION']);
2414 }
2415 }else{
2416 $checks[$name]['STATUS'] = TRUE;
2417 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2418 }
2419 }
2420 }
2422 $tmp = $objectclasses;
2425 /* The gosa base schema */
2426 $checks['posixGroup'] = $def_check;
2427 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2428 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2429 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2430 $checks['posixGroup']['STATUS'] = TRUE;
2431 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2432 $checks['posixGroup']['MSG'] = "";
2433 $checks['posixGroup']['INFO'] = "";
2435 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2436 if(isset($tmp['posixGroup'])){
2438 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2439 $checks['posixGroup']['STATUS'] = FALSE;
2440 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2441 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2442 }
2443 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2444 $checks['posixGroup']['STATUS'] = FALSE;
2445 $checks['posixGroup']['MSG'] = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2446 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2447 }
2448 }
2450 return($checks);
2451 }
2454 function prepare4mailbody($string)
2455 {
2456 $string = html_entity_decode($string);
2458 $from = array(
2459 "/%/",
2460 "/ /",
2461 "/\n/",
2462 "/\r/",
2463 "/!/",
2464 "/#/",
2465 "/\*/",
2466 "/\//",
2467 "/</",
2468 "/>/",
2469 "/\?/",
2470 "/\"/");
2472 $to = array(
2473 "%25",
2474 "%20",
2475 "%0A",
2476 "%0D",
2477 "%21",
2478 "%23",
2479 "%2A",
2480 "%2F",
2481 "%3C",
2482 "%3E",
2483 "%3F",
2484 "%22");
2486 $string = preg_replace($from,$to,$string);
2488 return($string);
2489 }
2492 function mac2company($mac)
2493 {
2494 $vendor= "";
2496 /* Generate a normailzed mac... */
2497 $mac= substr(preg_replace('/[:-]/', '', $mac), 0, 6);
2499 /* Check for existance of the oui file */
2500 if (!is_readable(CONFIG_DIR."/oui.txt")){
2501 return ("");
2502 }
2504 /* Open file and look for mac addresses... */
2505 $handle = @fopen(CONFIG_DIR."/oui.txt", "r");
2506 if ($handle) {
2507 while (!feof($handle)) {
2508 $line = fgets($handle, 4096);
2510 if (preg_match("/^$mac/i", $line)){
2511 $vendor= substr($line, 32);
2512 }
2513 }
2514 fclose($handle);
2515 }
2517 return ($vendor);
2518 }
2521 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2522 ?>