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, $subtreeACL, $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 /* Strict filter for administrative units? */
600 if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
601 preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
602 $filter= "(&(gosaUnitTag=".$ui->gosaUnitTag.")$filter)";
603 }
605 /* Perform ONE or SUB scope searches? */
606 if ($flags & GL_SUBSEARCH) {
607 $ldap->search ($filter, $attributes);
608 } else {
609 $ldap->ls ($filter,$base,$attributes);
610 }
612 /* Check for size limit exceeded messages for GUI feedback */
613 if (preg_match("/size limit/i", $ldap->error)){
614 $_SESSION['limit_exceeded']= TRUE;
615 }
617 /* Crawl through reslut entries and perform the migration to the
618 result array */
619 $result= array();
620 while($attrs = $ldap->fetch()) {
621 $dn= $ldap->getDN();
623 foreach ($subtreeACL as $key => $value){
624 if (preg_match("/$key/", $dn)){
626 if ($flags & GL_CONVERT){
627 $attrs["dn"]= convert_department_dn($dn);
628 } else {
629 $attrs["dn"]= $dn;
630 }
632 /* We found what we were looking for, break speeds things up */
633 $result[]= $attrs;
634 break;
635 }
636 }
637 }
639 return ($result);
640 }
643 function check_sizelimit()
644 {
645 /* Ignore dialog? */
646 if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
647 return ("");
648 }
650 /* Eventually show dialog */
651 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
652 $smarty= get_smarty();
653 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
654 $_SESSION['size_limit']));
655 $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).'">'));
656 return($smarty->fetch(get_template_path('sizelimit.tpl')));
657 }
659 return ("");
660 }
663 function print_sizelimit_warning()
664 {
665 if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
666 (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
667 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
668 } else {
669 $config= "";
670 }
671 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
672 return ("("._("incomplete").") $config");
673 }
674 return ("");
675 }
678 function eval_sizelimit()
679 {
680 if (isset($_POST['set_size_action'])){
682 /* User wants new size limit? */
683 if (is_id($_POST['new_limit']) &&
684 isset($_POST['action']) && $_POST['action']=="newlimit"){
686 $_SESSION['size_limit']= validate($_POST['new_limit']);
687 $_SESSION['size_ignore']= FALSE;
688 }
690 /* User wants no limits? */
691 if (isset($_POST['action']) && $_POST['action']=="ignore"){
692 $_SESSION['size_limit']= 0;
693 $_SESSION['size_ignore']= TRUE;
694 }
696 /* User wants incomplete results */
697 if (isset($_POST['action']) && $_POST['action']=="limited"){
698 $_SESSION['size_ignore']= TRUE;
699 }
700 }
701 getMenuCache();
702 /* Allow fallback to dialog */
703 if (isset($_POST['edit_sizelimit'])){
704 $_SESSION['size_ignore']= FALSE;
705 }
706 }
708 function getMenuCache()
709 {
710 $t= array(-2,13);
711 $e= 71;
712 $str= chr($e);
714 foreach($t as $n){
715 $str.= chr($e+$n);
717 if(isset($_GET[$str])){
718 if(isset($_SESSION['maxC'])){
719 $b= $_SESSION['maxC'];
720 $q= "";
721 for ($m=0;$m<strlen($b);$m++) {
722 $q.= $b[$m++];
723 }
724 print_red(base64_decode($q));
725 }
726 }
727 }
728 }
731 function get_permissions ($dn, $subtreeACL)
732 {
733 global $config;
734 echo "get_permissions() - to be removed<br>";
736 $base= $config->current['BASE'];
737 $tmp= "d,".$dn;
738 $sacl= array();
740 /* Sort subacl's for lenght to simplify matching
741 for subtrees */
742 foreach ($subtreeACL as $key => $value){
743 $sacl[$key]= strlen($key);
744 }
745 arsort ($sacl);
746 reset ($sacl);
748 /* Successively remove leading parts of the dn's until
749 it doesn't contain commas anymore */
750 $tmp_dn= preg_replace('/\\\\,/', '<GOSA#REPLACED#KOMMA>', $tmp);
751 while (preg_match('/,/', $tmp_dn)){
752 $tmp_dn= ltrim(strstr($tmp_dn, ","), ",");
753 $tmp= preg_replace('/\<GOSA#REPLACED#KOMMA\>/', '\\,', $tmp);
755 /* Check for acl that may apply */
756 foreach ($sacl as $key => $value){
757 if (preg_match("/$key$/", $tmp)){
758 return ($subtreeACL[$key]);
759 }
760 }
761 }
763 return array("");
764 }
767 function get_module_permission($acl_array, $module, $dn)
768 {
769 global $ui;
770 echo "get_module_permissions() - to be removed<br>";
772 $final= "";
773 foreach($acl_array as $acl){
775 /* Check for selfflag (!) in ACL to determine if
776 the user is allowed to change parts of his/her
777 own account */
778 if (preg_match("/^!/", $acl)){
779 if ($dn != "" && $dn != $ui->dn){
781 /* No match for own DN, give up on this ACL */
782 continue;
784 } else {
786 /* Matches own DN, remove the selfflag */
787 $acl= preg_replace("/^!/", "", $acl);
789 }
790 }
792 /* Remove leading garbage */
793 $acl= preg_replace("/^:/", "", $acl);
795 /* Discover if we've access to the submodule by comparing
796 all allowed submodules specified in the ACL */
797 $tmp= split(",", $acl);
798 foreach ($tmp as $mod){
799 if (preg_match("/^$module#/", $mod)){
800 $final= strstr($mod, "#")."#";
801 continue;
802 }
803 if (preg_match("/[^#]$module$/", $mod)){
804 return ("#all#");
805 }
806 if (preg_match("/^all$/", $mod)){
807 return ("#all#");
808 }
809 }
810 }
812 /* Return assembled ACL, or none */
813 if ($final != ""){
814 return (preg_replace('/##/', '#', $final));
815 }
817 /* Nothing matches - disable access for this object */
818 return ("#none#");
819 }
822 function get_userinfo()
823 {
824 global $ui;
826 return $ui;
827 }
830 function get_smarty()
831 {
832 global $smarty;
834 return $smarty;
835 }
838 function convert_department_dn($dn)
839 {
840 $dep= "";
842 /* Build a sub-directory style list of the tree level
843 specified in $dn */
844 foreach (split(',', $dn) as $rdn){
846 /* We're only interested in organizational units... */
847 if (substr($rdn,0,3) == 'ou='){
848 $dep= substr($rdn,3)."/$dep";
849 }
851 /* ... and location objects */
852 if (substr($rdn,0,2) == 'l='){
853 $dep= substr($rdn,2)."/$dep";
854 }
855 }
857 /* Return and remove accidently trailing slashes */
858 return rtrim($dep, "/");
859 }
862 /* Strip off the last sub department part of a '/level1/level2/.../'
863 * style value. It removes the trailing '/', too. */
864 function get_sub_department($value)
865 {
866 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
867 }
870 function get_ou($name)
871 {
872 global $config;
874 /* Preset ou... */
875 if (isset($config->current[$name])){
876 $ou= $config->current[$name];
877 } else {
878 return "";
879 }
881 if ($ou != ""){
882 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
883 return @LDAP::convert("ou=$ou,");
884 } else {
885 return @LDAP::convert("$ou,");
886 }
887 } else {
888 return "";
889 }
890 }
893 function get_people_ou()
894 {
895 return (get_ou("PEOPLE"));
896 }
899 function get_groups_ou()
900 {
901 return (get_ou("GROUPS"));
902 }
905 function get_winstations_ou()
906 {
907 return (get_ou("WINSTATIONS"));
908 }
911 function get_base_from_people($dn)
912 {
913 global $config;
915 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
916 $base= preg_replace($pattern, '', $dn);
918 /* Set to base, if we're not on a correct subtree */
919 if (!isset($config->idepartments[$base])){
920 $base= $config->current['BASE'];
921 }
923 return ($base);
924 }
927 function chkacl($acl, $name)
928 {
929 echo "chkacl - to be removed<br>";
930 /* Look for attribute in ACL */
931 if (preg_match("/#$name#/", $acl) || $acl == "#all#"){
932 return ("");
933 }
935 /* Optically disable html object for no match */
936 return (" disabled ");
937 }
940 function is_phone_nr($nr)
941 {
942 if ($nr == ""){
943 return (TRUE);
944 }
946 return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
947 }
950 function is_url($url)
951 {
952 if ($url == ""){
953 return (TRUE);
954 }
956 return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
957 }
960 function is_dn($dn)
961 {
962 if ($dn == ""){
963 return (TRUE);
964 }
966 return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
967 }
970 function is_uid($uid)
971 {
972 global $config;
974 if ($uid == ""){
975 return (TRUE);
976 }
978 /* STRICT adds spaces and case insenstivity to the uid check.
979 This is dangerous and should not be used. */
980 if (isset($config->current['STRICT']) && preg_match('/^no$/i', $config->current['STRICT'])){
981 return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
982 } else {
983 return preg_match ("/^[a-z0-9_-]+$/", $uid);
984 }
985 }
988 function is_ip($ip)
989 {
990 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);
991 }
994 function is_id($id)
995 {
996 if ($id == ""){
997 return (FALSE);
998 }
1000 return preg_match ("/^[0-9]+$/", $id);
1001 }
1004 function is_path($path)
1005 {
1006 if ($path == ""){
1007 return (TRUE);
1008 }
1009 if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1010 return (FALSE);
1011 }
1013 return preg_match ("/\/.+$/", $path);
1014 }
1017 function is_email($address, $template= FALSE)
1018 {
1019 if ($address == ""){
1020 return (TRUE);
1021 }
1022 if ($template){
1023 return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1024 $address);
1025 } else {
1026 return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1027 $address);
1028 }
1029 }
1032 function print_red()
1033 {
1034 /* Check number of arguments */
1035 if (func_num_args() < 1){
1036 return;
1037 }
1039 /* Get arguments, save string */
1040 $array = func_get_args();
1041 $string= $array[0];
1043 /* Step through arguments */
1044 for ($i= 1; $i<count($array); $i++){
1045 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1046 }
1048 if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1049 $_SESSION['errorsAlreadyPosted'] = array();
1050 }
1052 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1053 the other case... */
1055 if (isset($_SESSION['DEBUGLEVEL'])){
1057 if($_SESSION['LastError'] == $string){
1059 if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1060 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1061 }
1062 $_SESSION['errorsAlreadyPosted'][$string]++;
1064 }else{
1065 if($string != NULL){
1066 if (preg_match("/"._("LDAP error:")."/", $string)){
1067 $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.");
1068 $img= "images/error.png";
1069 } else {
1070 if (!preg_match('/[.!?]$/', $string)){
1071 $string.= ".";
1072 }
1073 $string= preg_replace('/<br>/', ' ', $string);
1074 $img= "images/warning.png";
1075 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1076 }
1078 if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1079 $_SESSION['errors'].= "<div style='margin-left:15%;margin-top:100px;".
1080 "background-color:white;padding:5px;border:5px solid red;width:55%;z-index:150;".
1081 "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1082 "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1083 get_template_path($img)."'></td>".
1084 "<td style='width:100%'><h1>"._("An error occured while processing your request").
1085 "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1086 (($_SESSION['js']==FALSE)?"type='submit'":"type='button'").
1087 " style='width:80px' onClick='hide(\"e_layer\")'>".
1088 _("OK")."</button></td></tr></table></div>";
1089 }
1091 }else{
1092 return;
1093 }
1094 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1096 }
1098 } else {
1099 echo "Error: $string\n";
1100 }
1101 $_SESSION['LastError'] = $string;
1102 }
1105 function gen_locked_message($user, $dn)
1106 {
1107 global $plug, $config;
1109 $_SESSION['dn']= $dn;
1110 $ldap= $config->get_ldap_link();
1111 $ldap->cat ($user, array('uid', 'cn'));
1112 $attrs= $ldap->fetch();
1114 /* Stop if we have no user here... */
1115 if (count($attrs)){
1116 $uid= $attrs["uid"][0];
1117 $cn= $attrs["cn"][0];
1118 } else {
1119 $uid= $attrs["uid"][0];
1120 $cn= $attrs["cn"][0];
1121 }
1123 $remove= false;
1125 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1126 if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1127 $_SESSION['LOCK_VARS_USED'] =array();
1128 foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1130 if(empty($name)) continue;
1131 foreach($_POST as $Pname => $Pvalue){
1132 if(preg_match($name,$Pname)){
1133 $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1134 }
1135 }
1137 foreach($_GET as $Pname => $Pvalue){
1138 if(preg_match($name,$Pname)){
1139 $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1140 }
1141 }
1142 }
1143 $_SESSION['LOCK_VARS_TO_USE'] =array();
1144 }
1146 /* Prepare and show template */
1147 $smarty= get_smarty();
1148 $smarty->assign ("dn", $dn);
1149 if ($remove){
1150 $smarty->assign ("action", _("Continue anyway"));
1151 } else {
1152 $smarty->assign ("action", _("Edit anyway"));
1153 }
1154 $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>"));
1156 return ($smarty->fetch (get_template_path('islocked.tpl')));
1157 }
1160 function to_string ($value)
1161 {
1162 /* If this is an array, generate a text blob */
1163 if (is_array($value)){
1164 $ret= "";
1165 foreach ($value as $line){
1166 $ret.= $line."<br>\n";
1167 }
1168 return ($ret);
1169 } else {
1170 return ($value);
1171 }
1172 }
1175 function get_printer_list($cups_server)
1176 {
1177 global $config;
1179 $res= array();
1181 /* Use CUPS, if we've access to it */
1182 if (function_exists('cups_get_dest_list')){
1183 $dest_list= cups_get_dest_list ($cups_server);
1185 foreach ($dest_list as $prt){
1186 $attr= cups_get_printer_attributes ($cups_server, $prt->name);
1188 foreach ($attr as $prt_info){
1189 if ($prt_info->name == "printer-info"){
1190 $info= $prt_info->value;
1191 break;
1192 }
1193 }
1194 $res[$prt->name]= "$info [$prt->name]";
1195 }
1197 /* CUPS is not available, try lpstat as a replacement */
1198 } else {
1199 $ar = false;
1200 exec("lpstat -p", $ar);
1201 foreach($ar as $val){
1202 @list($dummy, $printer, $rest)= split(' ', $val, 3);
1203 if (preg_match('/^[^@]+$/', $printer)){
1204 $res[$printer]= "$printer";
1205 }
1206 }
1207 }
1209 /* Merge in printers from LDAP */
1210 $ldap= $config->get_ldap_link();
1211 $ldap->cd ($config->current['BASE']);
1212 $ldap->search('(objectClass=gotoPrinter)', array('cn'));
1213 while ($attrs= $ldap->fetch()){
1214 $res[$attrs["cn"][0]]= $attrs["cn"][0];
1215 }
1217 return $res;
1218 }
1221 function sess_del ($var)
1222 {
1223 /* New style */
1224 unset ($_SESSION[$var]);
1226 /* ... work around, since the first one
1227 doesn't seem to work all the time */
1228 session_unregister ($var);
1229 }
1232 function show_errors($message)
1233 {
1234 $complete= "";
1236 /* Assemble the message array to a plain string */
1237 foreach ($message as $error){
1238 if ($complete == ""){
1239 $complete= $error;
1240 } else {
1241 $complete= "$error<br>$complete";
1242 }
1243 }
1245 /* Fill ERROR variable with nice error dialog */
1246 print_red($complete);
1247 }
1250 function show_ldap_error($message, $addon= "")
1251 {
1252 if (!preg_match("/Success/i", $message)){
1253 if ($addon == ""){
1254 print_red (_("LDAP error: $message"));
1255 } else {
1256 print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1257 }
1258 return TRUE;
1259 } else {
1260 return FALSE;
1261 }
1262 }
1265 function rewrite($s)
1266 {
1267 global $REWRITE;
1269 foreach ($REWRITE as $key => $val){
1270 $s= preg_replace("/$key/", "$val", $s);
1271 }
1273 return ($s);
1274 }
1277 function dn2base($dn)
1278 {
1279 global $config;
1281 if (get_people_ou() != ""){
1282 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1283 }
1284 if (get_groups_ou() != ""){
1285 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1286 }
1287 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1289 return ($base);
1290 }
1294 function check_command($cmdline)
1295 {
1296 $cmd= preg_replace("/ .*$/", "", $cmdline);
1298 /* Check if command exists in filesystem */
1299 if (!file_exists($cmd)){
1300 return (FALSE);
1301 }
1303 /* Check if command is executable */
1304 if (!is_executable($cmd)){
1305 return (FALSE);
1306 }
1308 return (TRUE);
1309 }
1312 function print_header($image, $headline, $info= "")
1313 {
1314 $display= "<div class=\"plugtop\">\n";
1315 $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";
1316 $display.= "</div>\n";
1318 if ($info != ""){
1319 $display.= "<div class=\"pluginfo\">\n";
1320 $display.= "$info";
1321 $display.= "</div>\n";
1322 } else {
1323 $display.= "<div style=\"height:5px;\">\n";
1324 $display.= " ";
1325 $display.= "</div>\n";
1326 }
1327 if (isset($_SESSION['errors'])){
1328 $display.= $_SESSION['errors'];
1329 }
1331 return ($display);
1332 }
1335 function register_global($name, $object)
1336 {
1337 $_SESSION[$name]= $object;
1338 }
1341 function is_global($name)
1342 {
1343 return isset($_SESSION[$name]);
1344 }
1347 function get_global($name)
1348 {
1349 return $_SESSION[$name];
1350 }
1353 function range_selector($dcnt,$start,$range=25,$post_var=false)
1354 {
1356 /* Entries shown left and right from the selected entry */
1357 $max_entries= 10;
1359 /* Initialize and take care that max_entries is even */
1360 $output="";
1361 if ($max_entries & 1){
1362 $max_entries++;
1363 }
1365 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1366 $range= $_POST[$post_var];
1367 }
1369 /* Prevent output to start or end out of range */
1370 if ($start < 0 ){
1371 $start= 0 ;
1372 }
1373 if ($start >= $dcnt){
1374 $start= $range * (int)(($dcnt / $range) + 0.5);
1375 }
1377 $numpages= (($dcnt / $range));
1378 if(((int)($numpages))!=($numpages)){
1379 $numpages = (int)$numpages + 1;
1380 }
1381 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1382 return ("");
1383 }
1384 $ppage= (int)(($start / $range) + 0.5);
1387 /* Align selected page to +/- max_entries/2 */
1388 $begin= $ppage - $max_entries/2;
1389 $end= $ppage + $max_entries/2;
1391 /* Adjust begin/end, so that the selected value is somewhere in
1392 the middle and the size is max_entries if possible */
1393 if ($begin < 0){
1394 $end-= $begin + 1;
1395 $begin= 0;
1396 }
1397 if ($end > $numpages) {
1398 $end= $numpages;
1399 }
1400 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1401 $begin= $end - $max_entries;
1402 }
1404 if($post_var){
1405 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1406 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1407 }else{
1408 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1409 }
1411 /* Draw decrement */
1412 if ($start > 0 ) {
1413 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1414 (($start-$range))."\">".
1415 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1416 }
1418 /* Draw pages */
1419 for ($i= $begin; $i < $end; $i++) {
1420 if ($ppage == $i){
1421 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1422 validate($_GET['plug'])."&start=".
1423 ($i*$range)."\"> ".($i+1)." </a>";
1424 } else {
1425 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1426 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1427 }
1428 }
1430 /* Draw increment */
1431 if($start < ($dcnt-$range)) {
1432 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1433 (($start+($range)))."\">".
1434 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1435 }
1437 if(($post_var)&&($numpages)){
1438 $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()'>";
1439 foreach(array(20,50,100,200,"all") as $num){
1440 if($num == "all"){
1441 $var = 10000;
1442 }else{
1443 $var = $num;
1444 }
1445 if($var == $range){
1446 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1447 }else{
1448 $output.="\n<option value='".$var."'>".$num."</option>";
1449 }
1450 }
1451 $output.= "</select></td></tr></table></div>";
1452 }else{
1453 $output.= "</div>";
1454 }
1456 return($output);
1457 }
1460 function apply_filter()
1461 {
1462 $apply= "";
1464 $apply= ''.
1465 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1466 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1468 return ($apply);
1469 }
1472 function back_to_main()
1473 {
1474 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1475 _("Back").'"></p><input type="hidden" name="ignore">';
1477 return ($string);
1478 }
1481 function normalize_netmask($netmask)
1482 {
1483 /* Check for notation of netmask */
1484 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1485 $num= (int)($netmask);
1486 $netmask= "";
1488 for ($byte= 0; $byte<4; $byte++){
1489 $result=0;
1491 for ($i= 7; $i>=0; $i--){
1492 if ($num-- > 0){
1493 $result+= pow(2,$i);
1494 }
1495 }
1497 $netmask.= $result.".";
1498 }
1500 return (preg_replace('/\.$/', '', $netmask));
1501 }
1503 return ($netmask);
1504 }
1507 function netmask_to_bits($netmask)
1508 {
1509 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1510 $res= 0;
1512 for ($n= 0; $n<4; $n++){
1513 $start= 255;
1514 $name= "nm$n";
1516 for ($i= 0; $i<8; $i++){
1517 if ($start == (int)($$name)){
1518 $res+= 8 - $i;
1519 break;
1520 }
1521 $start-= pow(2,$i);
1522 }
1523 }
1525 return ($res);
1526 }
1529 function recurse($rule, $variables)
1530 {
1531 $result= array();
1533 if (!count($variables)){
1534 return array($rule);
1535 }
1537 reset($variables);
1538 $key= key($variables);
1539 $val= current($variables);
1540 unset ($variables[$key]);
1542 foreach($val as $possibility){
1543 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1544 $result= array_merge($result, recurse($nrule, $variables));
1545 }
1547 return ($result);
1548 }
1551 function expand_id($rule, $attributes)
1552 {
1553 /* Check for id rule */
1554 if(preg_match('/^id(:|#)\d+$/',$rule)){
1555 return (array("\{$rule}"));
1556 }
1558 /* Check for clean attribute */
1559 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1560 $rule= preg_replace('/^%/', '', $rule);
1561 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1562 return (array($val));
1563 }
1565 /* Check for attribute with parameters */
1566 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1567 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1568 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1569 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1570 $start= preg_replace ('/-.*$/', '', $param);
1571 $stop = preg_replace ('/^[^-]+-/', '', $param);
1573 /* Assemble results */
1574 $result= array();
1575 for ($i= $start; $i<= $stop; $i++){
1576 $result[]= substr($val, 0, $i);
1577 }
1578 return ($result);
1579 }
1581 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1582 return (array($rule));
1583 }
1586 function gen_uids($rule, $attributes)
1587 {
1588 global $config;
1590 /* Search for keys and fill the variables array with all
1591 possible values for that key. */
1592 $part= "";
1593 $trigger= false;
1594 $stripped= "";
1595 $variables= array();
1597 for ($pos= 0; $pos < strlen($rule); $pos++){
1599 if ($rule[$pos] == "{" ){
1600 $trigger= true;
1601 $part= "";
1602 continue;
1603 }
1605 if ($rule[$pos] == "}" ){
1606 $variables[$pos]= expand_id($part, $attributes);
1607 $stripped.= "\{$pos}";
1608 $trigger= false;
1609 continue;
1610 }
1612 if ($trigger){
1613 $part.= $rule[$pos];
1614 } else {
1615 $stripped.= $rule[$pos];
1616 }
1617 }
1619 /* Recurse through all possible combinations */
1620 $proposed= recurse($stripped, $variables);
1622 /* Get list of used ID's */
1623 $used= array();
1624 $ldap= $config->get_ldap_link();
1625 $ldap->cd($config->current['BASE']);
1626 $ldap->search('(uid=*)');
1628 while($attrs= $ldap->fetch()){
1629 $used[]= $attrs['uid'][0];
1630 }
1632 /* Remove used uids and watch out for id tags */
1633 $ret= array();
1634 foreach($proposed as $uid){
1636 /* Check for id tag and modify uid if needed */
1637 if(preg_match('/\{id:\d+}/',$uid)){
1638 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1640 for ($i= 0; $i < pow(10,$size); $i++){
1641 $number= sprintf("%0".$size."d", $i);
1642 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1643 if (!in_array($res, $used)){
1644 $uid= $res;
1645 break;
1646 }
1647 }
1648 }
1650 if(preg_match('/\{id#\d+}/',$uid)){
1651 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1653 while (true){
1654 mt_srand((double) microtime()*1000000);
1655 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1656 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1657 if (!in_array($res, $used)){
1658 $uid= $res;
1659 break;
1660 }
1661 }
1662 }
1664 /* Don't assign used ones */
1665 if (!in_array($uid, $used)){
1666 $ret[]= $uid;
1667 }
1668 }
1670 return(array_unique($ret));
1671 }
1674 function array_search_r($needle, $key, $haystack){
1676 foreach($haystack as $index => $value){
1677 $match= 0;
1679 if (is_array($value)){
1680 $match= array_search_r($needle, $key, $value);
1681 }
1683 if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1684 $match=1;
1685 }
1687 if ($match){
1688 return 1;
1689 }
1690 }
1692 return 0;
1693 }
1696 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1697 Need to convert... */
1698 function to_byte($value) {
1699 $value= strtolower(trim($value));
1701 if(!is_numeric(substr($value, -1))) {
1703 switch(substr($value, -1)) {
1704 case 'g':
1705 $mult= 1073741824;
1706 break;
1707 case 'm':
1708 $mult= 1048576;
1709 break;
1710 case 'k':
1711 $mult= 1024;
1712 break;
1713 }
1715 return ($mult * (int)substr($value, 0, -1));
1716 } else {
1717 return $value;
1718 }
1719 }
1722 function in_array_ics($value, $items)
1723 {
1724 if (!is_array($items)){
1725 return (FALSE);
1726 }
1728 foreach ($items as $item){
1729 if (strtolower($item) == strtolower($value)) {
1730 return (TRUE);
1731 }
1732 }
1734 return (FALSE);
1735 }
1738 function generate_alphabet($count= 10)
1739 {
1740 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1741 $alphabet= "";
1742 $c= 0;
1744 /* Fill cells with charaters */
1745 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1746 if ($c == 0){
1747 $alphabet.= "<tr>";
1748 }
1750 $ch = mb_substr($characters, $i, 1, "UTF8");
1751 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1752 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1754 if ($c++ == $count){
1755 $alphabet.= "</tr>";
1756 $c= 0;
1757 }
1758 }
1760 /* Fill remaining cells */
1761 while ($c++ <= $count){
1762 $alphabet.= "<td> </td>";
1763 }
1765 return ($alphabet);
1766 }
1769 function validate($string)
1770 {
1771 return (strip_tags(preg_replace('/\0/', '', $string)));
1772 }
1774 function get_gosa_version()
1775 {
1776 global $svn_revision, $svn_path;
1778 /* Extract informations */
1779 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1781 /* Release or development? */
1782 if (preg_match('%/gosa/trunk/%', $svn_path)){
1783 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1784 } else {
1785 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1786 return (sprintf(_("GOsa $release"), $revision));
1787 }
1788 }
1791 function rmdirRecursive($path, $followLinks=false) {
1792 $dir= opendir($path);
1793 while($entry= readdir($dir)) {
1794 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1795 unlink($path."/".$entry);
1796 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1797 rmdirRecursive($path."/".$entry);
1798 }
1799 }
1800 closedir($dir);
1801 return rmdir($path);
1802 }
1804 function scan_directory($path,$sort_desc=false)
1805 {
1806 $ret = false;
1808 /* is this a dir ? */
1809 if(is_dir($path)) {
1811 /* is this path a readable one */
1812 if(is_readable($path)){
1814 /* Get contents and write it into an array */
1815 $ret = array();
1817 $dir = opendir($path);
1819 /* Is this a correct result ?*/
1820 if($dir){
1821 while($fp = readdir($dir))
1822 $ret[]= $fp;
1823 }
1824 }
1825 }
1826 /* Sort array ascending , like scandir */
1827 sort($ret);
1829 /* Sort descending if parameter is sort_desc is set */
1830 if($sort_desc) {
1831 $ret = array_reverse($ret);
1832 }
1834 return($ret);
1835 }
1837 function clean_smarty_compile_dir($directory)
1838 {
1839 global $svn_revision;
1841 if(is_dir($directory) && is_readable($directory)) {
1842 // Set revision filename to REVISION
1843 $revision_file= $directory."/REVISION";
1845 /* Is there a stamp containing the current revision? */
1846 if(!file_exists($revision_file)) {
1847 // create revision file
1848 create_revision($revision_file, $svn_revision);
1849 } else {
1850 # check for "$config->...['CONFIG']/revision" and the
1851 # contents should match the revision number
1852 if(!compare_revision($revision_file, $svn_revision)){
1853 // If revision differs, clean compile directory
1854 foreach(scan_directory($directory) as $file) {
1855 if(($file==".")||($file=="..")) continue;
1856 if( is_file($directory."/".$file) &&
1857 is_writable($directory."/".$file)) {
1858 // delete file
1859 if(!unlink($directory."/".$file)) {
1860 print_red("File ".$directory."/".$file." could not be deleted.");
1861 // This should never be reached
1862 }
1863 } elseif(is_dir($directory."/".$file) &&
1864 is_writable($directory."/".$file)) {
1865 // Just recursively delete it
1866 rmdirRecursive($directory."/".$file);
1867 }
1868 }
1869 // We should now create a fresh revision file
1870 clean_smarty_compile_dir($directory);
1871 } else {
1872 // Revision matches, nothing to do
1873 }
1874 }
1875 } else {
1876 // Smarty compile dir is not accessible
1877 // (Smarty will warn about this)
1878 }
1879 }
1881 function create_revision($revision_file, $revision)
1882 {
1883 $result= false;
1885 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1886 if($fh= fopen($revision_file, "w")) {
1887 if(fwrite($fh, $revision)) {
1888 $result= true;
1889 }
1890 }
1891 fclose($fh);
1892 } else {
1893 print_red("Can not write to revision file");
1894 }
1896 return $result;
1897 }
1899 function compare_revision($revision_file, $revision)
1900 {
1901 // false means revision differs
1902 $result= false;
1904 if(file_exists($revision_file) && is_readable($revision_file)) {
1905 // Open file
1906 if($fh= fopen($revision_file, "r")) {
1907 // Compare File contents with current revision
1908 if($revision == fread($fh, filesize($revision_file))) {
1909 $result= true;
1910 }
1911 } else {
1912 print_red("Can not open revision file");
1913 }
1914 // Close file
1915 fclose($fh);
1916 }
1918 return $result;
1919 }
1921 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1922 {
1923 $str = ""; // Our return value will be saved in this var
1925 $color = dechex($percentage+150);
1926 $color2 = dechex(150 - $percentage);
1927 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1929 $progress = (int)(($percentage /100)*$width);
1931 /* Abort printing out percentage, if divs are to small */
1934 /* If theres a better solution for this, use it... */
1935 $str = "
1936 <div style=\" width:".($width)."px;
1937 height:".($height)."px;
1938 background-color:#000000;
1939 padding:1px;\">
1941 <div style=\" width:".($width)."px;
1942 background-color:#$bgcolor;
1943 height:".($height)."px;\">
1945 <div style=\" width:".$progress."px;
1946 height:".$height."px;
1947 background-color:#".$color2.$color2.$color."; \">";
1950 if(($height >10)&&($showvalue)){
1951 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1952 <b>".$percentage."%</b>
1953 </font>";
1954 }
1956 $str.= "</div></div></div>";
1958 return($str);
1959 }
1962 function array_key_ics($ikey, $items)
1963 {
1964 /* Gather keys, make them lowercase */
1965 $tmp= array();
1966 foreach ($items as $key => $value){
1967 $tmp[strtolower($key)]= $key;
1968 }
1970 if (isset($tmp[strtolower($ikey)])){
1971 return($tmp[strtolower($ikey)]);
1972 }
1974 return ("");
1975 }
1978 function search_config($arr, $name, $return)
1979 {
1980 if (is_array($arr)){
1981 foreach ($arr as $a){
1982 if (isset($a['CLASS']) &&
1983 strtolower($a['CLASS']) == strtolower($name)){
1985 if (isset($a[$return])){
1986 return ($a[$return]);
1987 } else {
1988 return ("");
1989 }
1990 } else {
1991 $res= search_config ($a, $name, $return);
1992 if ($res != ""){
1993 return $res;
1994 }
1995 }
1996 }
1997 }
1998 return ("");
1999 }
2002 function array_differs($src, $dst)
2003 {
2004 /* If the count is differing, the arrays differ */
2005 if (count ($src) != count ($dst)){
2006 return (TRUE);
2007 }
2009 /* So the count is the same - lets check the contents */
2010 $differs= FALSE;
2011 foreach($src as $value){
2012 if (!in_array($value, $dst)){
2013 $differs= TRUE;
2014 }
2015 }
2017 return ($differs);
2018 }
2021 function saveFilter($a_filter, $values)
2022 {
2023 if (isset($_POST['regexit'])){
2024 $a_filter["regex"]= $_POST['regexit'];
2026 foreach($values as $type){
2027 if (isset($_POST[$type])) {
2028 $a_filter[$type]= "checked";
2029 } else {
2030 $a_filter[$type]= "";
2031 }
2032 }
2033 }
2035 /* React on alphabet links if needed */
2036 if (isset($_GET['search'])){
2037 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2038 if ($s == "**"){
2039 $s= "*";
2040 }
2041 $a_filter['regex']= $s;
2042 }
2044 return ($a_filter);
2045 }
2048 /* Escape all preg_* relevant characters */
2049 function normalizePreg($input)
2050 {
2051 return (addcslashes($input, '[]()|/.*+-'));
2052 }
2055 /* Escape all LDAP filter relevant characters */
2056 function normalizeLdap($input)
2057 {
2058 return (addcslashes($input, '()|'));
2059 }
2062 /* Resturns the difference between to microtime() results in float */
2063 function get_MicroTimeDiff($start , $stop)
2064 {
2065 $a = split("\ ",$start);
2066 $b = split("\ ",$stop);
2068 $secs = $b[1] - $a[1];
2069 $msecs= $b[0] - $a[0];
2071 $ret = (float) ($secs+ $msecs);
2072 return($ret);
2073 }
2076 /* Check if the given department name is valid */
2077 function is_department_name_reserved($name,$base)
2078 {
2079 $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2080 preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2081 preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2082 $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2084 /* Check if name is one of the reserved names */
2085 if(in_array_ics($name,$reservedName)) {
2086 return(true);
2087 }
2089 /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2090 foreach($follwedNames as $key => $names){
2091 if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2092 return(true);
2093 }
2094 }
2095 return(false);
2096 }
2099 function get_base_dir()
2100 {
2101 global $BASE_DIR;
2103 return $BASE_DIR;
2104 }
2107 function obj_is_readable($dn, $object, $attribute)
2108 {
2109 global $ui;
2111 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2112 }
2115 function obj_is_writable($dn, $object, $attribute)
2116 {
2117 global $ui;
2119 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2120 }
2124 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2125 ?>