e3254ed350608a960fe680f3845b36bf2da280fd
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_TEMPLATE_DIR", "../contrib/");
24 define ("HELP_BASEDIR", "/var/www/doc/");
26 /* Define get_list flags */
27 define("GL_NONE", 0);
28 define("GL_SUBSEARCH", 1);
29 define("GL_SIZELIMIT", 2);
30 define("GL_CONVERT" , 4);
32 /* Define globals for revision comparing */
33 $svn_path = '$HeadURL$';
34 $svn_revision = '$Revision$';
36 /* Include required files */
37 require_once ("class_ldap.inc");
38 require_once ("class_config.inc");
39 require_once ("class_plugin.inc");
40 require_once ("class_acl.inc");
41 require_once ("class_pluglist.inc");
42 require_once ("class_userinfo.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 return (strtolower($lang)."_".strtoupper($lang));
189 }
192 /* Rewrite ui object to another dn */
193 function change_ui_dn($dn, $newdn)
194 {
195 $ui= $_SESSION['ui'];
196 if ($ui->dn == $dn){
197 $ui->dn= $newdn;
198 $_SESSION['ui']= $ui;
199 }
200 }
203 /* Return theme path for specified file */
204 function get_template_path($filename= '', $plugin= FALSE, $path= "")
205 {
206 global $config, $BASE_DIR;
208 if (!@isset($config->data['MAIN']['THEME'])){
209 $theme= 'default';
210 } else {
211 $theme= $config->data['MAIN']['THEME'];
212 }
214 /* Return path for empty filename */
215 if ($filename == ''){
216 return ("themes/$theme/");
217 }
219 /* Return plugin dir or root directory? */
220 if ($plugin){
221 if ($path == ""){
222 $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
223 } else {
224 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
225 }
226 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
227 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
228 }
229 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
230 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
231 }
232 if ($path == ""){
233 return ($_SESSION['plugin_dir']."/$filename");
234 } else {
235 return ($path."/$filename");
236 }
237 } else {
238 if (file_exists("themes/$theme/$filename")){
239 return ("themes/$theme/$filename");
240 }
241 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
242 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
243 }
244 if (file_exists("themes/default/$filename")){
245 return ("themes/default/$filename");
246 }
247 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
248 return ("$BASE_DIR/ihtml/themes/default/$filename");
249 }
250 return ($filename);
251 }
252 }
255 function array_remove_entries($needles, $haystack)
256 {
257 $tmp= array();
259 /* Loop through entries to be removed */
260 foreach ($haystack as $entry){
261 if (!in_array($entry, $needles)){
262 $tmp[]= $entry;
263 }
264 }
266 return ($tmp);
267 }
270 function gosa_log ($message)
271 {
272 global $ui;
274 /* Preset to something reasonable */
275 $username= " unauthenticated";
277 /* Replace username if object is present */
278 if (isset($ui)){
279 if ($ui->username != ""){
280 $username= "[$ui->username]";
281 } else {
282 $username= "unknown";
283 }
284 }
286 syslog(LOG_INFO,"GOsa$username: $message");
287 }
290 function ldap_init ($server, $base, $binddn='', $pass='')
291 {
292 global $config;
294 $ldap = new LDAP ($binddn, $pass, $server, isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
295 isset($config->current['TLS']) && $config->current['TLS'] == "true");
297 /* Sadly we've no proper return values here. Use the error message instead. */
298 if (!preg_match("/Success/i", $ldap->error)){
299 echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
300 exit();
301 }
303 /* Preset connection base to $base and return to caller */
304 $ldap->cd ($base);
305 return $ldap;
306 }
309 function ldap_login_user ($username, $password)
310 {
311 global $config;
313 /* look through the entire ldap */
314 $ldap = $config->get_ldap_link();
315 if (!preg_match("/Success/i", $ldap->error)){
316 print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
317 $smarty= get_smarty();
318 $smarty->display(get_template_path('headers.tpl'));
319 echo "<body>".$_SESSION['errors']."</body></html>";
320 exit();
321 }
322 $ldap->cd($config->current['BASE']);
323 $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
325 /* get results, only a count of 1 is valid */
326 switch ($ldap->count()){
328 /* user not found */
329 case 0: return (NULL);
331 /* valid uniq user */
332 case 1:
333 break;
335 /* found more than one matching id */
336 default:
337 print_red(_("Username / UID is not unique. Please check your LDAP database."));
338 return (NULL);
339 }
341 /* LDAP schema is not case sensitive. Perform additional check. */
342 $attrs= $ldap->fetch();
343 if ($attrs['uid'][0] != $username){
344 return(NULL);
345 }
347 /* got user dn, fill acl's */
348 $ui= new userinfo($config, $ldap->getDN());
349 $ui->username= $username;
351 /* password check, bind as user with supplied password */
352 $ldap->disconnect();
353 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
354 isset($config->current['RECURSIVE']) &&
355 $config->current['RECURSIVE'] == "true",
356 isset($config->current['TLS'])
357 && $config->current['TLS'] == "true");
358 if (!preg_match("/Success/i", $ldap->error)){
359 return (NULL);
360 }
362 /* Username is set, load subtreeACL's now */
363 $ui->loadACL();
365 return ($ui);
366 }
369 function ldap_expired_account($config, $userdn, $username)
370 {
371 $ldap= $config->get_ldap_link();
372 $ldap->cat($userdn);
373 $attrs= $ldap->fetch();
375 /* default value no errors */
376 $expired = 0;
378 $sExpire = 0;
379 $sLastChange = 0;
380 $sMax = 0;
381 $sMin = 0;
382 $sInactive = 0;
383 $sWarning = 0;
385 $current= date("U");
387 $current= floor($current /60 /60 /24);
389 /* special case of the admin, should never been locked */
390 /* FIXME should allow any name as user admin */
391 if($username != "admin")
392 {
394 if(isset($attrs['shadowExpire'][0])){
395 $sExpire= $attrs['shadowExpire'][0];
396 } else {
397 $sExpire = 0;
398 }
400 if(isset($attrs['shadowLastChange'][0])){
401 $sLastChange= $attrs['shadowLastChange'][0];
402 } else {
403 $sLastChange = 0;
404 }
406 if(isset($attrs['shadowMax'][0])){
407 $sMax= $attrs['shadowMax'][0];
408 } else {
409 $smax = 0;
410 }
412 if(isset($attrs['shadowMin'][0])){
413 $sMin= $attrs['shadowMin'][0];
414 } else {
415 $sMin = 0;
416 }
418 if(isset($attrs['shadowInactive'][0])){
419 $sInactive= $attrs['shadowInactive'][0];
420 } else {
421 $sInactive = 0;
422 }
424 if(isset($attrs['shadowWarning'][0])){
425 $sWarning= $attrs['shadowWarning'][0];
426 } else {
427 $sWarning = 0;
428 }
430 /* is the account locked */
431 /* shadowExpire + shadowInactive (option) */
432 if($sExpire >0){
433 if($current >= ($sExpire+$sInactive)){
434 return(1);
435 }
436 }
438 /* the user should be warned to change is password */
439 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
440 if (($sExpire - $current) < $sWarning){
441 return(2);
442 }
443 }
445 /* force user to change password */
446 if(($sLastChange >0) && ($sMax) >0){
447 if($current >= ($sLastChange+$sMax)){
448 return(3);
449 }
450 }
452 /* the user should not be able to change is password */
453 if(($sLastChange >0) && ($sMin >0)){
454 if (($sLastChange + $sMin) >= $current){
455 return(4);
456 }
457 }
458 }
459 return($expired);
460 }
462 function add_lock ($object, $user)
463 {
464 global $config;
466 /* Just a sanity check... */
467 if ($object == "" || $user == ""){
468 print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
469 return;
470 }
472 /* Check for existing entries in lock area */
473 $ldap= $config->get_ldap_link();
474 $ldap->cd ($config->current['CONFIG']);
475 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
476 array("gosaUser"));
477 if (!preg_match("/Success/i", $ldap->error)){
478 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()));
479 return;
480 }
482 /* Add lock if none present */
483 if ($ldap->count() == 0){
484 $attrs= array();
485 $name= md5($object);
486 $ldap->cd("cn=$name,".$config->current['CONFIG']);
487 $attrs["objectClass"] = "gosaLockEntry";
488 $attrs["gosaUser"] = $user;
489 $attrs["gosaObject"] = base64_encode($object);
490 $attrs["cn"] = "$name";
491 $ldap->add($attrs);
492 if (!preg_match("/Success/i", $ldap->error)){
493 print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
494 $ldap->get_error()));
495 return;
496 }
497 }
498 }
501 function del_lock ($object)
502 {
503 global $config;
505 /* Sanity check */
506 if ($object == ""){
507 return;
508 }
510 /* Check for existance and remove the entry */
511 $ldap= $config->get_ldap_link();
512 $ldap->cd ($config->current['CONFIG']);
513 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
514 $attrs= $ldap->fetch();
515 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
516 $ldap->rmdir ($ldap->getDN());
518 if (!preg_match("/Success/i", $ldap->error)){
519 print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
520 $ldap->get_error()));
521 return;
522 }
523 }
524 }
527 function del_user_locks($userdn)
528 {
529 global $config;
531 /* Get LDAP ressources */
532 $ldap= $config->get_ldap_link();
533 $ldap->cd ($config->current['CONFIG']);
535 /* Remove all objects of this user, drop errors silently in this case. */
536 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
537 while ($attrs= $ldap->fetch()){
538 $ldap->rmdir($attrs['dn']);
539 }
540 }
543 function get_lock ($object)
544 {
545 global $config;
547 /* Sanity check */
548 if ($object == ""){
549 print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
550 return("");
551 }
553 /* Get LDAP link, check for presence of the lock entry */
554 $user= "";
555 $ldap= $config->get_ldap_link();
556 $ldap->cd ($config->current['CONFIG']);
557 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
558 if (!preg_match("/Success/i", $ldap->error)){
559 print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
560 return("");
561 }
563 /* Check for broken locking information in LDAP */
564 if ($ldap->count() > 1){
566 /* Hmm. We're removing broken LDAP information here and issue a warning. */
567 print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
569 /* Clean up these references now... */
570 while ($attrs= $ldap->fetch()){
571 $ldap->rmdir($attrs['dn']);
572 }
574 return("");
576 } elseif ($ldap->count() == 1){
577 $attrs = $ldap->fetch();
578 $user= $attrs['gosaUser'][0];
579 }
581 return ($user);
582 }
585 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
586 {
587 global $config, $ui;
589 /* Get LDAP link */
590 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
592 /* Set search base to configured base if $base is empty */
593 if ($base == ""){
594 $ldap->cd ($config->current['BASE']);
595 } else {
596 $ldap->cd ($base);
597 }
599 /* Perform ONE or SUB scope searches? */
600 if ($flags & GL_SUBSEARCH) {
601 $ldap->search ($filter, $attributes);
602 } else {
603 $ldap->ls ($filter,$base,$attributes);
604 }
606 /* Check for size limit exceeded messages for GUI feedback */
607 if (preg_match("/size limit/i", $ldap->error)){
608 $_SESSION['limit_exceeded']= TRUE;
609 }
611 /* Crawl through reslut entries and perform the migration to the
612 result array */
613 $result= array();
615 while($attrs = $ldap->fetch()) {
616 $dn= $ldap->getDN();
618 /* Sort in every value that fits the permissions */
619 if (is_array($category)){
620 foreach ($category as $o){
621 if ($ui->get_category_permissions($dn, $o) != ""){
622 if ($flags & GL_CONVERT){
623 $attrs["dn"]= convert_department_dn($dn);
624 } else {
625 $attrs["dn"]= $dn;
626 }
628 /* We found what we were looking for, break speeds things up */
629 $result[]= $attrs;
630 }
631 }
632 } else {
633 if ($ui->get_category_permissions($dn, $category) != ""){
634 if ($flags & GL_CONVERT){
635 $attrs["dn"]= convert_department_dn($dn);
636 } else {
637 $attrs["dn"]= $dn;
638 }
640 /* We found what we were looking for, break speeds things up */
641 $result[]= $attrs;
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 }
738 function get_permissions ($dn, $subtreeACL)
739 {
740 global $config;
741 echo "get_permissions() - to be removed<br>";
743 $base= $config->current['BASE'];
744 $tmp= "d,".$dn;
745 $sacl= array();
747 /* Sort subacl's for lenght to simplify matching
748 for subtrees */
749 foreach ($subtreeACL as $key => $value){
750 $sacl[$key]= strlen($key);
751 }
752 arsort ($sacl);
753 reset ($sacl);
755 /* Successively remove leading parts of the dn's until
756 it doesn't contain commas anymore */
757 $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
758 while (preg_match('/,/', $tmp_dn)){
759 $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
760 $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
762 /* Check for acl that may apply */
763 foreach ($sacl as $key => $value){
764 if (preg_match("/$key$/", $tmp)){
765 return ($subtreeACL[$key]);
766 }
767 }
768 }
770 return array("");
771 }
774 function get_module_permission($acl_array, $module, $dn)
775 {
776 global $ui;
777 echo "get_module_permissions() - to be removed<br>";
779 $final= "";
780 foreach($acl_array as $acl){
782 /* Check for selfflag (!) in ACL to determine if
783 the user is allowed to change parts of his/her
784 own account */
785 if (preg_match("/^!/", $acl)){
786 if ($dn != "" && $dn != $ui->dn){
788 /* No match for own DN, give up on this ACL */
789 continue;
791 } else {
793 /* Matches own DN, remove the selfflag */
794 $acl= preg_replace("/^!/", "", $acl);
796 }
797 }
799 /* Remove leading garbage */
800 $acl= preg_replace("/^:/", "", $acl);
802 /* Discover if we've access to the submodule by comparing
803 all allowed submodules specified in the ACL */
804 $tmp= split(",", $acl);
805 foreach ($tmp as $mod){
806 if (preg_match("/^$module#/", $mod)){
807 $final= strstr($mod, "#")."#";
808 continue;
809 }
810 if (preg_match("/[^#]$module$/", $mod)){
811 return ("#all#");
812 }
813 if (preg_match("/^all$/", $mod)){
814 return ("#all#");
815 }
816 }
817 }
819 /* Return assembled ACL, or none */
820 if ($final != ""){
821 return (preg_replace('/##/', '#', $final));
822 }
824 /* Nothing matches - disable access for this object */
825 return ("#none#");
826 }
829 function get_userinfo()
830 {
831 global $ui;
833 return $ui;
834 }
837 function get_smarty()
838 {
839 global $smarty;
841 return $smarty;
842 }
845 function convert_department_dn($dn)
846 {
847 $dep= "";
849 /* Build a sub-directory style list of the tree level
850 specified in $dn */
851 foreach (split(',', $dn) as $rdn){
853 /* We're only interested in organizational units... */
854 if (substr($rdn,0,3) == 'ou='){
855 $dep= substr($rdn,3)."/$dep";
856 }
858 /* ... and location objects */
859 if (substr($rdn,0,2) == 'l='){
860 $dep= substr($rdn,2)."/$dep";
861 }
862 }
864 /* Return and remove accidently trailing slashes */
865 return rtrim($dep, "/");
866 }
869 /* Strip off the last sub department part of a '/level1/level2/.../'
870 * style value. It removes the trailing '/', too. */
871 function get_sub_department($value)
872 {
873 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
874 }
877 function get_ou($name)
878 {
879 global $config;
881 /* Preset ou... */
882 if (isset($config->current[$name])){
883 $ou= $config->current[$name];
884 } else {
885 return "";
886 }
888 if ($ou != ""){
889 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
890 return @LDAP::convert("ou=$ou,");
891 } else {
892 return @LDAP::convert("$ou,");
893 }
894 } else {
895 return "";
896 }
897 }
900 function get_people_ou()
901 {
902 return (get_ou("PEOPLE"));
903 }
906 function get_groups_ou()
907 {
908 return (get_ou("GROUPS"));
909 }
912 function get_winstations_ou()
913 {
914 return (get_ou("WINSTATIONS"));
915 }
918 function get_base_from_people($dn)
919 {
920 global $config;
922 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
923 $base= preg_replace($pattern, '', $dn);
925 /* Set to base, if we're not on a correct subtree */
926 if (!isset($config->idepartments[$base])){
927 $base= $config->current['BASE'];
928 }
930 return ($base);
931 }
934 function chkacl($acl, $name)
935 {
936 echo "chkacl - to be removed<br>";
937 /* Look for attribute in ACL */
938 if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
939 return ("");
940 }
942 /* Optically disable html object for no match */
943 return (" disabled ");
944 }
947 function is_phone_nr($nr)
948 {
949 if ($nr == ""){
950 return (TRUE);
951 }
953 return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
954 }
957 function is_url($url)
958 {
959 if ($url == ""){
960 return (TRUE);
961 }
963 return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
964 }
967 function is_dn($dn)
968 {
969 if ($dn == ""){
970 return (TRUE);
971 }
973 return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
974 }
977 function is_uid($uid)
978 {
979 global $config;
981 if ($uid == ""){
982 return (TRUE);
983 }
985 /* STRICT adds spaces and case insenstivity to the uid check.
986 This is dangerous and should not be used. */
987 if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
988 return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
989 } else {
990 return preg_match ("/^[a-z0-9_-]+$/", $uid);
991 }
992 }
995 function is_ip($ip)
996 {
997 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);
998 }
1000 /* Checks if the given ip address dosen't match
1001 "is_ip" because there is also a sub net mask given */
1002 function is_ip_with_subnetmask($ip)
1003 {
1004 /* Generate list of valid submasks */
1005 $res = array();
1006 for($e = 0 ; $e <= 32; $e++){
1007 $res[$e] = $e;
1008 }
1009 $i[0] =255;
1010 $i[1] =255;
1011 $i[2] =255;
1012 $i[3] =255;
1013 for($a= 3 ; $a >= 0 ; $a --){
1014 $c = 1;
1015 while($i[$a] > 0 ){
1016 $str = $i[0].".".$i[1].".".$i[2].".".$i[3];
1017 $res[$str] = $str;
1018 $i[$a] -=$c;
1019 $c = 2*$c;
1020 }
1021 }
1022 $res["0.0.0.0"] = "0.0.0.0";
1023 if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1024 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1025 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1026 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
1027 $mask = preg_replace("/^(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]?)\.".
1030 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1032 $mask = preg_replace("/^\//","",$mask);
1033 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1034 return(TRUE);
1035 }
1036 }
1037 return(FALSE);
1038 }
1040 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1041 function is_domain($str)
1042 {
1043 return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1044 }
1048 function is_id($id)
1049 {
1050 if ($id == ""){
1051 return (FALSE);
1052 }
1054 return preg_match ("/^[0-9]+$/", $id);
1055 }
1058 function is_path($path)
1059 {
1060 if ($path == ""){
1061 return (TRUE);
1062 }
1063 if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1064 return (FALSE);
1065 }
1067 return preg_match ("/\/.+$/", $path);
1068 }
1071 function is_email($address, $template= FALSE)
1072 {
1073 if ($address == ""){
1074 return (TRUE);
1075 }
1076 if ($template){
1077 return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1078 $address);
1079 } else {
1080 return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1081 $address);
1082 }
1083 }
1086 function print_red()
1087 {
1088 /* Check number of arguments */
1089 if (func_num_args() < 1){
1090 return;
1091 }
1093 /* Get arguments, save string */
1094 $array = func_get_args();
1095 $string= $array[0];
1097 /* Step through arguments */
1098 for ($i= 1; $i<count($array); $i++){
1099 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1100 }
1102 if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1103 $_SESSION['errorsAlreadyPosted'] = array();
1104 }
1106 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1107 the other case... */
1109 if (isset($_SESSION['DEBUGLEVEL'])){
1111 if($_SESSION['LastError'] == $string){
1113 if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1114 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1115 }
1116 $_SESSION['errorsAlreadyPosted'][$string]++;
1118 }else{
1119 if($string != NULL){
1120 if (preg_match("/"._("LDAP error:")."/", $string)){
1121 $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.");
1122 $img= "images/error.png";
1123 } else {
1124 if (!preg_match('/[.!?]$/', $string)){
1125 $string.= ".";
1126 }
1127 $string= preg_replace('/<br>/', ' ', $string);
1128 $img= "images/warning.png";
1129 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1130 }
1132 if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1133 $_SESSION['errors'].= "<div style='margin-left:15%;margin-top:100px;".
1134 "background-color:white;padding:5px;border:5px solid red;width:55%;z-index:150;".
1135 "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1136 "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1137 get_template_path($img)."'></td>".
1138 "<td style='width:100%'><h1>"._("An error occured while processing your request").
1139 "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1140 (($_SESSION['js']==FALSE)?"type='submit'":"type='button'").
1141 " style='width:80px' onClick='hide(\"e_layer\")'>".
1142 _("OK")."</button></td></tr></table></div>";
1143 }
1145 }else{
1146 return;
1147 }
1148 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1150 }
1152 } else {
1153 echo "Error: $string\n";
1154 }
1155 $_SESSION['LastError'] = $string;
1156 }
1159 function gen_locked_message($user, $dn)
1160 {
1161 global $plug, $config;
1163 $_SESSION['dn']= $dn;
1164 $ldap= $config->get_ldap_link();
1165 $ldap->cat ($user, array('uid', 'cn'));
1166 $attrs= $ldap->fetch();
1168 /* Stop if we have no user here... */
1169 if (count($attrs)){
1170 $uid= $attrs["uid"][0];
1171 $cn= $attrs["cn"][0];
1172 } else {
1173 $uid= $attrs["uid"][0];
1174 $cn= $attrs["cn"][0];
1175 }
1177 $remove= false;
1179 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1180 if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1181 $_SESSION['LOCK_VARS_USED'] =array();
1182 foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1184 if(empty($name)) continue;
1185 foreach($_POST as $Pname => $Pvalue){
1186 if(preg_match($name,$Pname)){
1187 $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1188 }
1189 }
1191 foreach($_GET as $Pname => $Pvalue){
1192 if(preg_match($name,$Pname)){
1193 $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1194 }
1195 }
1196 }
1197 $_SESSION['LOCK_VARS_TO_USE'] =array();
1198 }
1200 /* Prepare and show template */
1201 $smarty= get_smarty();
1202 $smarty->assign ("dn", $dn);
1203 if ($remove){
1204 $smarty->assign ("action", _("Continue anyway"));
1205 } else {
1206 $smarty->assign ("action", _("Edit anyway"));
1207 }
1208 $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>"));
1210 return ($smarty->fetch (get_template_path('islocked.tpl')));
1211 }
1214 function to_string ($value)
1215 {
1216 /* If this is an array, generate a text blob */
1217 if (is_array($value)){
1218 $ret= "";
1219 foreach ($value as $line){
1220 $ret.= $line."<br>\n";
1221 }
1222 return ($ret);
1223 } else {
1224 return ($value);
1225 }
1226 }
1229 function get_printer_list($cups_server)
1230 {
1231 global $config;
1233 $res= array();
1235 /* Use CUPS, if we've access to it */
1236 if (function_exists('cups_get_dest_list')){
1237 $dest_list= cups_get_dest_list ($cups_server);
1239 foreach ($dest_list as $prt){
1240 $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1242 foreach ($attr as $prt_info){
1243 if ($prt_info->name == "printer-info"){
1244 $info= $prt_info->value;
1245 break;
1246 }
1247 }
1248 $res[$prt->name]= "$info [$prt->name]";
1249 }
1251 /* CUPS is not available, try lpstat as a replacement */
1252 } else {
1253 $ar = false;
1254 exec("lpstat -p", $ar);
1255 foreach($ar as $val){
1256 @list($dummy, $printer, $rest)= split(' ', $val, 3);
1257 if (preg_match('/^[^@]+$/', $printer)){
1258 $res[$printer]= "$printer";
1259 }
1260 }
1261 }
1263 /* Merge in printers from LDAP */
1264 $ldap= $config->get_ldap_link();
1265 $ldap->cd ($config->current['BASE']);
1266 $ui= get_userinfo();
1267 if (preg_match('/TRUE/i', $config->current['STRICT_UNITS']) && $ui->gosaUnitTag != ""){
1268 $ldap->search('((objectClass=gotoPrinter)(gosaUnitTag='.$ui->gosaUnitTag.'))', array('cn'));
1269 } else {
1270 $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1271 }
1273 return $res;
1274 }
1277 function sess_del ($var)
1278 {
1279 /* New style */
1280 unset ($_SESSION[$var]);
1282 /* ... work around, since the first one
1283 doesn't seem to work all the time */
1284 session_unregister ($var);
1285 }
1288 function show_errors($message)
1289 {
1290 $complete= "";
1292 /* Assemble the message array to a plain string */
1293 foreach ($message as $error){
1294 if ($complete == ""){
1295 $complete= $error;
1296 } else {
1297 $complete= "$error<br>$complete";
1298 }
1299 }
1301 /* Fill ERROR variable with nice error dialog */
1302 print_red($complete);
1303 }
1306 function show_ldap_error($message, $addon= "")
1307 {
1308 if (!preg_match("/Success/i", $message)){
1309 if ($addon == ""){
1310 print_red (_("LDAP error: $message"));
1311 } else {
1312 print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1313 }
1314 return TRUE;
1315 } else {
1316 return FALSE;
1317 }
1318 }
1321 function rewrite($s)
1322 {
1323 global $REWRITE;
1325 foreach ($REWRITE as $key => $val){
1326 $s= preg_replace("/$key/", "$val", $s);
1327 }
1329 return ($s);
1330 }
1333 function dn2base($dn)
1334 {
1335 global $config;
1337 if (get_people_ou() != ""){
1338 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1339 }
1340 if (get_groups_ou() != ""){
1341 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1342 }
1343 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1345 return ($base);
1346 }
1350 function check_command($cmdline)
1351 {
1352 $cmd= preg_replace("/ .*$/", "", $cmdline);
1354 /* Check if command exists in filesystem */
1355 if (!file_exists($cmd)){
1356 return (FALSE);
1357 }
1359 /* Check if command is executable */
1360 if (!is_executable($cmd)){
1361 return (FALSE);
1362 }
1364 return (TRUE);
1365 }
1368 function print_header($image, $headline, $info= "")
1369 {
1370 $display= "<div class=\"plugtop\">\n";
1371 $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";
1372 $display.= "</div>\n";
1374 if ($info != ""){
1375 $display.= "<div class=\"pluginfo\">\n";
1376 $display.= "$info";
1377 $display.= "</div>\n";
1378 } else {
1379 $display.= "<div style=\"height:5px;\">\n";
1380 $display.= " ";
1381 $display.= "</div>\n";
1382 }
1383 if (isset($_SESSION['errors'])){
1384 $display.= $_SESSION['errors'];
1385 }
1387 return ($display);
1388 }
1391 function register_global($name, $object)
1392 {
1393 $_SESSION[$name]= $object;
1394 }
1397 function is_global($name)
1398 {
1399 return isset($_SESSION[$name]);
1400 }
1403 function get_global($name)
1404 {
1405 return $_SESSION[$name];
1406 }
1409 function range_selector($dcnt,$start,$range=25,$post_var=false)
1410 {
1412 /* Entries shown left and right from the selected entry */
1413 $max_entries= 10;
1415 /* Initialize and take care that max_entries is even */
1416 $output="";
1417 if ($max_entries & 1){
1418 $max_entries++;
1419 }
1421 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1422 $range= $_POST[$post_var];
1423 }
1425 /* Prevent output to start or end out of range */
1426 if ($start < 0 ){
1427 $start= 0 ;
1428 }
1429 if ($start >= $dcnt){
1430 $start= $range * (int)(($dcnt / $range) + 0.5);
1431 }
1433 $numpages= (($dcnt / $range));
1434 if(((int)($numpages))!=($numpages)){
1435 $numpages = (int)$numpages + 1;
1436 }
1437 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1438 return ("");
1439 }
1440 $ppage= (int)(($start / $range) + 0.5);
1443 /* Align selected page to +/- max_entries/2 */
1444 $begin= $ppage - $max_entries/2;
1445 $end= $ppage + $max_entries/2;
1447 /* Adjust begin/end, so that the selected value is somewhere in
1448 the middle and the size is max_entries if possible */
1449 if ($begin < 0){
1450 $end-= $begin + 1;
1451 $begin= 0;
1452 }
1453 if ($end > $numpages) {
1454 $end= $numpages;
1455 }
1456 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1457 $begin= $end - $max_entries;
1458 }
1460 if($post_var){
1461 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1462 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1463 }else{
1464 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1465 }
1467 /* Draw decrement */
1468 if ($start > 0 ) {
1469 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1470 (($start-$range))."\">".
1471 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1472 }
1474 /* Draw pages */
1475 for ($i= $begin; $i < $end; $i++) {
1476 if ($ppage == $i){
1477 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1478 validate($_GET['plug'])."&start=".
1479 ($i*$range)."\"> ".($i+1)." </a>";
1480 } else {
1481 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1482 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1483 }
1484 }
1486 /* Draw increment */
1487 if($start < ($dcnt-$range)) {
1488 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1489 (($start+($range)))."\">".
1490 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1491 }
1493 if(($post_var)&&($numpages)){
1494 $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()'>";
1495 foreach(array(20,50,100,200,"all") as $num){
1496 if($num == "all"){
1497 $var = 10000;
1498 }else{
1499 $var = $num;
1500 }
1501 if($var == $range){
1502 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1503 }else{
1504 $output.="\n<option value='".$var."'>".$num."</option>";
1505 }
1506 }
1507 $output.= "</select></td></tr></table></div>";
1508 }else{
1509 $output.= "</div>";
1510 }
1512 return($output);
1513 }
1516 function apply_filter()
1517 {
1518 $apply= "";
1520 $apply= ''.
1521 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1522 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1524 return ($apply);
1525 }
1528 function back_to_main()
1529 {
1530 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1531 _("Back").'"></p><input type="hidden" name="ignore">';
1533 return ($string);
1534 }
1537 function normalize_netmask($netmask)
1538 {
1539 /* Check for notation of netmask */
1540 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1541 $num= (int)($netmask);
1542 $netmask= "";
1544 for ($byte= 0; $byte<4; $byte++){
1545 $result=0;
1547 for ($i= 7; $i>=0; $i--){
1548 if ($num-- > 0){
1549 $result+= pow(2,$i);
1550 }
1551 }
1553 $netmask.= $result.".";
1554 }
1556 return (preg_replace('/\.$/', '', $netmask));
1557 }
1559 return ($netmask);
1560 }
1563 function netmask_to_bits($netmask)
1564 {
1565 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1566 $res= 0;
1568 for ($n= 0; $n<4; $n++){
1569 $start= 255;
1570 $name= "nm$n";
1572 for ($i= 0; $i<8; $i++){
1573 if ($start == (int)($$name)){
1574 $res+= 8 - $i;
1575 break;
1576 }
1577 $start-= pow(2,$i);
1578 }
1579 }
1581 return ($res);
1582 }
1585 function recurse($rule, $variables)
1586 {
1587 $result= array();
1589 if (!count($variables)){
1590 return array($rule);
1591 }
1593 reset($variables);
1594 $key= key($variables);
1595 $val= current($variables);
1596 unset ($variables[$key]);
1598 foreach($val as $possibility){
1599 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1600 $result= array_merge($result, recurse($nrule, $variables));
1601 }
1603 return ($result);
1604 }
1607 function expand_id($rule, $attributes)
1608 {
1609 /* Check for id rule */
1610 if(preg_match('/^id(:|#)\d+$/',$rule)){
1611 return (array("\{$rule}"));
1612 }
1614 /* Check for clean attribute */
1615 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1616 $rule= preg_replace('/^%/', '', $rule);
1617 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1618 return (array($val));
1619 }
1621 /* Check for attribute with parameters */
1622 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1623 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1624 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1625 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1626 $start= preg_replace ('/-.*$/', '', $param);
1627 $stop = preg_replace ('/^[^-]+-/', '', $param);
1629 /* Assemble results */
1630 $result= array();
1631 for ($i= $start; $i<= $stop; $i++){
1632 $result[]= substr($val, 0, $i);
1633 }
1634 return ($result);
1635 }
1637 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1638 return (array($rule));
1639 }
1642 function gen_uids($rule, $attributes)
1643 {
1644 global $config;
1646 /* Search for keys and fill the variables array with all
1647 possible values for that key. */
1648 $part= "";
1649 $trigger= false;
1650 $stripped= "";
1651 $variables= array();
1653 for ($pos= 0; $pos < strlen($rule); $pos++){
1655 if ($rule[$pos] == "{" ){
1656 $trigger= true;
1657 $part= "";
1658 continue;
1659 }
1661 if ($rule[$pos] == "}" ){
1662 $variables[$pos]= expand_id($part, $attributes);
1663 $stripped.= "\{$pos}";
1664 $trigger= false;
1665 continue;
1666 }
1668 if ($trigger){
1669 $part.= $rule[$pos];
1670 } else {
1671 $stripped.= $rule[$pos];
1672 }
1673 }
1675 /* Recurse through all possible combinations */
1676 $proposed= recurse($stripped, $variables);
1678 /* Get list of used ID's */
1679 $used= array();
1680 $ldap= $config->get_ldap_link();
1681 $ldap->cd($config->current['BASE']);
1682 $ldap->search('(uid=*)');
1684 while($attrs= $ldap->fetch()){
1685 $used[]= $attrs['uid'][0];
1686 }
1688 /* Remove used uids and watch out for id tags */
1689 $ret= array();
1690 foreach($proposed as $uid){
1692 /* Check for id tag and modify uid if needed */
1693 if(preg_match('/\{id:\d+}/',$uid)){
1694 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1696 for ($i= 0; $i < pow(10,$size); $i++){
1697 $number= sprintf("%0".$size."d", $i);
1698 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1699 if (!in_array($res, $used)){
1700 $uid= $res;
1701 break;
1702 }
1703 }
1704 }
1706 if(preg_match('/\{id#\d+}/',$uid)){
1707 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1709 while (true){
1710 mt_srand((double) microtime()*1000000);
1711 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1712 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1713 if (!in_array($res, $used)){
1714 $uid= $res;
1715 break;
1716 }
1717 }
1718 }
1720 /* Don't assign used ones */
1721 if (!in_array($uid, $used)){
1722 $ret[]= $uid;
1723 }
1724 }
1726 return(array_unique($ret));
1727 }
1730 function array_search_r($needle, $key, $haystack){
1732 foreach($haystack as $index => $value){
1733 $match= 0;
1735 if (is_array($value)){
1736 $match= array_search_r($needle, $key, $value);
1737 }
1739 if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1740 $match=1;
1741 }
1743 if ($match){
1744 return 1;
1745 }
1746 }
1748 return 0;
1749 }
1752 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1753 Need to convert... */
1754 function to_byte($value) {
1755 $value= strtolower(trim($value));
1757 if(!is_numeric(substr($value, -1))) {
1759 switch(substr($value, -1)) {
1760 case 'g':
1761 $mult= 1073741824;
1762 break;
1763 case 'm':
1764 $mult= 1048576;
1765 break;
1766 case 'k':
1767 $mult= 1024;
1768 break;
1769 }
1771 return ($mult * (int)substr($value, 0, -1));
1772 } else {
1773 return $value;
1774 }
1775 }
1778 function in_array_ics($value, $items)
1779 {
1780 if (!is_array($items)){
1781 return (FALSE);
1782 }
1784 foreach ($items as $item){
1785 if (strtolower($item) == strtolower($value)) {
1786 return (TRUE);
1787 }
1788 }
1790 return (FALSE);
1791 }
1794 function generate_alphabet($count= 10)
1795 {
1796 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1797 $alphabet= "";
1798 $c= 0;
1800 /* Fill cells with charaters */
1801 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1802 if ($c == 0){
1803 $alphabet.= "<tr>";
1804 }
1806 $ch = mb_substr($characters, $i, 1, "UTF8");
1807 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1808 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1810 if ($c++ == $count){
1811 $alphabet.= "</tr>";
1812 $c= 0;
1813 }
1814 }
1816 /* Fill remaining cells */
1817 while ($c++ <= $count){
1818 $alphabet.= "<td> </td>";
1819 }
1821 return ($alphabet);
1822 }
1825 function validate($string)
1826 {
1827 return (strip_tags(preg_replace('/\0/', '', $string)));
1828 }
1830 function get_gosa_version()
1831 {
1832 global $svn_revision, $svn_path;
1834 /* Extract informations */
1835 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1837 /* Release or development? */
1838 if (preg_match('%/gosa/trunk/%', $svn_path)){
1839 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1840 } else {
1841 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1842 return (sprintf(_("GOsa $release"), $revision));
1843 }
1844 }
1847 function rmdirRecursive($path, $followLinks=false) {
1848 $dir= opendir($path);
1849 while($entry= readdir($dir)) {
1850 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1851 unlink($path."/".$entry);
1852 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1853 rmdirRecursive($path."/".$entry);
1854 }
1855 }
1856 closedir($dir);
1857 return rmdir($path);
1858 }
1860 function scan_directory($path,$sort_desc=false)
1861 {
1862 $ret = false;
1864 /* is this a dir ? */
1865 if(is_dir($path)) {
1867 /* is this path a readable one */
1868 if(is_readable($path)){
1870 /* Get contents and write it into an array */
1871 $ret = array();
1873 $dir = opendir($path);
1875 /* Is this a correct result ?*/
1876 if($dir){
1877 while($fp = readdir($dir))
1878 $ret[]= $fp;
1879 }
1880 }
1881 }
1882 /* Sort array ascending , like scandir */
1883 sort($ret);
1885 /* Sort descending if parameter is sort_desc is set */
1886 if($sort_desc) {
1887 $ret = array_reverse($ret);
1888 }
1890 return($ret);
1891 }
1893 function clean_smarty_compile_dir($directory)
1894 {
1895 global $svn_revision;
1897 if(is_dir($directory) && is_readable($directory)) {
1898 // Set revision filename to REVISION
1899 $revision_file= $directory."/REVISION";
1901 /* Is there a stamp containing the current revision? */
1902 if(!file_exists($revision_file)) {
1903 // create revision file
1904 create_revision($revision_file, $svn_revision);
1905 } else {
1906 # check for "$config->...['CONFIG']/revision" and the
1907 # contents should match the revision number
1908 if(!compare_revision($revision_file, $svn_revision)){
1909 // If revision differs, clean compile directory
1910 foreach(scan_directory($directory) as $file) {
1911 if(($file==".")||($file=="..")) continue;
1912 if( is_file($directory."/".$file) &&
1913 is_writable($directory."/".$file)) {
1914 // delete file
1915 if(!unlink($directory."/".$file)) {
1916 print_red("File ".$directory."/".$file." could not be deleted.");
1917 // This should never be reached
1918 }
1919 } elseif(is_dir($directory."/".$file) &&
1920 is_writable($directory."/".$file)) {
1921 // Just recursively delete it
1922 rmdirRecursive($directory."/".$file);
1923 }
1924 }
1925 // We should now create a fresh revision file
1926 clean_smarty_compile_dir($directory);
1927 } else {
1928 // Revision matches, nothing to do
1929 }
1930 }
1931 } else {
1932 // Smarty compile dir is not accessible
1933 // (Smarty will warn about this)
1934 }
1935 }
1937 function create_revision($revision_file, $revision)
1938 {
1939 $result= false;
1941 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1942 if($fh= fopen($revision_file, "w")) {
1943 if(fwrite($fh, $revision)) {
1944 $result= true;
1945 }
1946 }
1947 fclose($fh);
1948 } else {
1949 print_red("Can not write to revision file");
1950 }
1952 return $result;
1953 }
1955 function compare_revision($revision_file, $revision)
1956 {
1957 // false means revision differs
1958 $result= false;
1960 if(file_exists($revision_file) && is_readable($revision_file)) {
1961 // Open file
1962 if($fh= fopen($revision_file, "r")) {
1963 // Compare File contents with current revision
1964 if($revision == fread($fh, filesize($revision_file))) {
1965 $result= true;
1966 }
1967 } else {
1968 print_red("Can not open revision file");
1969 }
1970 // Close file
1971 fclose($fh);
1972 }
1974 return $result;
1975 }
1977 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1978 {
1979 $str = ""; // Our return value will be saved in this var
1981 $color = dechex($percentage+150);
1982 $color2 = dechex(150 - $percentage);
1983 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1985 $progress = (int)(($percentage /100)*$width);
1987 /* Abort printing out percentage, if divs are to small */
1990 /* If theres a better solution for this, use it... */
1991 $str = "
1992 <div style=\" width:".($width)."px;
1993 height:".($height)."px;
1994 background-color:#000000;
1995 padding:1px;\">
1997 <div style=\" width:".($width)."px;
1998 background-color:#$bgcolor;
1999 height:".($height)."px;\">
2001 <div style=\" width:".$progress."px;
2002 height:".$height."px;
2003 background-color:#".$color2.$color2.$color."; \">";
2006 if(($height >10)&&($showvalue)){
2007 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2008 <b>".$percentage."%</b>
2009 </font>";
2010 }
2012 $str.= "</div></div></div>";
2014 return($str);
2015 }
2018 function array_key_ics($ikey, $items)
2019 {
2020 /* Gather keys, make them lowercase */
2021 $tmp= array();
2022 foreach ($items as $key => $value){
2023 $tmp[strtolower($key)]= $key;
2024 }
2026 if (isset($tmp[strtolower($ikey)])){
2027 return($tmp[strtolower($ikey)]);
2028 }
2030 return ("");
2031 }
2034 function search_config($arr, $name, $return)
2035 {
2036 if (is_array($arr)){
2037 foreach ($arr as $a){
2038 if (isset($a['CLASS']) &&
2039 strtolower($a['CLASS']) == strtolower($name)){
2041 if (isset($a[$return])){
2042 return ($a[$return]);
2043 } else {
2044 return ("");
2045 }
2046 } else {
2047 $res= search_config ($a, $name, $return);
2048 if ($res != ""){
2049 return $res;
2050 }
2051 }
2052 }
2053 }
2054 return ("");
2055 }
2058 function array_differs($src, $dst)
2059 {
2060 /* If the count is differing, the arrays differ */
2061 if (count ($src) != count ($dst)){
2062 return (TRUE);
2063 }
2065 /* So the count is the same - lets check the contents */
2066 $differs= FALSE;
2067 foreach($src as $value){
2068 if (!in_array($value, $dst)){
2069 $differs= TRUE;
2070 }
2071 }
2073 return ($differs);
2074 }
2077 function saveFilter($a_filter, $values)
2078 {
2079 if (isset($_POST['regexit'])){
2080 $a_filter["regex"]= $_POST['regexit'];
2082 foreach($values as $type){
2083 if (isset($_POST[$type])) {
2084 $a_filter[$type]= "checked";
2085 } else {
2086 $a_filter[$type]= "";
2087 }
2088 }
2089 }
2091 /* React on alphabet links if needed */
2092 if (isset($_GET['search'])){
2093 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2094 if ($s == "**"){
2095 $s= "*";
2096 }
2097 $a_filter['regex']= $s;
2098 }
2100 return ($a_filter);
2101 }
2104 /* Escape all preg_* relevant characters */
2105 function normalizePreg($input)
2106 {
2107 return (addcslashes($input, '[]()|/.*+-'));
2108 }
2111 /* Escape all LDAP filter relevant characters */
2112 function normalizeLdap($input)
2113 {
2114 return (addcslashes($input, '()|'));
2115 }
2118 /* Resturns the difference between to microtime() results in float */
2119 function get_MicroTimeDiff($start , $stop)
2120 {
2121 $a = split("\ ",$start);
2122 $b = split("\ ",$stop);
2124 $secs = $b[1] - $a[1];
2125 $msecs= $b[0] - $a[0];
2127 $ret = (float) ($secs+ $msecs);
2128 return($ret);
2129 }
2132 /* Check if the given department name is valid */
2133 function is_department_name_reserved($name,$base)
2134 {
2135 $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2136 preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2137 preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2138 $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2140 /* Check if name is one of the reserved names */
2141 if(in_array_ics($name,$reservedName)) {
2142 return(true);
2143 }
2145 /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2146 foreach($follwedNames as $key => $names){
2147 if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2148 return(true);
2149 }
2150 }
2151 return(false);
2152 }
2155 function get_base_dir()
2156 {
2157 global $BASE_DIR;
2159 return $BASE_DIR;
2160 }
2163 function obj_is_readable($dn, $object, $attribute)
2164 {
2165 global $ui;
2167 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2168 }
2171 function obj_is_writable($dn, $object, $attribute)
2172 {
2173 global $ui;
2175 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2176 }
2179 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2180 {
2181 /* Initialize variables */
2182 $ret = array("count" => 0); // Set count to 0
2183 $next = true; // if false, then skip next loops and return
2184 $cnt = 0; // Current number of loops
2185 $max = 100; // Just for security, prevent looops
2186 $ldap = NULL; // To check if created result a valid
2187 $keep = ""; // save last failed parse string
2189 /* Check each parsed dn in ldap ? */
2190 if($config!=NULL && $verify_in_ldap){
2191 $ldap = $config->get_ldap_link();
2192 }
2194 $Diff = ldap_explode_dn($dn,0);
2196 /* Lets start */
2197 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2199 $cnt ++;
2200 if(!preg_match("/,/",$dn)){
2201 $next = false;
2202 }
2203 $object = preg_replace("/[,].*$/","",$dn);
2204 $dn = preg_replace("/^[^,]+,/","",$dn);
2206 /* Check if current dn is valid */
2207 if($ldap!=NULL){
2208 $ldap->cd($dn);
2209 $ldap->cat($dn,array("dn"));
2210 if($ldap->count()){
2211 $ret[] = $keep.$object;
2212 $keep = "";
2213 }else{
2214 $keep .= $object.",";
2215 }
2216 }else{
2217 $ret[] = $keep.$object;
2218 $keep = "";
2219 }
2220 }
2222 /* Append the rest */
2223 $ret[] = $keep.$dn;
2224 $ret['count'] = count($ret) - 1;
2226 $diff = array_diff($ret,$Diff);
2227 if($diff){
2228 print_a(array("Diff" => $diff,"OLD" => $Diff,"NEW"=> $ret,"DEBUG"=> debug_backtrace()));
2229 }
2230 return($ret);
2231 }
2233 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2234 ?>