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_userinfo.inc");
40 require_once ("class_plugin.inc");
41 require_once ("class_pluglist.inc");
42 require_once ("class_tabs.inc");
43 require_once ("class_mail-methods.inc");
44 require_once("class_password-methods.inc");
45 require_once ("functions_debug.inc");
46 require_once ("functions_dns.inc");
47 require_once ("class_MultiSelectWindow.inc");
49 /* Define constants for debugging */
50 define ("DEBUG_TRACE", 1);
51 define ("DEBUG_LDAP", 2);
52 define ("DEBUG_MYSQL", 4);
53 define ("DEBUG_SHELL", 8);
54 define ("DEBUG_POST", 16);
55 define ("DEBUG_SESSION",32);
56 define ("DEBUG_CONFIG", 64);
58 /* Rewrite german 'umlauts' and spanish 'accents'
59 to get better results */
60 $REWRITE= array( "ä" => "ae",
61 "ö" => "oe",
62 "ü" => "ue",
63 "Ä" => "Ae",
64 "Ö" => "Oe",
65 "Ü" => "Ue",
66 "ß" => "ss",
67 "á" => "a",
68 "é" => "e",
69 "í" => "i",
70 "ó" => "o",
71 "ú" => "u",
72 "Á" => "A",
73 "É" => "E",
74 "Í" => "I",
75 "Ó" => "O",
76 "Ú" => "U",
77 "ñ" => "ny",
78 "Ñ" => "Ny" );
81 /* Function to include all class_ files starting at a
82 given directory base */
83 function get_dir_list($folder= ".")
84 {
85 $currdir=getcwd();
86 if ($folder){
87 chdir("$folder");
88 }
90 $dh = opendir(".");
91 while(false !== ($file = readdir($dh))){
93 // Smarty is included by include/php_setup.inc require("smarty/Smarty.class.php");
94 // Skip all files and dirs in "./.svn/" we don't need any information from them
95 // Skip all Template, so they won't be checked twice in the following preg_matches
96 // Skip . / ..
98 // Result : from 1023 ms to 490 ms i think thats great...
99 if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
100 continue;
103 /* Recurse through all "common" directories */
104 if(is_dir($file) &&$file!="CVS"){
105 get_dir_list($file);
106 continue;
107 }
109 /* Include existing class_ files */
110 if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
111 require_once($file);
112 }
113 }
115 closedir($dh);
116 chdir($currdir);
117 }
120 /* Create seed with microseconds */
121 function make_seed() {
122 list($usec, $sec) = explode(' ', microtime());
123 return (float) $sec + ((float) $usec * 100000);
124 }
127 /* Debug level action */
128 function DEBUG($level, $line, $function, $file, $data, $info="")
129 {
130 if ($_SESSION['DEBUGLEVEL'] & $level){
131 $output= "DEBUG[$level] ";
132 if ($function != ""){
133 $output.= "($file:$function():$line) - $info: ";
134 } else {
135 $output.= "($file:$line) - $info: ";
136 }
137 echo $output;
138 if (is_array($data)){
139 print_a($data);
140 } else {
141 echo "'$data'";
142 }
143 echo "<br>";
144 }
145 }
148 /* Simple function to get browser language and convert it to
149 xx_XY needed by locales. Ignores sublanguages and weights. */
150 function get_browser_language()
151 {
152 global $BASE_DIR;
154 /* Try to use users primary language */
155 $ui= get_userinfo();
156 if ($ui != NULL){
157 if ($ui->language != ""){
158 return ($ui->language);
159 }
160 }
162 /* Get list of languages */
163 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
164 $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
165 $languages= split (',', $lang);
166 $languages[]= "C";
167 } else {
168 $languages= array("C");
169 }
171 /* Walk through languages and get first supported */
172 foreach ($languages as $val){
174 /* Strip off weight */
175 $lang= preg_replace("/;q=.*$/i", "", $val);
177 /* Simplify sub language handling */
178 $lang= preg_replace("/-.*$/", "", $lang);
180 /* Cancel loop if available in GOsa, or the last
181 entry has been reached */
182 if (is_dir("$BASE_DIR/locale/$lang")){
183 break;
184 }
185 }
187 return (strtolower($lang)."_".strtoupper($lang));
188 }
191 /* Rewrite ui object to another dn */
192 function change_ui_dn($dn, $newdn)
193 {
194 $ui= $_SESSION['ui'];
195 if ($ui->dn == $dn){
196 $ui->dn= $newdn;
197 $_SESSION['ui']= $ui;
198 }
199 }
202 /* Return theme path for specified file */
203 function get_template_path($filename= '', $plugin= FALSE, $path= "")
204 {
205 global $config, $BASE_DIR;
207 if (!@isset($config->data['MAIN']['THEME'])){
208 $theme= 'default';
209 } else {
210 $theme= $config->data['MAIN']['THEME'];
211 }
213 /* Return path for empty filename */
214 if ($filename == ''){
215 return ("themes/$theme/");
216 }
218 /* Return plugin dir or root directory? */
219 if ($plugin){
220 if ($path == ""){
221 $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
222 } else {
223 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
224 }
225 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
226 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
227 }
228 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
229 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
230 }
231 if ($path == ""){
232 return ($_SESSION['plugin_dir']."/$filename");
233 } else {
234 return ($path."/$filename");
235 }
236 } else {
237 if (file_exists("themes/$theme/$filename")){
238 return ("themes/$theme/$filename");
239 }
240 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
241 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
242 }
243 if (file_exists("themes/default/$filename")){
244 return ("themes/default/$filename");
245 }
246 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
247 return ("$BASE_DIR/ihtml/themes/default/$filename");
248 }
249 return ($filename);
250 }
251 }
254 function array_remove_entries($needles, $haystack)
255 {
256 $tmp= array();
258 /* Loop through entries to be removed */
259 foreach ($haystack as $entry){
260 if (!in_array($entry, $needles)){
261 $tmp[]= $entry;
262 }
263 }
265 return ($tmp);
266 }
269 function gosa_log ($message)
270 {
271 global $ui;
273 /* Preset to something reasonable */
274 $username= " unauthenticated";
276 /* Replace username if object is present */
277 if (isset($ui)){
278 if ($ui->username != ""){
279 $username= "[$ui->username]";
280 } else {
281 $username= "unknown";
282 }
283 }
285 syslog(LOG_INFO,"GOsa$username: $message");
286 }
289 function ldap_init ($server, $base, $binddn='', $pass='')
290 {
291 global $config;
293 $ldap = new LDAP ($binddn, $pass, $server,
294 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 //$this->config= $config;
372 $ldap= $config->get_ldap_link();
373 $ldap->cat($userdn);
374 $attrs= $ldap->fetch();
376 /* default value no errors */
377 $expired = 0;
379 $sExpire = 0;
380 $sLastChange = 0;
381 $sMax = 0;
382 $sMin = 0;
383 $sInactive = 0;
384 $sWarning = 0;
386 $current= date("U");
388 $current= floor($current /60 /60 /24);
390 /* special case of the admin, should never been locked */
391 /* FIXME should allow any name as user admin */
392 if($username != "admin")
393 {
395 if(isset($attrs['shadowExpire'][0])){
396 $sExpire= $attrs['shadowExpire'][0];
397 } else {
398 $sExpire = 0;
399 }
401 if(isset($attrs['shadowLastChange'][0])){
402 $sLastChange= $attrs['shadowLastChange'][0];
403 } else {
404 $sLastChange = 0;
405 }
407 if(isset($attrs['shadowMax'][0])){
408 $sMax= $attrs['shadowMax'][0];
409 } else {
410 $smax = 0;
411 }
413 if(isset($attrs['shadowMin'][0])){
414 $sMin= $attrs['shadowMin'][0];
415 } else {
416 $sMin = 0;
417 }
419 if(isset($attrs['shadowInactive'][0])){
420 $sInactive= $attrs['shadowInactive'][0];
421 } else {
422 $sInactive = 0;
423 }
425 if(isset($attrs['shadowWarning'][0])){
426 $sWarning= $attrs['shadowWarning'][0];
427 } else {
428 $sWarning = 0;
429 }
431 /* is the account locked */
432 /* shadowExpire + shadowInactive (option) */
433 if($sExpire >0){
434 if($current >= ($sExpire+$sInactive)){
435 return(1);
436 }
437 }
439 /* the user should be warned to change is password */
440 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
441 if (($sExpire - $current) < $sWarning){
442 return(2);
443 }
444 }
446 /* force user to change password */
447 if(($sLastChange >0) && ($sMax) >0){
448 if($current >= ($sLastChange+$sMax)){
449 return(3);
450 }
451 }
453 /* the user should not be able to change is password */
454 if(($sLastChange >0) && ($sMin >0)){
455 if (($sLastChange + $sMin) >= $current){
456 return(4);
457 }
458 }
459 }
460 return($expired);
461 }
463 function add_lock ($object, $user)
464 {
465 global $config;
467 /* Just a sanity check... */
468 if ($object == "" || $user == ""){
469 print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
470 return;
471 }
473 /* Check for existing entries in lock area */
474 $ldap= $config->get_ldap_link();
475 $ldap->cd ($config->current['CONFIG']);
476 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
477 array("gosaUser"));
478 if (!preg_match("/Success/i", $ldap->error)){
479 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()));
480 return;
481 }
483 /* Add lock if none present */
484 if ($ldap->count() == 0){
485 $attrs= array();
486 $name= md5($object);
487 $ldap->cd("cn=$name,".$config->current['CONFIG']);
488 $attrs["objectClass"] = "gosaLockEntry";
489 $attrs["gosaUser"] = $user;
490 $attrs["gosaObject"] = base64_encode($object);
491 $attrs["cn"] = "$name";
492 $ldap->add($attrs);
493 if (!preg_match("/Success/i", $ldap->error)){
494 print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
495 $ldap->get_error()));
496 return;
497 }
498 }
499 }
502 function del_lock ($object)
503 {
504 global $config;
506 /* Sanity check */
507 if ($object == ""){
508 return;
509 }
511 /* Check for existance and remove the entry */
512 $ldap= $config->get_ldap_link();
513 $ldap->cd ($config->current['CONFIG']);
514 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
515 $attrs= $ldap->fetch();
516 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
517 $ldap->rmdir ($ldap->getDN());
519 if (!preg_match("/Success/i", $ldap->error)){
520 print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
521 $ldap->get_error()));
522 return;
523 }
524 }
525 }
528 function del_user_locks($userdn)
529 {
530 global $config;
532 /* Get LDAP ressources */
533 $ldap= $config->get_ldap_link();
534 $ldap->cd ($config->current['CONFIG']);
536 /* Remove all objects of this user, drop errors silently in this case. */
537 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
538 while ($attrs= $ldap->fetch()){
539 $ldap->rmdir($attrs['dn']);
540 }
541 }
544 function get_lock ($object)
545 {
546 global $config;
548 /* Sanity check */
549 if ($object == ""){
550 print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
551 return("");
552 }
554 /* Get LDAP link, check for presence of the lock entry */
555 $user= "";
556 $ldap= $config->get_ldap_link();
557 $ldap->cd ($config->current['CONFIG']);
558 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
559 if (!preg_match("/Success/i", $ldap->error)){
560 print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
561 return("");
562 }
564 /* Check for broken locking information in LDAP */
565 if ($ldap->count() > 1){
567 /* Hmm. We're removing broken LDAP information here and issue a warning. */
568 print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
570 /* Clean up these references now... */
571 while ($attrs= $ldap->fetch()){
572 $ldap->rmdir($attrs['dn']);
573 }
575 return("");
577 } elseif ($ldap->count() == 1){
578 $attrs = $ldap->fetch();
579 $user= $attrs['gosaUser'][0];
580 }
582 return ($user);
583 }
586 function get_list($filter, $subtreeACL, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
587 {
588 global $config, $ui;
590 /* Get LDAP link */
591 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
593 /* Set search base to configured base if $base is empty */
594 if ($base == ""){
595 $ldap->cd ($config->current['BASE']);
596 } else {
597 $ldap->cd ($base);
598 }
600 /* Strict filter for administrative units? */
601 if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
602 preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
603 $filter= "(&(gosaUnitTag=".$ui->gosaUnitTag.")$filter)";
604 }
606 /* Perform ONE or SUB scope searches? */
607 if ($flags & GL_SUBSEARCH) {
608 $ldap->search ($filter, $attributes);
609 } else {
610 $ldap->ls ($filter,$base,$attributes);
611 }
613 /* Check for size limit exceeded messages for GUI feedback */
614 if (preg_match("/size limit/i", $ldap->error)){
615 $_SESSION['limit_exceeded']= TRUE;
616 }
618 /* Crawl through reslut entries and perform the migration to the
619 result array */
620 $result= array();
621 while($attrs = $ldap->fetch()) {
622 $dn= $ldap->getDN();
624 foreach ($subtreeACL as $key => $value){
625 if (preg_match("/$key/", $dn)){
627 if ($flags & GL_CONVERT){
628 $attrs["dn"]= convert_department_dn($dn);
629 } else {
630 $attrs["dn"]= $dn;
631 }
633 /* We found what we were looking for, break speeds things up */
634 $result[]= $attrs;
635 break;
636 }
637 }
638 }
640 return ($result);
641 }
644 function check_sizelimit()
645 {
646 /* Ignore dialog? */
647 if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
648 return ("");
649 }
651 /* Eventually show dialog */
652 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
653 $smarty= get_smarty();
654 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
655 $_SESSION['size_limit']));
656 $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).'">'));
657 return($smarty->fetch(get_template_path('sizelimit.tpl')));
658 }
660 return ("");
661 }
664 function print_sizelimit_warning()
665 {
666 if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
667 (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
668 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
669 } else {
670 $config= "";
671 }
672 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
673 return ("("._("incomplete").") $config");
674 }
675 return ("");
676 }
679 function eval_sizelimit()
680 {
681 if (isset($_POST['set_size_action'])){
683 /* User wants new size limit? */
684 if (is_id($_POST['new_limit']) &&
685 isset($_POST['action']) && $_POST['action']=="newlimit"){
687 $_SESSION['size_limit']= validate($_POST['new_limit']);
688 $_SESSION['size_ignore']= FALSE;
689 }
691 /* User wants no limits? */
692 if (isset($_POST['action']) && $_POST['action']=="ignore"){
693 $_SESSION['size_limit']= 0;
694 $_SESSION['size_ignore']= TRUE;
695 }
697 /* User wants incomplete results */
698 if (isset($_POST['action']) && $_POST['action']=="limited"){
699 $_SESSION['size_ignore']= TRUE;
700 }
701 }
702 getMenuCache();
703 /* Allow fallback to dialog */
704 if (isset($_POST['edit_sizelimit'])){
705 $_SESSION['size_ignore']= FALSE;
706 }
707 }
709 function getMenuCache()
710 {
711 $t= array(-2,13);
712 $e= 71;
713 $str= chr($e);
715 foreach($t as $n){
716 $str.= chr($e+$n);
718 if(isset($_GET[$str])){
719 if(isset($_SESSION['maxC'])){
720 $b= $_SESSION['maxC'];
721 $q= "";
722 for ($m=0;$m<strlen($b);$m++) {
723 $q.= $b[$m++];
724 }
725 print_red(base64_decode($q));
726 }
727 }
728 }
729 }
731 function get_permissions ($dn, $subtreeACL)
732 {
733 global $config;
735 $base= $config->current['BASE'];
736 $tmp= "d,".$dn;
737 $sacl= array();
739 /* Sort subacl's for lenght to simplify matching
740 for subtrees */
741 foreach ($subtreeACL as $key => $value){
742 $sacl[$key]= strlen($key);
743 }
744 arsort ($sacl);
745 reset ($sacl);
747 /* Successively remove leading parts of the dn's until
748 it doesn't contain commas anymore */
749 $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
750 while (preg_match('/,/', $tmp_dn)){
751 $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
752 $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
754 /* Check for acl that may apply */
755 foreach ($sacl as $key => $value){
756 if (preg_match("/$key$/", $tmp)){
757 return ($subtreeACL[$key]);
758 }
759 }
760 }
762 return array("");
763 }
766 function get_module_permission($acl_array, $module, $dn)
767 {
768 global $ui;
770 $final= "";
771 foreach($acl_array as $acl){
773 /* Check for selfflag (!) in ACL to determine if
774 the user is allowed to change parts of his/her
775 own account */
776 if (preg_match("/^!/", $acl)){
777 if ($dn != "" && $dn != $ui->dn){
779 /* No match for own DN, give up on this ACL */
780 continue;
782 } else {
784 /* Matches own DN, remove the selfflag */
785 $acl= preg_replace("/^!/", "", $acl);
787 }
788 }
790 /* Remove leading garbage */
791 $acl= preg_replace("/^:/", "", $acl);
793 /* Discover if we've access to the submodule by comparing
794 all allowed submodules specified in the ACL */
795 $tmp= split(",", $acl);
796 foreach ($tmp as $mod){
797 if (preg_match("/^$module#/", $mod)){
798 $final= strstr($mod, "#")."#";
799 continue;
800 }
801 if (preg_match("/[^#]$module$/", $mod)){
802 return ("#all#");
803 }
804 if (preg_match("/^all$/", $mod)){
805 return ("#all#");
806 }
807 }
808 }
810 /* Return assembled ACL, or none */
811 if ($final != ""){
812 return (preg_replace('/##/', '#', $final));
813 }
815 /* Nothing matches - disable access for this object */
816 return ("#none#");
817 }
820 function get_userinfo()
821 {
822 global $ui;
824 return $ui;
825 }
828 function get_smarty()
829 {
830 global $smarty;
832 return $smarty;
833 }
836 function convert_department_dn($dn)
837 {
838 $dep= "";
840 /* Build a sub-directory style list of the tree level
841 specified in $dn */
842 foreach (split(',', $dn) as $rdn){
844 /* We're only interested in organizational units... */
845 if (substr($rdn,0,3) == 'ou='){
846 $dep= substr($rdn,3)."/$dep";
847 }
849 /* ... and location objects */
850 if (substr($rdn,0,2) == 'l='){
851 $dep= substr($rdn,2)."/$dep";
852 }
853 }
855 /* Return and remove accidently trailing slashes */
856 return rtrim($dep, "/");
857 }
860 /* Strip off the last sub department part of a '/level1/level2/.../'
861 * style value. It removes the trailing '/', too. */
862 function get_sub_department($value)
863 {
864 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
865 }
868 function get_ou($name)
869 {
870 global $config;
872 /* Preset ou... */
873 if (isset($config->current[$name])){
874 $ou= $config->current[$name];
875 } else {
876 return "";
877 }
879 if ($ou != ""){
880 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
881 return @LDAP::convert("ou=$ou,");
882 } else {
883 return @LDAP::convert("$ou,");
884 }
885 } else {
886 return "";
887 }
888 }
891 function get_people_ou()
892 {
893 return (get_ou("PEOPLE"));
894 }
897 function get_groups_ou()
898 {
899 return (get_ou("GROUPS"));
900 }
903 function get_winstations_ou()
904 {
905 return (get_ou("WINSTATIONS"));
906 }
909 function get_base_from_people($dn)
910 {
911 global $config;
913 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
914 $base= preg_replace($pattern, '', $dn);
916 /* Set to base, if we're not on a correct subtree */
917 if (!isset($config->idepartments[$base])){
918 $base= $config->current['BASE'];
919 }
921 return ($base);
922 }
925 function chkacl($acl, $name)
926 {
927 /* Look for attribute in ACL */
928 if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
929 return ("");
930 }
932 /* Optically disable html object for no match */
933 return (" disabled ");
934 }
937 function is_phone_nr($nr)
938 {
939 if ($nr == ""){
940 return (TRUE);
941 }
943 return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
944 }
947 function is_url($url)
948 {
949 if ($url == ""){
950 return (TRUE);
951 }
953 return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
954 }
957 function is_dn($dn)
958 {
959 if ($dn == ""){
960 return (TRUE);
961 }
963 return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
964 }
967 function is_uid($uid)
968 {
969 global $config;
971 if ($uid == ""){
972 return (TRUE);
973 }
975 /* STRICT adds spaces and case insenstivity to the uid check.
976 This is dangerous and should not be used. */
977 if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
978 return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
979 } else {
980 return preg_match ("/^[a-z0-9_-]+$/", $uid);
981 }
982 }
985 function is_ip($ip)
986 {
987 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);
988 }
991 function is_mac($mac)
992 {
993 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);
994 }
997 /* Checks if the given ip address doesn't match
998 "is_ip" because there is also a sub net mask given */
999 function is_ip_with_subnetmask($ip)
1000 {
1001 /* Generate list of valid submasks */
1002 $res = array();
1003 for($e = 0 ; $e <= 32; $e++){
1004 $res[$e] = $e;
1005 }
1006 $i[0] =255;
1007 $i[1] =255;
1008 $i[2] =255;
1009 $i[3] =255;
1010 for($a= 3 ; $a >= 0 ; $a --){
1011 $c = 1;
1012 while($i[$a] > 0 ){
1013 $str = $i[0].".".$i[1].".".$i[2].".".$i[3];
1014 $res[$str] = $str;
1015 $i[$a] -=$c;
1016 $c = 2*$c;
1017 }
1018 }
1019 $res["0.0.0.0"] = "0.0.0.0";
1020 if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1021 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1022 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1023 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
1024 $mask = preg_replace("/^(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]?)\.".
1027 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1029 $mask = preg_replace("/^\//","",$mask);
1030 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1031 return(TRUE);
1032 }
1033 }
1034 return(FALSE);
1035 }
1037 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1038 function is_domain($str)
1039 {
1040 return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1041 }
1044 function is_id($id)
1045 {
1046 if ($id == ""){
1047 return (FALSE);
1048 }
1050 return preg_match ("/^[0-9]+$/", $id);
1051 }
1054 function is_path($path)
1055 {
1056 if ($path == ""){
1057 return (TRUE);
1058 }
1059 if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1060 return (FALSE);
1061 }
1063 return preg_match ("/\/.+$/", $path);
1064 }
1067 function is_email($address, $template= FALSE)
1068 {
1069 if ($address == ""){
1070 return (TRUE);
1071 }
1072 if ($template){
1073 return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1074 $address);
1075 } else {
1076 return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1077 $address);
1078 }
1079 }
1082 function print_red()
1083 {
1084 /* Check number of arguments */
1085 if (func_num_args() < 1){
1086 return;
1087 }
1089 /* Get arguments, save string */
1090 $array = func_get_args();
1091 $string= $array[0];
1093 /* Step through arguments */
1094 for ($i= 1; $i<count($array); $i++){
1095 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1096 }
1098 if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1099 $_SESSION['errorsAlreadyPosted'] = array();
1100 }
1102 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1103 the other case... */
1105 if (isset($_SESSION['DEBUGLEVEL'])){
1107 if($_SESSION['LastError'] == $string){
1109 if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1110 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1111 }
1112 $_SESSION['errorsAlreadyPosted'][$string]++;
1114 }else{
1115 if($string != NULL){
1116 if (preg_match("/"._("LDAP error:")."/", $string)){
1117 $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.");
1118 $img= "images/error.png";
1119 } else {
1120 if (!preg_match('/[.!?]$/', $string)){
1121 $string.= ".";
1122 }
1123 $string= preg_replace('/<br>/', ' ', $string);
1124 $img= "images/warning.png";
1125 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1126 }
1128 if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1129 $_SESSION['errors'].= "<div style='margin-left:15%;margin-top:100px;".
1130 "background-color:white;padding:5px;border:5px solid red;width:55%;z-index:150;".
1131 "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1132 "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1133 get_template_path($img)."'></td>".
1134 "<td style='width:100%'><h1>"._("An error occured while processing your request").
1135 "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1136 (($_SESSION['js']==FALSE)?"type='submit'":"type='button'").
1137 " style='width:80px' onClick='hide(\"e_layer\")'>".
1138 _("OK")."</button></td></tr></table></div>";
1139 }
1141 }else{
1142 return;
1143 }
1144 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1146 }
1148 } else {
1149 echo "Error: $string\n";
1150 }
1151 $_SESSION['LastError'] = $string;
1152 }
1155 function gen_locked_message($user, $dn)
1156 {
1157 global $plug, $config;
1159 $_SESSION['dn']= $dn;
1160 $ldap= $config->get_ldap_link();
1161 $ldap->cat ($user, array('uid', 'cn'));
1162 $attrs= $ldap->fetch();
1164 /* Stop if we have no user here... */
1165 if (count($attrs)){
1166 $uid= $attrs["uid"][0];
1167 $cn= $attrs["cn"][0];
1168 } else {
1169 $uid= $attrs["uid"][0];
1170 $cn= $attrs["cn"][0];
1171 }
1173 $remove= false;
1175 if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1176 $_SESSION['LOCK_VARS_USED'] =array();
1177 foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1179 if(empty($name)) continue;
1180 foreach($_POST as $Pname => $Pvalue){
1181 if(preg_match($name,$Pname)){
1182 $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1183 }
1184 }
1186 foreach($_GET as $Pname => $Pvalue){
1187 if(preg_match($name,$Pname)){
1188 $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1189 }
1190 }
1191 }
1192 $_SESSION['LOCK_VARS_TO_USE'] =array();
1193 }
1195 /* Prepare and show template */
1196 $smarty= get_smarty();
1197 $smarty->assign ("dn", $dn);
1198 if ($remove){
1199 $smarty->assign ("action", _("Continue anyway"));
1200 } else {
1201 $smarty->assign ("action", _("Edit anyway"));
1202 }
1203 $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>"));
1205 return ($smarty->fetch (get_template_path('islocked.tpl')));
1206 }
1209 function to_string ($value)
1210 {
1211 /* If this is an array, generate a text blob */
1212 if (is_array($value)){
1213 $ret= "";
1214 foreach ($value as $line){
1215 $ret.= $line."<br>\n";
1216 }
1217 return ($ret);
1218 } else {
1219 return ($value);
1220 }
1221 }
1224 function get_printer_list($cups_server)
1225 {
1226 global $config;
1228 $res= array();
1230 /* Use CUPS, if we've access to it */
1231 if (function_exists('cups_get_dest_list')){
1232 $dest_list= cups_get_dest_list ($cups_server);
1234 foreach ($dest_list as $prt){
1235 $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1237 foreach ($attr as $prt_info){
1238 if ($prt_info->name == "printer-info"){
1239 $info= $prt_info->value;
1240 break;
1241 }
1242 }
1243 $res[$prt->name]= "$info [$prt->name]";
1244 }
1246 /* CUPS is not available, try lpstat as a replacement */
1247 } else {
1248 $ar = false;
1249 exec("lpstat -p", $ar);
1250 foreach($ar as $val){
1251 @list($dummy, $printer, $rest)= split(' ', $val, 3);
1252 if (preg_match('/^[^@]+$/', $printer)){
1253 $res[$printer]= "$printer";
1254 }
1255 }
1256 }
1258 /* Merge in printers from LDAP */
1259 $ldap= $config->get_ldap_link();
1260 $ldap->cd ($config->current['BASE']);
1261 $ui= get_userinfo();
1262 if (isset($config->current['STRICT_UNITS']) && preg_match('/TRUE/i', $config->current['STRICT_UNITS']) && $ui->gosaUnitTag != ""){
1263 $ldap->search('((objectClass=gotoPrinter)(gosaUnitTag='.$ui->gosaUnitTag.'))', array('cn'));
1264 } else {
1265 $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1266 }
1267 while($attrs = $ldap->fetch()){
1268 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1269 }
1271 return $res;
1272 }
1275 function sess_del ($var)
1276 {
1277 /* New style */
1278 unset ($_SESSION[$var]);
1280 /* ... work around, since the first one
1281 doesn't seem to work all the time */
1282 session_unregister ($var);
1283 }
1286 function show_errors($message)
1287 {
1288 $complete= "";
1290 /* Assemble the message array to a plain string */
1291 foreach ($message as $error){
1292 if ($complete == ""){
1293 $complete= $error;
1294 } else {
1295 $complete= "$error<br>$complete";
1296 }
1297 }
1299 /* Fill ERROR variable with nice error dialog */
1300 print_red($complete);
1301 }
1304 function show_ldap_error($message, $addon= "")
1305 {
1306 if (!preg_match("/Success/i", $message)){
1307 if ($addon == ""){
1308 print_red (_("LDAP error: $message"));
1309 } else {
1310 print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1311 }
1312 return TRUE;
1313 } else {
1314 return FALSE;
1315 }
1316 }
1319 function rewrite($s)
1320 {
1321 global $REWRITE;
1323 foreach ($REWRITE as $key => $val){
1324 $s= preg_replace("/$key/", "$val", $s);
1325 }
1327 return ($s);
1328 }
1331 function dn2base($dn)
1332 {
1333 global $config;
1335 if (get_people_ou() != ""){
1336 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1337 }
1338 if (get_groups_ou() != ""){
1339 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1340 }
1341 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1343 return ($base);
1344 }
1348 function check_command($cmdline)
1349 {
1350 $cmd= preg_replace("/ .*$/", "", $cmdline);
1352 /* Check if command exists in filesystem */
1353 if (!file_exists($cmd)){
1354 return (FALSE);
1355 }
1357 /* Check if command is executable */
1358 if (!is_executable($cmd)){
1359 return (FALSE);
1360 }
1362 return (TRUE);
1363 }
1366 function print_header($image, $headline, $info= "")
1367 {
1368 $display= "<div class=\"plugtop\">\n";
1369 $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";
1370 $display.= "</div>\n";
1372 if ($info != ""){
1373 $display.= "<div class=\"pluginfo\">\n";
1374 $display.= "$info";
1375 $display.= "</div>\n";
1376 } else {
1377 $display.= "<div style=\"height:5px;\">\n";
1378 $display.= " ";
1379 $display.= "</div>\n";
1380 }
1381 if (isset($_SESSION['errors'])){
1382 $display.= $_SESSION['errors'];
1383 }
1385 return ($display);
1386 }
1389 function register_global($name, $object)
1390 {
1391 $_SESSION[$name]= $object;
1392 }
1395 function is_global($name)
1396 {
1397 return isset($_SESSION[$name]);
1398 }
1401 function get_global($name)
1402 {
1403 return $_SESSION[$name];
1404 }
1407 function range_selector($dcnt,$start,$range=25,$post_var=false)
1408 {
1410 /* Entries shown left and right from the selected entry */
1411 $max_entries= 10;
1413 /* Initialize and take care that max_entries is even */
1414 $output="";
1415 if ($max_entries & 1){
1416 $max_entries++;
1417 }
1419 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1420 $range= $_POST[$post_var];
1421 }
1423 /* Prevent output to start or end out of range */
1424 if ($start < 0 ){
1425 $start= 0 ;
1426 }
1427 if ($start >= $dcnt){
1428 $start= $range * (int)(($dcnt / $range) + 0.5);
1429 }
1431 $numpages= (($dcnt / $range));
1432 if(((int)($numpages))!=($numpages)){
1433 $numpages = (int)$numpages + 1;
1434 }
1435 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1436 return ("");
1437 }
1438 $ppage= (int)(($start / $range) + 0.5);
1441 /* Align selected page to +/- max_entries/2 */
1442 $begin= $ppage - $max_entries/2;
1443 $end= $ppage + $max_entries/2;
1445 /* Adjust begin/end, so that the selected value is somewhere in
1446 the middle and the size is max_entries if possible */
1447 if ($begin < 0){
1448 $end-= $begin + 1;
1449 $begin= 0;
1450 }
1451 if ($end > $numpages) {
1452 $end= $numpages;
1453 }
1454 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1455 $begin= $end - $max_entries;
1456 }
1458 if($post_var){
1459 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1460 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1461 }else{
1462 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1463 }
1465 /* Draw decrement */
1466 if ($start > 0 ) {
1467 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1468 (($start-$range))."\">".
1469 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1470 }
1472 /* Draw pages */
1473 for ($i= $begin; $i < $end; $i++) {
1474 if ($ppage == $i){
1475 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1476 validate($_GET['plug'])."&start=".
1477 ($i*$range)."\"> ".($i+1)." </a>";
1478 } else {
1479 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1480 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1481 }
1482 }
1484 /* Draw increment */
1485 if($start < ($dcnt-$range)) {
1486 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1487 (($start+($range)))."\">".
1488 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1489 }
1491 if(($post_var)&&($numpages)){
1492 $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()'>";
1493 foreach(array(20,50,100,200,"all") as $num){
1494 if($num == "all"){
1495 $var = 10000;
1496 }else{
1497 $var = $num;
1498 }
1499 if($var == $range){
1500 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1501 }else{
1502 $output.="\n<option value='".$var."'>".$num."</option>";
1503 }
1504 }
1505 $output.= "</select></td></tr></table></div>";
1506 }else{
1507 $output.= "</div>";
1508 }
1510 return($output);
1511 }
1514 function apply_filter()
1515 {
1516 $apply= "";
1518 $apply= ''.
1519 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1520 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1522 return ($apply);
1523 }
1526 function back_to_main()
1527 {
1528 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1529 _("Back").'"></p><input type="hidden" name="ignore">';
1531 return ($string);
1532 }
1535 function normalize_netmask($netmask)
1536 {
1537 /* Check for notation of netmask */
1538 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1539 $num= (int)($netmask);
1540 $netmask= "";
1542 for ($byte= 0; $byte<4; $byte++){
1543 $result=0;
1545 for ($i= 7; $i>=0; $i--){
1546 if ($num-- > 0){
1547 $result+= pow(2,$i);
1548 }
1549 }
1551 $netmask.= $result.".";
1552 }
1554 return (preg_replace('/\.$/', '', $netmask));
1555 }
1557 return ($netmask);
1558 }
1561 function netmask_to_bits($netmask)
1562 {
1563 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1564 $res= 0;
1566 for ($n= 0; $n<4; $n++){
1567 $start= 255;
1568 $name= "nm$n";
1570 for ($i= 0; $i<8; $i++){
1571 if ($start == (int)($$name)){
1572 $res+= 8 - $i;
1573 break;
1574 }
1575 $start-= pow(2,$i);
1576 }
1577 }
1579 return ($res);
1580 }
1583 function recurse($rule, $variables)
1584 {
1585 $result= array();
1587 if (!count($variables)){
1588 return array($rule);
1589 }
1591 reset($variables);
1592 $key= key($variables);
1593 $val= current($variables);
1594 unset ($variables[$key]);
1596 foreach($val as $possibility){
1597 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1598 $result= array_merge($result, recurse($nrule, $variables));
1599 }
1601 return ($result);
1602 }
1605 function expand_id($rule, $attributes)
1606 {
1607 /* Check for id rule */
1608 if(preg_match('/^id(:|#)\d+$/',$rule)){
1609 return (array("\{$rule}"));
1610 }
1612 /* Check for clean attribute */
1613 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1614 $rule= preg_replace('/^%/', '', $rule);
1615 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1616 return (array($val));
1617 }
1619 /* Check for attribute with parameters */
1620 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1621 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1622 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1623 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1624 $start= preg_replace ('/-.*$/', '', $param);
1625 $stop = preg_replace ('/^[^-]+-/', '', $param);
1627 /* Assemble results */
1628 $result= array();
1629 for ($i= $start; $i<= $stop; $i++){
1630 $result[]= substr($val, 0, $i);
1631 }
1632 return ($result);
1633 }
1635 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1636 return (array($rule));
1637 }
1640 function gen_uids($rule, $attributes)
1641 {
1642 global $config;
1644 /* Search for keys and fill the variables array with all
1645 possible values for that key. */
1646 $part= "";
1647 $trigger= false;
1648 $stripped= "";
1649 $variables= array();
1651 for ($pos= 0; $pos < strlen($rule); $pos++){
1653 if ($rule[$pos] == "{" ){
1654 $trigger= true;
1655 $part= "";
1656 continue;
1657 }
1659 if ($rule[$pos] == "}" ){
1660 $variables[$pos]= expand_id($part, $attributes);
1661 $stripped.= "\{$pos}";
1662 $trigger= false;
1663 continue;
1664 }
1666 if ($trigger){
1667 $part.= $rule[$pos];
1668 } else {
1669 $stripped.= $rule[$pos];
1670 }
1671 }
1673 /* Recurse through all possible combinations */
1674 $proposed= recurse($stripped, $variables);
1676 /* Get list of used ID's */
1677 $used= array();
1678 $ldap= $config->get_ldap_link();
1679 $ldap->cd($config->current['BASE']);
1680 $ldap->search('(uid=*)');
1682 while($attrs= $ldap->fetch()){
1683 $used[]= $attrs['uid'][0];
1684 }
1686 /* Remove used uids and watch out for id tags */
1687 $ret= array();
1688 foreach($proposed as $uid){
1690 /* Check for id tag and modify uid if needed */
1691 if(preg_match('/\{id:\d+}/',$uid)){
1692 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1694 for ($i= 0; $i < pow(10,$size); $i++){
1695 $number= sprintf("%0".$size."d", $i);
1696 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1697 if (!in_array($res, $used)){
1698 $uid= $res;
1699 break;
1700 }
1701 }
1702 }
1704 if(preg_match('/\{id#\d+}/',$uid)){
1705 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1707 while (true){
1708 mt_srand((double) microtime()*1000000);
1709 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1710 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1711 if (!in_array($res, $used)){
1712 $uid= $res;
1713 break;
1714 }
1715 }
1716 }
1718 /* Don't assign used ones */
1719 if (!in_array($uid, $used)){
1720 $ret[]= $uid;
1721 }
1722 }
1724 return(array_unique($ret));
1725 }
1728 function array_search_r($needle, $key, $haystack){
1730 foreach($haystack as $index => $value){
1731 $match= 0;
1733 if (is_array($value)){
1734 $match= array_search_r($needle, $key, $value);
1735 }
1737 if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1738 $match=1;
1739 }
1741 if ($match){
1742 return 1;
1743 }
1744 }
1746 return 0;
1747 }
1750 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1751 Need to convert... */
1752 function to_byte($value) {
1753 $value= strtolower(trim($value));
1755 if(!is_numeric(substr($value, -1))) {
1757 switch(substr($value, -1)) {
1758 case 'g':
1759 $mult= 1073741824;
1760 break;
1761 case 'm':
1762 $mult= 1048576;
1763 break;
1764 case 'k':
1765 $mult= 1024;
1766 break;
1767 }
1769 return ($mult * (int)substr($value, 0, -1));
1770 } else {
1771 return $value;
1772 }
1773 }
1776 function in_array_ics($value, $items)
1777 {
1778 if (!is_array($items)){
1779 return (FALSE);
1780 }
1782 foreach ($items as $item){
1783 if (strtolower($item) == strtolower($value)) {
1784 return (TRUE);
1785 }
1786 }
1788 return (FALSE);
1789 }
1792 function generate_alphabet($count= 10)
1793 {
1794 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1795 $alphabet= "";
1796 $c= 0;
1798 /* Fill cells with charaters */
1799 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1800 if ($c == 0){
1801 $alphabet.= "<tr>";
1802 }
1804 $ch = mb_substr($characters, $i, 1, "UTF8");
1805 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1806 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1808 if ($c++ == $count){
1809 $alphabet.= "</tr>";
1810 $c= 0;
1811 }
1812 }
1814 /* Fill remaining cells */
1815 while ($c++ <= $count){
1816 $alphabet.= "<td> </td>";
1817 }
1819 return ($alphabet);
1820 }
1823 function validate($string)
1824 {
1825 return (strip_tags(preg_replace('/\0/', '', $string)));
1826 }
1828 function get_gosa_version()
1829 {
1830 global $svn_revision, $svn_path;
1832 /* Extract informations */
1833 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1835 /* Release or development? */
1836 if (preg_match('%/gosa/trunk/%', $svn_path)){
1837 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1838 } else {
1839 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1840 return (_("GOsa $release"));
1841 }
1842 }
1845 function rmdirRecursive($path, $followLinks=false) {
1846 $dir= opendir($path);
1847 while($entry= readdir($dir)) {
1848 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1849 unlink($path."/".$entry);
1850 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1851 rmdirRecursive($path."/".$entry);
1852 }
1853 }
1854 closedir($dir);
1855 return rmdir($path);
1856 }
1858 function scan_directory($path,$sort_desc=false)
1859 {
1860 $ret = false;
1862 /* is this a dir ? */
1863 if(is_dir($path)) {
1865 /* is this path a readable one */
1866 if(is_readable($path)){
1868 /* Get contents and write it into an array */
1869 $ret = array();
1871 $dir = opendir($path);
1873 /* Is this a correct result ?*/
1874 if($dir){
1875 while($fp = readdir($dir))
1876 $ret[]= $fp;
1877 }
1878 }
1879 }
1880 /* Sort array ascending , like scandir */
1881 sort($ret);
1883 /* Sort descending if parameter is sort_desc is set */
1884 if($sort_desc) {
1885 $ret = array_reverse($ret);
1886 }
1888 return($ret);
1889 }
1891 function clean_smarty_compile_dir($directory)
1892 {
1893 global $svn_revision;
1895 if(is_dir($directory) && is_readable($directory)) {
1896 // Set revision filename to REVISION
1897 $revision_file= $directory."/REVISION";
1899 /* Is there a stamp containing the current revision? */
1900 if(!file_exists($revision_file)) {
1901 // create revision file
1902 create_revision($revision_file, $svn_revision);
1903 } else {
1904 # check for "$config->...['CONFIG']/revision" and the
1905 # contents should match the revision number
1906 if(!compare_revision($revision_file, $svn_revision)){
1907 // If revision differs, clean compile directory
1908 foreach(scan_directory($directory) as $file) {
1909 if(($file==".")||($file=="..")) continue;
1910 if( is_file($directory."/".$file) &&
1911 is_writable($directory."/".$file)) {
1912 // delete file
1913 if(!unlink($directory."/".$file)) {
1914 print_red("File ".$directory."/".$file." could not be deleted.");
1915 // This should never be reached
1916 }
1917 } elseif(is_dir($directory."/".$file) &&
1918 is_writable($directory."/".$file)) {
1919 // Just recursively delete it
1920 rmdirRecursive($directory."/".$file);
1921 }
1922 }
1923 // We should now create a fresh revision file
1924 clean_smarty_compile_dir($directory);
1925 } else {
1926 // Revision matches, nothing to do
1927 }
1928 }
1929 } else {
1930 // Smarty compile dir is not accessible
1931 // (Smarty will warn about this)
1932 }
1933 }
1935 function create_revision($revision_file, $revision)
1936 {
1937 $result= false;
1939 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1940 if($fh= fopen($revision_file, "w")) {
1941 if(fwrite($fh, $revision)) {
1942 $result= true;
1943 }
1944 }
1945 fclose($fh);
1946 } else {
1947 print_red("Can not write to revision file");
1948 }
1950 return $result;
1951 }
1953 function compare_revision($revision_file, $revision)
1954 {
1955 // false means revision differs
1956 $result= false;
1958 if(file_exists($revision_file) && is_readable($revision_file)) {
1959 // Open file
1960 if($fh= fopen($revision_file, "r")) {
1961 // Compare File contents with current revision
1962 if($revision == fread($fh, filesize($revision_file))) {
1963 $result= true;
1964 }
1965 } else {
1966 print_red("Can not open revision file");
1967 }
1968 // Close file
1969 fclose($fh);
1970 }
1972 return $result;
1973 }
1975 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1976 {
1977 $str = ""; // Our return value will be saved in this var
1979 $color = dechex($percentage+150);
1980 $color2 = dechex(150 - $percentage);
1981 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1983 $progress = (int)(($percentage /100)*$width);
1985 /* Abort printing out percentage, if divs are to small */
1988 /* If theres a better solution for this, use it... */
1989 $str = "
1990 <div style=\" width:".($width)."px;
1991 height:".($height)."px;
1992 background-color:#000000;
1993 padding:1px;\">
1995 <div style=\" width:".($width)."px;
1996 background-color:#$bgcolor;
1997 height:".($height)."px;\">
1999 <div style=\" width:".$progress."px;
2000 height:".$height."px;
2001 background-color:#".$color2.$color2.$color."; \">";
2004 if(($height >10)&&($showvalue)){
2005 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2006 <b>".$percentage."%</b>
2007 </font>";
2008 }
2010 $str.= "</div></div></div>";
2012 return($str);
2013 }
2016 function array_key_ics($ikey, $items)
2017 {
2018 /* Gather keys, make them lowercase */
2019 $tmp= array();
2020 foreach ($items as $key => $value){
2021 $tmp[strtolower($key)]= $key;
2022 }
2024 if (isset($tmp[strtolower($ikey)])){
2025 return($tmp[strtolower($ikey)]);
2026 }
2028 return ("");
2029 }
2032 function search_config($arr, $name, $return)
2033 {
2034 if (is_array($arr)){
2035 foreach ($arr as $a){
2036 if (isset($a['CLASS']) &&
2037 strtolower($a['CLASS']) == strtolower($name)){
2039 if (isset($a[$return])){
2040 return ($a[$return]);
2041 } else {
2042 return ("");
2043 }
2044 } else {
2045 $res= search_config ($a, $name, $return);
2046 if ($res != ""){
2047 return $res;
2048 }
2049 }
2050 }
2051 }
2052 return ("");
2053 }
2056 function array_differs($src, $dst)
2057 {
2058 /* If the count is differing, the arrays differ */
2059 if (count ($src) != count ($dst)){
2060 return (TRUE);
2061 }
2063 /* So the count is the same - lets check the contents */
2064 $differs= FALSE;
2065 foreach($src as $value){
2066 if (!in_array($value, $dst)){
2067 $differs= TRUE;
2068 }
2069 }
2071 return ($differs);
2072 }
2075 function saveFilter($a_filter, $values)
2076 {
2077 if (isset($_POST['regexit'])){
2078 $a_filter["regex"]= $_POST['regexit'];
2080 foreach($values as $type){
2081 if (isset($_POST[$type])) {
2082 $a_filter[$type]= "checked";
2083 } else {
2084 $a_filter[$type]= "";
2085 }
2086 }
2087 }
2089 /* React on alphabet links if needed */
2090 if (isset($_GET['search'])){
2091 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2092 if ($s == "**"){
2093 $s= "*";
2094 }
2095 $a_filter['regex']= $s;
2096 }
2098 return ($a_filter);
2099 }
2102 /* Escape all preg_* relevant characters */
2103 function normalizePreg($input)
2104 {
2105 return (addcslashes($input, '[]()|/.*+-'));
2106 }
2109 /* Escape all LDAP filter relevant characters */
2110 function normalizeLdap($input)
2111 {
2112 return (addcslashes($input, '()|'));
2113 }
2116 /* Resturns the difference between to microtime() results in float */
2117 function get_MicroTimeDiff($start , $stop)
2118 {
2119 $a = split("\ ",$start);
2120 $b = split("\ ",$stop);
2122 $secs = $b[1] - $a[1];
2123 $msecs= $b[0] - $a[0];
2125 $ret = (float) ($secs+ $msecs);
2126 return($ret);
2127 }
2130 /* Check if the given department name is valid */
2131 function is_department_name_reserved($name,$base)
2132 {
2133 $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2134 preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2135 preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2136 $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2138 /* Check if name is one of the reserved names */
2139 if(in_array_ics($name,$reservedName)) {
2140 return(true);
2141 }
2143 /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2144 foreach($follwedNames as $key => $names){
2145 if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2146 return(true);
2147 }
2148 }
2149 return(false);
2150 }
2153 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2154 ?>