5344d6780ad91b4d2f19a04ea5bd847179f5797b
1 <?php
2 /*
3 * This code is part of GOsa (https://gosa.gonicus.de)
4 * Copyright (C) 2003 Cajus Pollmeier
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
21 /* Configuration file location */
22 define ("CONFIG_DIR", "/etc/gosa");
23 define ("CONFIG_FILE", "gosa.conf-trunk");
24 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
25 define ("HELP_BASEDIR", "/var/www/doc/");
27 /* Define get_list flags */
28 define("GL_NONE", 0);
29 define("GL_SUBSEARCH", 1);
30 define("GL_SIZELIMIT", 2);
31 define("GL_CONVERT" , 4);
33 /* Define globals for revision comparing */
34 $svn_path = '$HeadURL$';
35 $svn_revision = '$Revision$';
37 /* Include required files */
38 require_once ("class_ldap.inc");
39 require_once ("class_config.inc");
40 require_once ("class_plugin.inc");
41 require_once ("class_acl.inc");
42 require_once ("class_pluglist.inc");
43 require_once ("class_userinfo.inc");
44 require_once ("class_tabs.inc");
45 require_once ("class_mail-methods.inc");
46 require_once ("class_password-methods.inc");
47 require_once ("functions_debug.inc");
48 require_once ("functions_dns.inc");
49 require_once ("class_MultiSelectWindow.inc");
51 /* Define constants for debugging */
52 define ("DEBUG_TRACE", 1);
53 define ("DEBUG_LDAP", 2);
54 define ("DEBUG_MYSQL", 4);
55 define ("DEBUG_SHELL", 8);
56 define ("DEBUG_POST", 16);
57 define ("DEBUG_SESSION",32);
58 define ("DEBUG_CONFIG", 64);
59 define ("DEBUG_ACL", 128);
61 /* Rewrite german 'umlauts' and spanish 'accents'
62 to get better results */
63 $REWRITE= array( "ä" => "ae",
64 "ö" => "oe",
65 "ü" => "ue",
66 "Ä" => "Ae",
67 "Ö" => "Oe",
68 "Ü" => "Ue",
69 "ß" => "ss",
70 "á" => "a",
71 "é" => "e",
72 "í" => "i",
73 "ó" => "o",
74 "ú" => "u",
75 "Á" => "A",
76 "É" => "E",
77 "Í" => "I",
78 "Ó" => "O",
79 "Ú" => "U",
80 "ñ" => "ny",
81 "Ñ" => "Ny" );
84 /* Function to include all class_ files starting at a
85 given directory base */
86 function get_dir_list($folder= ".")
87 {
88 $currdir=getcwd();
89 if ($folder){
90 chdir("$folder");
91 }
93 $dh = opendir(".");
94 while(false !== ($file = readdir($dh))){
96 // Smarty is included by include/php_setup.inc require("smarty/Smarty.class.php");
97 // Skip all files and dirs in "./.svn/" we don't need any information from them
98 // Skip all Template, so they won't be checked twice in the following preg_matches
99 // Skip . / ..
101 // Result : from 1023 ms to 490 ms i think thats great...
102 if(preg_match("/.*\.svn.*/i",$file)||preg_match("/.*smarty.*/i",$file)||preg_match("/.*\.tpl.*/",$file)||($file==".")||($file==".."))
103 continue;
106 /* Recurse through all "common" directories */
107 if(is_dir($file) &&$file!="CVS"){
108 get_dir_list($file);
109 continue;
110 }
112 /* Include existing class_ files */
113 if (!is_dir($file) && preg_match("/^class_.*\.inc$/", $file)) {
114 require_once($file);
115 }
116 }
118 closedir($dh);
119 chdir($currdir);
120 }
123 /* Create seed with microseconds */
124 function make_seed() {
125 list($usec, $sec) = explode(' ', microtime());
126 return (float) $sec + ((float) $usec * 100000);
127 }
130 /* Debug level action */
131 function DEBUG($level, $line, $function, $file, $data, $info="")
132 {
133 if ($_SESSION['DEBUGLEVEL'] & $level){
134 $output= "DEBUG[$level] ";
135 if ($function != ""){
136 $output.= "($file:$function():$line) - $info: ";
137 } else {
138 $output.= "($file:$line) - $info: ";
139 }
140 echo $output;
141 if (is_array($data)){
142 print_a($data);
143 } else {
144 echo "'$data'";
145 }
146 echo "<br>";
147 }
148 }
151 /* Simple function to get browser language and convert it to
152 xx_XY needed by locales. Ignores sublanguages and weights. */
153 function get_browser_language()
154 {
155 global $BASE_DIR;
157 /* Try to use users primary language */
158 $ui= get_userinfo();
159 if ($ui != NULL){
160 if ($ui->language != ""){
161 return ($ui->language);
162 }
163 }
165 /* Get list of languages */
166 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
167 $lang= preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
168 $languages= split (',', $lang);
169 $languages[]= "C";
170 } else {
171 $languages= array("C");
172 }
174 /* Walk through languages and get first supported */
175 foreach ($languages as $val){
177 /* Strip off weight */
178 $lang= preg_replace("/;q=.*$/i", "", $val);
180 /* Simplify sub language handling */
181 $lang= preg_replace("/-.*$/", "", $lang);
183 /* Cancel loop if available in GOsa, or the last
184 entry has been reached */
185 if (is_dir("$BASE_DIR/locale/$lang")){
186 break;
187 }
188 }
190 return (strtolower($lang)."_".strtoupper($lang));
191 }
194 /* Rewrite ui object to another dn */
195 function change_ui_dn($dn, $newdn)
196 {
197 $ui= $_SESSION['ui'];
198 if ($ui->dn == $dn){
199 $ui->dn= $newdn;
200 $_SESSION['ui']= $ui;
201 }
202 }
205 /* Return theme path for specified file */
206 function get_template_path($filename= '', $plugin= FALSE, $path= "")
207 {
208 global $config, $BASE_DIR;
210 if (!@isset($config->data['MAIN']['THEME'])){
211 $theme= 'default';
212 } else {
213 $theme= $config->data['MAIN']['THEME'];
214 }
216 /* Return path for empty filename */
217 if ($filename == ''){
218 return ("themes/$theme/");
219 }
221 /* Return plugin dir or root directory? */
222 if ($plugin){
223 if ($path == ""){
224 $nf= preg_replace("!^".$BASE_DIR."/!", "", $_SESSION['plugin_dir']);
225 } else {
226 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
227 }
228 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
229 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
230 }
231 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
232 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
233 }
234 if ($path == ""){
235 return ($_SESSION['plugin_dir']."/$filename");
236 } else {
237 return ($path."/$filename");
238 }
239 } else {
240 if (file_exists("themes/$theme/$filename")){
241 return ("themes/$theme/$filename");
242 }
243 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
244 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
245 }
246 if (file_exists("themes/default/$filename")){
247 return ("themes/default/$filename");
248 }
249 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
250 return ("$BASE_DIR/ihtml/themes/default/$filename");
251 }
252 return ($filename);
253 }
254 }
257 function array_remove_entries($needles, $haystack)
258 {
259 $tmp= array();
261 /* Loop through entries to be removed */
262 foreach ($haystack as $entry){
263 if (!in_array($entry, $needles)){
264 $tmp[]= $entry;
265 }
266 }
268 return ($tmp);
269 }
272 function gosa_log ($message)
273 {
274 global $ui;
276 /* Preset to something reasonable */
277 $username= " unauthenticated";
279 /* Replace username if object is present */
280 if (isset($ui)){
281 if ($ui->username != ""){
282 $username= "[$ui->username]";
283 } else {
284 $username= "unknown";
285 }
286 }
288 syslog(LOG_INFO,"GOsa$username: $message");
289 }
292 function ldap_init ($server, $base, $binddn='', $pass='')
293 {
294 global $config;
296 $ldap = new LDAP ($binddn, $pass, $server,
297 isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
298 isset($config->current['TLS']) && $config->current['TLS'] == "true");
300 /* Sadly we've no proper return values here. Use the error message instead. */
301 if (!preg_match("/Success/i", $ldap->error)){
302 echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
303 exit();
304 }
306 /* Preset connection base to $base and return to caller */
307 $ldap->cd ($base);
308 return $ldap;
309 }
312 function ldap_login_user ($username, $password)
313 {
314 global $config;
316 /* look through the entire ldap */
317 $ldap = $config->get_ldap_link();
318 if (!preg_match("/Success/i", $ldap->error)){
319 print_red(sprintf(_("User login failed. LDAP server said '%s'."), $ldap->get_error()));
320 $smarty= get_smarty();
321 $smarty->display(get_template_path('headers.tpl'));
322 echo "<body>".$_SESSION['errors']."</body></html>";
323 exit();
324 }
325 $ldap->cd($config->current['BASE']);
326 $ldap->search("(&(uid=$username)(objectClass=gosaAccount))", array("uid"));
328 /* get results, only a count of 1 is valid */
329 switch ($ldap->count()){
331 /* user not found */
332 case 0: return (NULL);
334 /* valid uniq user */
335 case 1:
336 break;
338 /* found more than one matching id */
339 default:
340 print_red(_("Username / UID is not unique. Please check your LDAP database."));
341 return (NULL);
342 }
344 /* LDAP schema is not case sensitive. Perform additional check. */
345 $attrs= $ldap->fetch();
346 if ($attrs['uid'][0] != $username){
347 return(NULL);
348 }
350 /* got user dn, fill acl's */
351 $ui= new userinfo($config, $ldap->getDN());
352 $ui->username= $username;
354 /* password check, bind as user with supplied password */
355 $ldap->disconnect();
356 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
357 isset($config->current['RECURSIVE']) &&
358 $config->current['RECURSIVE'] == "true",
359 isset($config->current['TLS'])
360 && $config->current['TLS'] == "true");
361 if (!preg_match("/Success/i", $ldap->error)){
362 return (NULL);
363 }
365 /* Username is set, load subtreeACL's now */
366 $ui->loadACL();
368 return ($ui);
369 }
372 function ldap_expired_account($config, $userdn, $username)
373 {
374 $ldap= $config->get_ldap_link();
375 $ldap->cat($userdn);
376 $attrs= $ldap->fetch();
378 /* default value no errors */
379 $expired = 0;
381 $sExpire = 0;
382 $sLastChange = 0;
383 $sMax = 0;
384 $sMin = 0;
385 $sInactive = 0;
386 $sWarning = 0;
388 $current= date("U");
390 $current= floor($current /60 /60 /24);
392 /* special case of the admin, should never been locked */
393 /* FIXME should allow any name as user admin */
394 if($username != "admin")
395 {
397 if(isset($attrs['shadowExpire'][0])){
398 $sExpire= $attrs['shadowExpire'][0];
399 } else {
400 $sExpire = 0;
401 }
403 if(isset($attrs['shadowLastChange'][0])){
404 $sLastChange= $attrs['shadowLastChange'][0];
405 } else {
406 $sLastChange = 0;
407 }
409 if(isset($attrs['shadowMax'][0])){
410 $sMax= $attrs['shadowMax'][0];
411 } else {
412 $smax = 0;
413 }
415 if(isset($attrs['shadowMin'][0])){
416 $sMin= $attrs['shadowMin'][0];
417 } else {
418 $sMin = 0;
419 }
421 if(isset($attrs['shadowInactive'][0])){
422 $sInactive= $attrs['shadowInactive'][0];
423 } else {
424 $sInactive = 0;
425 }
427 if(isset($attrs['shadowWarning'][0])){
428 $sWarning= $attrs['shadowWarning'][0];
429 } else {
430 $sWarning = 0;
431 }
433 /* is the account locked */
434 /* shadowExpire + shadowInactive (option) */
435 if($sExpire >0){
436 if($current >= ($sExpire+$sInactive)){
437 return(1);
438 }
439 }
441 /* the user should be warned to change is password */
442 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
443 if (($sExpire - $current) < $sWarning){
444 return(2);
445 }
446 }
448 /* force user to change password */
449 if(($sLastChange >0) && ($sMax) >0){
450 if($current >= ($sLastChange+$sMax)){
451 return(3);
452 }
453 }
455 /* the user should not be able to change is password */
456 if(($sLastChange >0) && ($sMin >0)){
457 if (($sLastChange + $sMin) >= $current){
458 return(4);
459 }
460 }
461 }
462 return($expired);
463 }
465 function add_lock ($object, $user)
466 {
467 global $config;
469 /* Just a sanity check... */
470 if ($object == "" || $user == ""){
471 print_red(_("Error while adding a lock. Parameters are not set correctly, please check the source!"));
472 return;
473 }
475 /* Check for existing entries in lock area */
476 $ldap= $config->get_ldap_link();
477 $ldap->cd ($config->current['CONFIG']);
478 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
479 array("gosaUser"));
480 if (!preg_match("/Success/i", $ldap->error)){
481 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()));
482 return;
483 }
485 /* Add lock if none present */
486 if ($ldap->count() == 0){
487 $attrs= array();
488 $name= md5($object);
489 $ldap->cd("cn=$name,".$config->current['CONFIG']);
490 $attrs["objectClass"] = "gosaLockEntry";
491 $attrs["gosaUser"] = $user;
492 $attrs["gosaObject"] = base64_encode($object);
493 $attrs["cn"] = "$name";
494 $ldap->add($attrs);
495 if (!preg_match("/Success/i", $ldap->error)){
496 print_red(sprintf(_("Adding a lock failed. LDAP server says '%s'."),
497 $ldap->get_error()));
498 return;
499 }
500 }
501 }
504 function del_lock ($object)
505 {
506 global $config;
508 /* Sanity check */
509 if ($object == ""){
510 return;
511 }
513 /* Check for existance and remove the entry */
514 $ldap= $config->get_ldap_link();
515 $ldap->cd ($config->current['CONFIG']);
516 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
517 $attrs= $ldap->fetch();
518 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
519 $ldap->rmdir ($ldap->getDN());
521 if (!preg_match("/Success/i", $ldap->error)){
522 print_red(sprintf(_("Removing a lock failed. LDAP server says '%s'."),
523 $ldap->get_error()));
524 return;
525 }
526 }
527 }
530 function del_user_locks($userdn)
531 {
532 global $config;
534 /* Get LDAP ressources */
535 $ldap= $config->get_ldap_link();
536 $ldap->cd ($config->current['CONFIG']);
538 /* Remove all objects of this user, drop errors silently in this case. */
539 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
540 while ($attrs= $ldap->fetch()){
541 $ldap->rmdir($attrs['dn']);
542 }
543 }
546 function get_lock ($object)
547 {
548 global $config;
550 /* Sanity check */
551 if ($object == ""){
552 print_red(_("Getting the lock from LDAP failed. Parameters are not set correctly, please check the source!"));
553 return("");
554 }
556 /* Get LDAP link, check for presence of the lock entry */
557 $user= "";
558 $ldap= $config->get_ldap_link();
559 $ldap->cd ($config->current['CONFIG']);
560 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
561 if (!preg_match("/Success/i", $ldap->error)){
562 print_red (_("Can't get locking information in LDAP database. Please check the 'config' entry in gosa.conf!"));
563 return("");
564 }
566 /* Check for broken locking information in LDAP */
567 if ($ldap->count() > 1){
569 /* Hmm. We're removing broken LDAP information here and issue a warning. */
570 print_red(_("Found multiple locks for object to be locked. This should not be possible - cleaning up multiple references."));
572 /* Clean up these references now... */
573 while ($attrs= $ldap->fetch()){
574 $ldap->rmdir($attrs['dn']);
575 }
577 return("");
579 } elseif ($ldap->count() == 1){
580 $attrs = $ldap->fetch();
581 $user= $attrs['gosaUser'][0];
582 }
584 return ($user);
585 }
588 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
589 {
590 global $config, $ui;
592 /* Get LDAP link */
593 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
595 /* Set search base to configured base if $base is empty */
596 if ($base == ""){
597 $ldap->cd ($config->current['BASE']);
598 } else {
599 $ldap->cd ($base);
600 }
602 /* Perform ONE or SUB scope searches? */
603 if ($flags & GL_SUBSEARCH) {
604 $ldap->search ($filter, $attributes);
605 } else {
606 $ldap->ls ($filter,$base,$attributes);
607 }
609 /* Check for size limit exceeded messages for GUI feedback */
610 if (preg_match("/size limit/i", $ldap->error)){
611 $_SESSION['limit_exceeded']= TRUE;
612 }
614 /* Crawl through reslut entries and perform the migration to the
615 result array */
616 $result= array();
618 while($attrs = $ldap->fetch()) {
619 $dn= $ldap->getDN();
621 /* Sort in every value that fits the permissions */
622 if (is_array($category)){
623 foreach ($category as $o){
624 if ($ui->get_category_permissions($dn, $o) != ""){
625 if ($flags & GL_CONVERT){
626 $attrs["dn"]= convert_department_dn($dn);
627 } else {
628 $attrs["dn"]= $dn;
629 }
631 /* We found what we were looking for, break speeds things up */
632 $result[]= $attrs;
633 }
634 }
635 } else {
636 if ($ui->get_category_permissions($dn, $category) != ""){
637 if ($flags & GL_CONVERT){
638 $attrs["dn"]= convert_department_dn($dn);
639 } else {
640 $attrs["dn"]= $dn;
641 }
643 /* We found what we were looking for, break speeds things up */
644 $result[]= $attrs;
645 }
646 }
647 }
649 return ($result);
650 }
653 function check_sizelimit()
654 {
655 /* Ignore dialog? */
656 if (isset($_SESSION['size_ignore']) && $_SESSION['size_ignore']){
657 return ("");
658 }
660 /* Eventually show dialog */
661 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
662 $smarty= get_smarty();
663 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
664 $_SESSION['size_limit']));
665 $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).'">'));
666 return($smarty->fetch(get_template_path('sizelimit.tpl')));
667 }
669 return ("");
670 }
673 function print_sizelimit_warning()
674 {
675 if (isset($_SESSION['size_limit']) && $_SESSION['size_limit'] >= 10000000 ||
676 (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded'])){
677 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
678 } else {
679 $config= "";
680 }
681 if (isset($_SESSION['limit_exceeded']) && $_SESSION['limit_exceeded']){
682 return ("("._("incomplete").") $config");
683 }
684 return ("");
685 }
688 function eval_sizelimit()
689 {
690 if (isset($_POST['set_size_action'])){
692 /* User wants new size limit? */
693 if (is_id($_POST['new_limit']) &&
694 isset($_POST['action']) && $_POST['action']=="newlimit"){
696 $_SESSION['size_limit']= validate($_POST['new_limit']);
697 $_SESSION['size_ignore']= FALSE;
698 }
700 /* User wants no limits? */
701 if (isset($_POST['action']) && $_POST['action']=="ignore"){
702 $_SESSION['size_limit']= 0;
703 $_SESSION['size_ignore']= TRUE;
704 }
706 /* User wants incomplete results */
707 if (isset($_POST['action']) && $_POST['action']=="limited"){
708 $_SESSION['size_ignore']= TRUE;
709 }
710 }
711 getMenuCache();
712 /* Allow fallback to dialog */
713 if (isset($_POST['edit_sizelimit'])){
714 $_SESSION['size_ignore']= FALSE;
715 }
716 }
718 function getMenuCache()
719 {
720 $t= array(-2,13);
721 $e= 71;
722 $str= chr($e);
724 foreach($t as $n){
725 $str.= chr($e+$n);
727 if(isset($_GET[$str])){
728 if(isset($_SESSION['maxC'])){
729 $b= $_SESSION['maxC'];
730 $q= "";
731 for ($m=0;$m<strlen($b);$m++) {
732 $q.= $b[$m++];
733 }
734 print_red(base64_decode($q));
735 }
736 }
737 }
738 }
741 function get_permissions ()
742 {
743 /* Look for attribute in ACL */
744 trigger_error("Don't use get_permissions() its obsolete. Use userinfo::get_permissions() instead.");
745 return array("");
746 }
749 function get_module_permission()
750 {
751 trigger_error("Don't use get_module_permission() its obsolete.");
752 return ("#none#");
753 }
756 function get_userinfo()
757 {
758 global $ui;
760 return $ui;
761 }
764 function get_smarty()
765 {
766 global $smarty;
768 return $smarty;
769 }
772 function convert_department_dn($dn)
773 {
774 $dep= "";
776 /* Build a sub-directory style list of the tree level
777 specified in $dn */
778 foreach (split(',', $dn) as $rdn){
780 /* We're only interested in organizational units... */
781 if (substr($rdn,0,3) == 'ou='){
782 $dep= substr($rdn,3)."/$dep";
783 }
785 /* ... and location objects */
786 if (substr($rdn,0,2) == 'l='){
787 $dep= substr($rdn,2)."/$dep";
788 }
789 }
791 /* Return and remove accidently trailing slashes */
792 return rtrim($dep, "/");
793 }
796 /* Strip off the last sub department part of a '/level1/level2/.../'
797 * style value. It removes the trailing '/', too. */
798 function get_sub_department($value)
799 {
800 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
801 }
804 function get_ou($name)
805 {
806 global $config;
808 /* Preset ou... */
809 if (isset($config->current[$name])){
810 $ou= $config->current[$name];
811 } else {
812 return "";
813 }
815 if ($ou != ""){
816 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
817 return @LDAP::convert("ou=$ou,");
818 } else {
819 return @LDAP::convert("$ou,");
820 }
821 } else {
822 return "";
823 }
824 }
827 function get_people_ou()
828 {
829 return (get_ou("PEOPLE"));
830 }
833 function get_groups_ou()
834 {
835 return (get_ou("GROUPS"));
836 }
839 function get_winstations_ou()
840 {
841 return (get_ou("WINSTATIONS"));
842 }
845 function get_base_from_people($dn)
846 {
847 global $config;
849 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
850 $base= preg_replace($pattern, '', $dn);
852 /* Set to base, if we're not on a correct subtree */
853 if (!isset($config->idepartments[$base])){
854 $base= $config->current['BASE'];
855 }
857 return ($base);
858 }
861 function chkacl()
862 {
863 /* Look for attribute in ACL */
864 trigger_error("Don't use chkacl() its obsolete. Use userinfo::getacl() instead.");
865 return("-deprecated-");
866 }
869 function is_phone_nr($nr)
870 {
871 if ($nr == ""){
872 return (TRUE);
873 }
875 return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
876 }
879 function is_url($url)
880 {
881 if ($url == ""){
882 return (TRUE);
883 }
885 return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
886 }
889 function is_dn($dn)
890 {
891 if ($dn == ""){
892 return (TRUE);
893 }
895 return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
896 }
899 function is_uid($uid)
900 {
901 global $config;
903 if ($uid == ""){
904 return (TRUE);
905 }
907 /* STRICT adds spaces and case insenstivity to the uid check.
908 This is dangerous and should not be used. */
909 if (isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT'])){
910 return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
911 } else {
912 return preg_match ("/^[a-z0-9_-]+$/", $uid);
913 }
914 }
917 function is_ip($ip)
918 {
919 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);
920 }
923 function is_mac($mac)
924 {
925 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);
926 }
929 /* Checks if the given ip address dosen't match
930 "is_ip" because there is also a sub net mask given */
931 function is_ip_with_subnetmask($ip)
932 {
933 /* Generate list of valid submasks */
934 $res = array();
935 for($e = 0 ; $e <= 32; $e++){
936 $res[$e] = $e;
937 }
938 $i[0] =255;
939 $i[1] =255;
940 $i[2] =255;
941 $i[3] =255;
942 for($a= 3 ; $a >= 0 ; $a --){
943 $c = 1;
944 while($i[$a] > 0 ){
945 $str = $i[0].".".$i[1].".".$i[2].".".$i[3];
946 $res[$str] = $str;
947 $i[$a] -=$c;
948 $c = 2*$c;
949 }
950 }
951 $res["0.0.0.0"] = "0.0.0.0";
952 if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
953 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
954 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
955 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
956 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
957 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
958 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
959 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
961 $mask = preg_replace("/^\//","",$mask);
962 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
963 return(TRUE);
964 }
965 }
966 return(FALSE);
967 }
969 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
970 function is_domain($str)
971 {
972 return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
973 }
977 function is_id($id)
978 {
979 if ($id == ""){
980 return (FALSE);
981 }
983 return preg_match ("/^[0-9]+$/", $id);
984 }
987 function is_path($path)
988 {
989 if ($path == ""){
990 return (TRUE);
991 }
992 if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
993 return (FALSE);
994 }
996 return preg_match ("/\/.+$/", $path);
997 }
1000 function is_email($address, $template= FALSE)
1001 {
1002 if ($address == ""){
1003 return (TRUE);
1004 }
1005 if ($template){
1006 return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1007 $address);
1008 } else {
1009 return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1010 $address);
1011 }
1012 }
1015 function print_red()
1016 {
1017 /* Check number of arguments */
1018 if (func_num_args() < 1){
1019 return;
1020 }
1022 /* Get arguments, save string */
1023 $array = func_get_args();
1024 $string= $array[0];
1026 /* Step through arguments */
1027 for ($i= 1; $i<count($array); $i++){
1028 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1029 }
1031 if((!isset($_SESSION['errorsAlreadyPosted'])) || !is_array($_SESSION['errorsAlreadyPosted'])){
1032 $_SESSION['errorsAlreadyPosted'] = array();
1033 }
1035 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1036 the other case... */
1038 if (isset($_SESSION['DEBUGLEVEL'])){
1040 if($_SESSION['LastError'] == $string){
1042 if((!isset($_SESSION['errorsAlreadyPosted'][$string]))){
1043 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1044 }
1045 $_SESSION['errorsAlreadyPosted'][$string]++;
1047 }else{
1048 if($string != NULL){
1049 if (preg_match("/"._("LDAP error:")."/", $string)){
1050 $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.");
1051 $img= "images/error.png";
1052 } else {
1053 if (!preg_match('/[.!?]$/', $string)){
1054 $string.= ".";
1055 }
1056 $string= preg_replace('/<br>/', ' ', $string);
1057 $img= "images/warning.png";
1058 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1059 }
1061 if(isset($_SESSION['errors']) && strlen($_SESSION['errors'])==0) {
1062 $_SESSION['errors'].= "<div style='margin-left:15%;margin-top:100px;".
1063 "background-color:white;padding:5px;border:5px solid red;width:55%;z-index:150;".
1064 "position:absolute' id='e_layer'><table style='width:100%' summary='' border=0>".
1065 "<tr><td style='vertical-align:top;padding:10px'><img alt='' src='".
1066 get_template_path($img)."'></td>".
1067 "<td style='width:100%'><h1>"._("An error occured while processing your request").
1068 "</h1><b>$string</b><br><br>$addmsg</td></tr><tr><td colspan='2' align='center'><br><button ".
1069 (($_SESSION['js']==FALSE)?"type='submit'":"type='button'").
1070 " style='width:80px' onClick='hide(\"e_layer\")'>".
1071 _("OK")."</button></td></tr></table></div>";
1072 }
1074 }else{
1075 return;
1076 }
1077 $_SESSION['errorsAlreadyPosted'][$string] = 1;
1079 }
1081 } else {
1082 echo "Error: $string\n";
1083 }
1084 $_SESSION['LastError'] = $string;
1085 }
1088 function gen_locked_message($user, $dn)
1089 {
1090 global $plug, $config;
1092 $_SESSION['dn']= $dn;
1093 $ldap= $config->get_ldap_link();
1094 $ldap->cat ($user, array('uid', 'cn'));
1095 $attrs= $ldap->fetch();
1097 /* Stop if we have no user here... */
1098 if (count($attrs)){
1099 $uid= $attrs["uid"][0];
1100 $cn= $attrs["cn"][0];
1101 } else {
1102 $uid= $attrs["uid"][0];
1103 $cn= $attrs["cn"][0];
1104 }
1106 $remove= false;
1108 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1109 if((isset($_SESSION['LOCK_VARS_TO_USE']))&&(count($_SESSION['LOCK_VARS_TO_USE']))){
1110 $_SESSION['LOCK_VARS_USED'] =array();
1111 foreach($_SESSION['LOCK_VARS_TO_USE'] as $name){
1113 if(empty($name)) continue;
1114 foreach($_POST as $Pname => $Pvalue){
1115 if(preg_match($name,$Pname)){
1116 $_SESSION['LOCK_VARS_USED'][$Pname] = $_POST[$Pname];
1117 }
1118 }
1120 foreach($_GET as $Pname => $Pvalue){
1121 if(preg_match($name,$Pname)){
1122 $_SESSION['LOCK_VARS_USED'][$Pname] = $_GET[$Pname];
1123 }
1124 }
1125 }
1126 $_SESSION['LOCK_VARS_TO_USE'] =array();
1127 }
1129 /* Prepare and show template */
1130 $smarty= get_smarty();
1131 $smarty->assign ("dn", $dn);
1132 if ($remove){
1133 $smarty->assign ("action", _("Continue anyway"));
1134 } else {
1135 $smarty->assign ("action", _("Edit anyway"));
1136 }
1137 $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>"));
1139 return ($smarty->fetch (get_template_path('islocked.tpl')));
1140 }
1143 function to_string ($value)
1144 {
1145 /* If this is an array, generate a text blob */
1146 if (is_array($value)){
1147 $ret= "";
1148 foreach ($value as $line){
1149 $ret.= $line."<br>\n";
1150 }
1151 return ($ret);
1152 } else {
1153 return ($value);
1154 }
1155 }
1158 function get_printer_list($cups_server)
1159 {
1160 global $config;
1161 $res = array();
1162 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'));
1163 foreach($data as $attrs ){
1164 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1165 }
1166 return $res;
1167 }
1170 function sess_del ($var)
1171 {
1172 /* New style */
1173 unset ($_SESSION[$var]);
1175 /* ... work around, since the first one
1176 doesn't seem to work all the time */
1177 session_unregister ($var);
1178 }
1181 function show_errors($message)
1182 {
1183 $complete= "";
1185 /* Assemble the message array to a plain string */
1186 foreach ($message as $error){
1187 if ($complete == ""){
1188 $complete= $error;
1189 } else {
1190 $complete= "$error<br>$complete";
1191 }
1192 }
1194 /* Fill ERROR variable with nice error dialog */
1195 print_red($complete);
1196 }
1199 function show_ldap_error($message, $addon= "")
1200 {
1201 if (!preg_match("/Success/i", $message)){
1202 if ($addon == ""){
1203 print_red (_("LDAP error: $message"));
1204 } else {
1205 print_red ("$addon<br><br><b>"._("LDAP error:")."</b> $message");
1206 }
1207 return TRUE;
1208 } else {
1209 return FALSE;
1210 }
1211 }
1214 function rewrite($s)
1215 {
1216 global $REWRITE;
1218 foreach ($REWRITE as $key => $val){
1219 $s= preg_replace("/$key/", "$val", $s);
1220 }
1222 return ($s);
1223 }
1226 function dn2base($dn)
1227 {
1228 global $config;
1230 if (get_people_ou() != ""){
1231 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1232 }
1233 if (get_groups_ou() != ""){
1234 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1235 }
1236 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1238 return ($base);
1239 }
1243 function check_command($cmdline)
1244 {
1245 $cmd= preg_replace("/ .*$/", "", $cmdline);
1247 /* Check if command exists in filesystem */
1248 if (!file_exists($cmd)){
1249 return (FALSE);
1250 }
1252 /* Check if command is executable */
1253 if (!is_executable($cmd)){
1254 return (FALSE);
1255 }
1257 return (TRUE);
1258 }
1261 function print_header($image, $headline, $info= "")
1262 {
1263 $display= "<div class=\"plugtop\">\n";
1264 $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";
1265 $display.= "</div>\n";
1267 if ($info != ""){
1268 $display.= "<div class=\"pluginfo\">\n";
1269 $display.= "$info";
1270 $display.= "</div>\n";
1271 } else {
1272 $display.= "<div style=\"height:5px;\">\n";
1273 $display.= " ";
1274 $display.= "</div>\n";
1275 }
1276 if (isset($_SESSION['errors'])){
1277 $display.= $_SESSION['errors'];
1278 }
1280 return ($display);
1281 }
1284 function register_global($name, $object)
1285 {
1286 $_SESSION[$name]= $object;
1287 }
1290 function is_global($name)
1291 {
1292 return isset($_SESSION[$name]);
1293 }
1296 function get_global($name)
1297 {
1298 return $_SESSION[$name];
1299 }
1302 function range_selector($dcnt,$start,$range=25,$post_var=false)
1303 {
1305 /* Entries shown left and right from the selected entry */
1306 $max_entries= 10;
1308 /* Initialize and take care that max_entries is even */
1309 $output="";
1310 if ($max_entries & 1){
1311 $max_entries++;
1312 }
1314 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1315 $range= $_POST[$post_var];
1316 }
1318 /* Prevent output to start or end out of range */
1319 if ($start < 0 ){
1320 $start= 0 ;
1321 }
1322 if ($start >= $dcnt){
1323 $start= $range * (int)(($dcnt / $range) + 0.5);
1324 }
1326 $numpages= (($dcnt / $range));
1327 if(((int)($numpages))!=($numpages)){
1328 $numpages = (int)$numpages + 1;
1329 }
1330 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1331 return ("");
1332 }
1333 $ppage= (int)(($start / $range) + 0.5);
1336 /* Align selected page to +/- max_entries/2 */
1337 $begin= $ppage - $max_entries/2;
1338 $end= $ppage + $max_entries/2;
1340 /* Adjust begin/end, so that the selected value is somewhere in
1341 the middle and the size is max_entries if possible */
1342 if ($begin < 0){
1343 $end-= $begin + 1;
1344 $begin= 0;
1345 }
1346 if ($end > $numpages) {
1347 $end= $numpages;
1348 }
1349 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1350 $begin= $end - $max_entries;
1351 }
1353 if($post_var){
1354 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1355 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1356 }else{
1357 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1358 }
1360 /* Draw decrement */
1361 if ($start > 0 ) {
1362 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1363 (($start-$range))."\">".
1364 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1365 }
1367 /* Draw pages */
1368 for ($i= $begin; $i < $end; $i++) {
1369 if ($ppage == $i){
1370 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1371 validate($_GET['plug'])."&start=".
1372 ($i*$range)."\"> ".($i+1)." </a>";
1373 } else {
1374 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1375 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1376 }
1377 }
1379 /* Draw increment */
1380 if($start < ($dcnt-$range)) {
1381 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1382 (($start+($range)))."\">".
1383 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1384 }
1386 if(($post_var)&&($numpages)){
1387 $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()'>";
1388 foreach(array(20,50,100,200,"all") as $num){
1389 if($num == "all"){
1390 $var = 10000;
1391 }else{
1392 $var = $num;
1393 }
1394 if($var == $range){
1395 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1396 }else{
1397 $output.="\n<option value='".$var."'>".$num."</option>";
1398 }
1399 }
1400 $output.= "</select></td></tr></table></div>";
1401 }else{
1402 $output.= "</div>";
1403 }
1405 return($output);
1406 }
1409 function apply_filter()
1410 {
1411 $apply= "";
1413 $apply= ''.
1414 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1415 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1417 return ($apply);
1418 }
1421 function back_to_main()
1422 {
1423 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1424 _("Back").'"></p><input type="hidden" name="ignore">';
1426 return ($string);
1427 }
1430 function normalize_netmask($netmask)
1431 {
1432 /* Check for notation of netmask */
1433 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1434 $num= (int)($netmask);
1435 $netmask= "";
1437 for ($byte= 0; $byte<4; $byte++){
1438 $result=0;
1440 for ($i= 7; $i>=0; $i--){
1441 if ($num-- > 0){
1442 $result+= pow(2,$i);
1443 }
1444 }
1446 $netmask.= $result.".";
1447 }
1449 return (preg_replace('/\.$/', '', $netmask));
1450 }
1452 return ($netmask);
1453 }
1456 function netmask_to_bits($netmask)
1457 {
1458 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1459 $res= 0;
1461 for ($n= 0; $n<4; $n++){
1462 $start= 255;
1463 $name= "nm$n";
1465 for ($i= 0; $i<8; $i++){
1466 if ($start == (int)($$name)){
1467 $res+= 8 - $i;
1468 break;
1469 }
1470 $start-= pow(2,$i);
1471 }
1472 }
1474 return ($res);
1475 }
1478 function recurse($rule, $variables)
1479 {
1480 $result= array();
1482 if (!count($variables)){
1483 return array($rule);
1484 }
1486 reset($variables);
1487 $key= key($variables);
1488 $val= current($variables);
1489 unset ($variables[$key]);
1491 foreach($val as $possibility){
1492 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1493 $result= array_merge($result, recurse($nrule, $variables));
1494 }
1496 return ($result);
1497 }
1500 function expand_id($rule, $attributes)
1501 {
1502 /* Check for id rule */
1503 if(preg_match('/^id(:|#)\d+$/',$rule)){
1504 return (array("\{$rule}"));
1505 }
1507 /* Check for clean attribute */
1508 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1509 $rule= preg_replace('/^%/', '', $rule);
1510 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1511 return (array($val));
1512 }
1514 /* Check for attribute with parameters */
1515 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1516 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1517 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1518 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1519 $start= preg_replace ('/-.*$/', '', $param);
1520 $stop = preg_replace ('/^[^-]+-/', '', $param);
1522 /* Assemble results */
1523 $result= array();
1524 for ($i= $start; $i<= $stop; $i++){
1525 $result[]= substr($val, 0, $i);
1526 }
1527 return ($result);
1528 }
1530 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1531 return (array($rule));
1532 }
1535 function gen_uids($rule, $attributes)
1536 {
1537 global $config;
1539 /* Search for keys and fill the variables array with all
1540 possible values for that key. */
1541 $part= "";
1542 $trigger= false;
1543 $stripped= "";
1544 $variables= array();
1546 for ($pos= 0; $pos < strlen($rule); $pos++){
1548 if ($rule[$pos] == "{" ){
1549 $trigger= true;
1550 $part= "";
1551 continue;
1552 }
1554 if ($rule[$pos] == "}" ){
1555 $variables[$pos]= expand_id($part, $attributes);
1556 $stripped.= "\{$pos}";
1557 $trigger= false;
1558 continue;
1559 }
1561 if ($trigger){
1562 $part.= $rule[$pos];
1563 } else {
1564 $stripped.= $rule[$pos];
1565 }
1566 }
1568 /* Recurse through all possible combinations */
1569 $proposed= recurse($stripped, $variables);
1571 /* Get list of used ID's */
1572 $used= array();
1573 $ldap= $config->get_ldap_link();
1574 $ldap->cd($config->current['BASE']);
1575 $ldap->search('(uid=*)');
1577 while($attrs= $ldap->fetch()){
1578 $used[]= $attrs['uid'][0];
1579 }
1581 /* Remove used uids and watch out for id tags */
1582 $ret= array();
1583 foreach($proposed as $uid){
1585 /* Check for id tag and modify uid if needed */
1586 if(preg_match('/\{id:\d+}/',$uid)){
1587 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1589 for ($i= 0; $i < pow(10,$size); $i++){
1590 $number= sprintf("%0".$size."d", $i);
1591 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1592 if (!in_array($res, $used)){
1593 $uid= $res;
1594 break;
1595 }
1596 }
1597 }
1599 if(preg_match('/\{id#\d+}/',$uid)){
1600 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1602 while (true){
1603 mt_srand((double) microtime()*1000000);
1604 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1605 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1606 if (!in_array($res, $used)){
1607 $uid= $res;
1608 break;
1609 }
1610 }
1611 }
1613 /* Don't assign used ones */
1614 if (!in_array($uid, $used)){
1615 $ret[]= $uid;
1616 }
1617 }
1619 return(array_unique($ret));
1620 }
1623 function array_search_r($needle, $key, $haystack){
1625 foreach($haystack as $index => $value){
1626 $match= 0;
1628 if (is_array($value)){
1629 $match= array_search_r($needle, $key, $value);
1630 }
1632 if ($index==$key && !is_array($value) && preg_match("/$needle/i", $value)){
1633 $match=1;
1634 }
1636 if ($match){
1637 return 1;
1638 }
1639 }
1641 return 0;
1642 }
1645 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1646 Need to convert... */
1647 function to_byte($value) {
1648 $value= strtolower(trim($value));
1650 if(!is_numeric(substr($value, -1))) {
1652 switch(substr($value, -1)) {
1653 case 'g':
1654 $mult= 1073741824;
1655 break;
1656 case 'm':
1657 $mult= 1048576;
1658 break;
1659 case 'k':
1660 $mult= 1024;
1661 break;
1662 }
1664 return ($mult * (int)substr($value, 0, -1));
1665 } else {
1666 return $value;
1667 }
1668 }
1671 function in_array_ics($value, $items)
1672 {
1673 if (!is_array($items)){
1674 return (FALSE);
1675 }
1677 foreach ($items as $item){
1678 if (strtolower($item) == strtolower($value)) {
1679 return (TRUE);
1680 }
1681 }
1683 return (FALSE);
1684 }
1687 function generate_alphabet($count= 10)
1688 {
1689 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1690 $alphabet= "";
1691 $c= 0;
1693 /* Fill cells with charaters */
1694 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1695 if ($c == 0){
1696 $alphabet.= "<tr>";
1697 }
1699 $ch = mb_substr($characters, $i, 1, "UTF8");
1700 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1701 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1703 if ($c++ == $count){
1704 $alphabet.= "</tr>";
1705 $c= 0;
1706 }
1707 }
1709 /* Fill remaining cells */
1710 while ($c++ <= $count){
1711 $alphabet.= "<td> </td>";
1712 }
1714 return ($alphabet);
1715 }
1718 function validate($string)
1719 {
1720 return (strip_tags(preg_replace('/\0/', '', $string)));
1721 }
1723 function get_gosa_version()
1724 {
1725 global $svn_revision, $svn_path;
1727 /* Extract informations */
1728 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1730 /* Release or development? */
1731 if (preg_match('%/gosa/trunk/%', $svn_path)){
1732 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1733 } else {
1734 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1735 return (sprintf(_("GOsa $release"), $revision));
1736 }
1737 }
1740 function rmdirRecursive($path, $followLinks=false) {
1741 $dir= opendir($path);
1742 while($entry= readdir($dir)) {
1743 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1744 unlink($path."/".$entry);
1745 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1746 rmdirRecursive($path."/".$entry);
1747 }
1748 }
1749 closedir($dir);
1750 return rmdir($path);
1751 }
1753 function scan_directory($path,$sort_desc=false)
1754 {
1755 $ret = false;
1757 /* is this a dir ? */
1758 if(is_dir($path)) {
1760 /* is this path a readable one */
1761 if(is_readable($path)){
1763 /* Get contents and write it into an array */
1764 $ret = array();
1766 $dir = opendir($path);
1768 /* Is this a correct result ?*/
1769 if($dir){
1770 while($fp = readdir($dir))
1771 $ret[]= $fp;
1772 }
1773 }
1774 }
1775 /* Sort array ascending , like scandir */
1776 sort($ret);
1778 /* Sort descending if parameter is sort_desc is set */
1779 if($sort_desc) {
1780 $ret = array_reverse($ret);
1781 }
1783 return($ret);
1784 }
1786 function clean_smarty_compile_dir($directory)
1787 {
1788 global $svn_revision;
1790 if(is_dir($directory) && is_readable($directory)) {
1791 // Set revision filename to REVISION
1792 $revision_file= $directory."/REVISION";
1794 /* Is there a stamp containing the current revision? */
1795 if(!file_exists($revision_file)) {
1796 // create revision file
1797 create_revision($revision_file, $svn_revision);
1798 } else {
1799 # check for "$config->...['CONFIG']/revision" and the
1800 # contents should match the revision number
1801 if(!compare_revision($revision_file, $svn_revision)){
1802 // If revision differs, clean compile directory
1803 foreach(scan_directory($directory) as $file) {
1804 if(($file==".")||($file=="..")) continue;
1805 if( is_file($directory."/".$file) &&
1806 is_writable($directory."/".$file)) {
1807 // delete file
1808 if(!unlink($directory."/".$file)) {
1809 print_red("File ".$directory."/".$file." could not be deleted.");
1810 // This should never be reached
1811 }
1812 } elseif(is_dir($directory."/".$file) &&
1813 is_writable($directory."/".$file)) {
1814 // Just recursively delete it
1815 rmdirRecursive($directory."/".$file);
1816 }
1817 }
1818 // We should now create a fresh revision file
1819 clean_smarty_compile_dir($directory);
1820 } else {
1821 // Revision matches, nothing to do
1822 }
1823 }
1824 } else {
1825 // Smarty compile dir is not accessible
1826 // (Smarty will warn about this)
1827 }
1828 }
1830 function create_revision($revision_file, $revision)
1831 {
1832 $result= false;
1834 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1835 if($fh= fopen($revision_file, "w")) {
1836 if(fwrite($fh, $revision)) {
1837 $result= true;
1838 }
1839 }
1840 fclose($fh);
1841 } else {
1842 print_red("Can not write to revision file");
1843 }
1845 return $result;
1846 }
1848 function compare_revision($revision_file, $revision)
1849 {
1850 // false means revision differs
1851 $result= false;
1853 if(file_exists($revision_file) && is_readable($revision_file)) {
1854 // Open file
1855 if($fh= fopen($revision_file, "r")) {
1856 // Compare File contents with current revision
1857 if($revision == fread($fh, filesize($revision_file))) {
1858 $result= true;
1859 }
1860 } else {
1861 print_red("Can not open revision file");
1862 }
1863 // Close file
1864 fclose($fh);
1865 }
1867 return $result;
1868 }
1870 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1871 {
1872 $str = ""; // Our return value will be saved in this var
1874 $color = dechex($percentage+150);
1875 $color2 = dechex(150 - $percentage);
1876 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1878 $progress = (int)(($percentage /100)*$width);
1880 /* Abort printing out percentage, if divs are to small */
1883 /* If theres a better solution for this, use it... */
1884 $str = "
1885 <div style=\" width:".($width)."px;
1886 height:".($height)."px;
1887 background-color:#000000;
1888 padding:1px;\">
1890 <div style=\" width:".($width)."px;
1891 background-color:#$bgcolor;
1892 height:".($height)."px;\">
1894 <div style=\" width:".$progress."px;
1895 height:".$height."px;
1896 background-color:#".$color2.$color2.$color."; \">";
1899 if(($height >10)&&($showvalue)){
1900 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1901 <b>".$percentage."%</b>
1902 </font>";
1903 }
1905 $str.= "</div></div></div>";
1907 return($str);
1908 }
1911 function array_key_ics($ikey, $items)
1912 {
1913 /* Gather keys, make them lowercase */
1914 $tmp= array();
1915 foreach ($items as $key => $value){
1916 $tmp[strtolower($key)]= $key;
1917 }
1919 if (isset($tmp[strtolower($ikey)])){
1920 return($tmp[strtolower($ikey)]);
1921 }
1923 return ("");
1924 }
1927 function search_config($arr, $name, $return)
1928 {
1929 if (is_array($arr)){
1930 foreach ($arr as $a){
1931 if (isset($a['CLASS']) &&
1932 strtolower($a['CLASS']) == strtolower($name)){
1934 if (isset($a[$return])){
1935 return ($a[$return]);
1936 } else {
1937 return ("");
1938 }
1939 } else {
1940 $res= search_config ($a, $name, $return);
1941 if ($res != ""){
1942 return $res;
1943 }
1944 }
1945 }
1946 }
1947 return ("");
1948 }
1951 function array_differs($src, $dst)
1952 {
1953 /* If the count is differing, the arrays differ */
1954 if (count ($src) != count ($dst)){
1955 return (TRUE);
1956 }
1958 /* So the count is the same - lets check the contents */
1959 $differs= FALSE;
1960 foreach($src as $value){
1961 if (!in_array($value, $dst)){
1962 $differs= TRUE;
1963 }
1964 }
1966 return ($differs);
1967 }
1970 function saveFilter($a_filter, $values)
1971 {
1972 if (isset($_POST['regexit'])){
1973 $a_filter["regex"]= $_POST['regexit'];
1975 foreach($values as $type){
1976 if (isset($_POST[$type])) {
1977 $a_filter[$type]= "checked";
1978 } else {
1979 $a_filter[$type]= "";
1980 }
1981 }
1982 }
1984 /* React on alphabet links if needed */
1985 if (isset($_GET['search'])){
1986 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
1987 if ($s == "**"){
1988 $s= "*";
1989 }
1990 $a_filter['regex']= $s;
1991 }
1993 return ($a_filter);
1994 }
1997 /* Escape all preg_* relevant characters */
1998 function normalizePreg($input)
1999 {
2000 return (addcslashes($input, '[]()|/.*+-'));
2001 }
2004 /* Escape all LDAP filter relevant characters */
2005 function normalizeLdap($input)
2006 {
2007 return (addcslashes($input, '()|'));
2008 }
2011 /* Resturns the difference between to microtime() results in float */
2012 function get_MicroTimeDiff($start , $stop)
2013 {
2014 $a = split("\ ",$start);
2015 $b = split("\ ",$stop);
2017 $secs = $b[1] - $a[1];
2018 $msecs= $b[0] - $a[0];
2020 $ret = (float) ($secs+ $msecs);
2021 return($ret);
2022 }
2025 /* Check if the given department name is valid */
2026 function is_department_name_reserved($name,$base)
2027 {
2028 $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2029 preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2030 preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2031 $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2033 /* Check if name is one of the reserved names */
2034 if(in_array_ics($name,$reservedName)) {
2035 return(true);
2036 }
2038 /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2039 foreach($follwedNames as $key => $names){
2040 if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2041 return(true);
2042 }
2043 }
2044 return(false);
2045 }
2048 function get_base_dir()
2049 {
2050 global $BASE_DIR;
2052 return $BASE_DIR;
2053 }
2056 function obj_is_readable($dn, $object, $attribute)
2057 {
2058 global $ui;
2060 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2061 }
2064 function obj_is_writable($dn, $object, $attribute)
2065 {
2066 global $ui;
2068 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2069 }
2072 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2073 {
2074 /* Initialize variables */
2075 $ret = array("count" => 0); // Set count to 0
2076 $next = true; // if false, then skip next loops and return
2077 $cnt = 0; // Current number of loops
2078 $max = 100; // Just for security, prevent looops
2079 $ldap = NULL; // To check if created result a valid
2080 $keep = ""; // save last failed parse string
2082 /* Check each parsed dn in ldap ? */
2083 if($config!=NULL && $verify_in_ldap){
2084 $ldap = $config->get_ldap_link();
2085 }
2087 /* Lets start */
2088 $called = false;
2089 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2091 $cnt ++;
2092 if(!preg_match("/,/",$dn)){
2093 $next = false;
2094 }
2095 $object = preg_replace("/[,].*$/","",$dn);
2096 $dn = preg_replace("/^[^,]+,/","",$dn);
2098 $called = true;
2100 /* Check if current dn is valid */
2101 if($ldap!=NULL){
2102 $ldap->cd($dn);
2103 $ldap->cat($dn,array("dn"));
2104 if($ldap->count()){
2105 $ret[] = $keep.$object;
2106 $keep = "";
2107 }else{
2108 $keep .= $object.",";
2109 }
2110 }else{
2111 $ret[] = $keep.$object;
2112 $keep = "";
2113 }
2114 }
2116 /* No dn was posted */
2117 if($cnt == 0 && !empty($dn)){
2118 $ret[] = $dn;
2119 }
2121 /* Append the rest */
2122 $test = $keep.$dn;
2123 if($called && !empty($test)){
2124 $ret[] = $keep.$dn;
2125 }
2126 $ret['count'] = count($ret) - 1;
2128 return($ret);
2129 }
2131 function is_php4()
2132 {
2133 if (isset($_SESSION['PHP4COMPATIBLE'])){
2134 return true;
2135 }
2136 return (preg_match('/^4/', phpversion()));
2137 }
2139 /* Add "str_split" if this function is missing.
2140 * This function is only available in PHP5
2141 */
2142 if(!function_exists("str_split")){
2143 function str_split($str,$length =1)
2144 {
2145 if($length < 1 ) $length =1;
2147 $ret = array();
2148 for($i = 0 ; $i < strlen($str); $i = $i +$length){
2149 $ret[] = substr($str,$i ,$length);
2150 }
2151 return($ret);
2152 }
2153 }
2156 function get_base_from_hook($dn, $attrib)
2157 {
2158 global $config;
2160 if (isset($config->current['BASE_HOOK'])){
2162 /* Call hook script - if present */
2163 $command= $config->current['BASE_HOOK'];
2165 if ($command != ""){
2166 $command.= " '$dn' $attrib";
2167 if (check_command($command)){
2168 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2169 exec($command, $output);
2170 if (preg_match("/^[0-9]+$/", $output[0])){
2171 return ($output[0]);
2172 } else {
2173 print_red(_("Warning - base_hook is not avialable. Using default base."));
2174 return ($config->current['UIDBASE']);
2175 }
2176 } else {
2177 print_red(_("Warning - base_hook is not avialable. Using default base."));
2178 return ($config->current['UIDBASE']);
2179 }
2181 } else {
2183 print_red(_("Warning - no base_hook defined. Using default base."));
2184 return ($config->current['UIDBASE']);
2186 }
2187 }
2188 }
2190 /* Schema validation functions */
2192 function check_schema_version($class, $version)
2193 {
2194 return preg_match("/\(v$version\)/", $class['DESC']);
2195 }
2197 function check_schema($cfg,$rfc2307bis = FALSE)
2198 {
2199 $messages= array();
2201 /* Get objectclasses */
2202 $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2203 $objectclasses = $ldap->get_objectclasses();
2204 if(count($objectclasses) == 0){
2205 print_red(_("Can't get schema information from server. No schema check possible!"));
2206 }
2208 /* This is the default block used for each entry.
2209 * to avoid unset indexes.
2210 */
2211 $def_check = array("REQUIRED_VERSION" => "0",
2212 "SCHEMA_FILES" => array(),
2213 "CLASSES_REQUIRED" => array(),
2214 "STATUS" => FALSE,
2215 "IS_MUST_HAVE" => FALSE,
2216 "MSG" => "",
2217 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2219 /* The gosa base schema */
2220 $checks['gosaObject'] = $def_check;
2221 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2222 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2223 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2224 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2226 /* GOsa Account class */
2227 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2228 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2229 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2230 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2231 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2233 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2234 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2235 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2236 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2237 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2238 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2240 /* Some other checks */
2241 foreach(array(
2242 "gosaCacheEntry" => array("version" => "2.4"),
2243 "gosaDepartment" => array("version" => "2.4"),
2244 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2245 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2246 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2247 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2248 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2249 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2250 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2251 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2252 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2253 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2254 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2255 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2256 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2257 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2258 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2259 "goLdapServer" => array("version" => "2.4"),
2260 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2261 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2262 "goKrbServer" => array("version" => "2.4"),
2263 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2264 ) as $name => $values){
2266 $checks[$name] = $def_check;
2267 if(isset($values['version'])){
2268 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2269 }
2270 if(isset($values['file'])){
2271 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2272 }
2273 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2274 }
2275 foreach($checks as $name => $value){
2276 foreach($value['CLASSES_REQUIRED'] as $class){
2278 if(!isset($objectclasses[$name])){
2279 $checks[$name]['STATUS'] = FALSE;
2280 if($value['IS_MUST_HAVE']){
2281 $checks[$name]['MSG'] = sprintf(_("The required objectClass '%s' is not present in your schema setup"),$class);
2282 }else{
2283 $checks[$name]['MSG'] = sprintf(_("The optional objectClass '%s' is not present in your schema setup"),$class);
2284 }
2285 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2286 $checks[$name]['STATUS'] = FALSE;
2288 if($value['IS_MUST_HAVE']){
2289 $checks[$name]['MSG'] = sprintf(_("The required objectclass '%s' does not have version %s"), $class, $value['REQUIRED_VERSION']);
2290 }else{
2291 $checks[$name]['MSG'] = sprintf(_("The optional objectclass '%s' does not have version %s"), $class, $value['REQUIRED_VERSION']);
2292 }
2293 }else{
2294 $checks[$name]['STATUS'] = TRUE;
2295 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2296 }
2297 }
2298 }
2300 $tmp = $objectclasses;
2302 /* The gosa base schema */
2303 $checks['posixGroup'] = $def_check;
2304 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2305 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2306 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2307 $checks['posixGroup']['STATUS'] = TRUE;
2308 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2309 $checks['posixGroup']['MSG'] = "";
2310 $checks['posixGroup']['INFO'] = "";
2312 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2313 if(isset($tmp['posixGroup'])){
2315 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2316 $checks['posixGroup']['STATUS'] = FALSE;
2317 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2318 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2319 }
2320 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2321 $checks['posixGroup']['STATUS'] = FALSE;
2322 $checks['posixGroup']['MSG'] = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2323 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2324 }
2325 }
2327 return($checks);
2328 }
2330 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2331 ?>