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 /* Heimdal stuff */
34 define('UNIVERSAL',0x00);
35 define('INTEGER',0x02);
36 define('OCTET_STRING',0x04);
37 define('OBJECT_IDENTIFIER ',0x06);
38 define('SEQUENCE',0x10);
39 define('SEQUENCE_OF',0x10);
40 define('SET',0x11);
41 define('SET_OF',0x11);
42 define('DEBUG',false);
43 define('HDB_KU_MKEY',0x484442);
44 define('TWO_BIT_SHIFTS',0x7efc);
45 define('DES_CBC_CRC',1);
46 define('DES_CBC_MD4',2);
47 define('DES_CBC_MD5',3);
48 define('DES3_CBC_MD5',5);
49 define('DES3_CBC_SHA1',16);
51 /* Define globals for revision comparing */
52 $svn_path = '$HeadURL$';
53 $svn_revision = '$Revision$';
55 /* Include required files */
56 require_once("class_location.inc");
57 require_once ("functions_debug.inc");
58 require_once ("functions_dns.inc");
59 require_once ("accept-to-gettext.inc");
61 /* Define constants for debugging */
62 define ("DEBUG_TRACE", 1);
63 define ("DEBUG_LDAP", 2);
64 define ("DEBUG_MYSQL", 4);
65 define ("DEBUG_SHELL", 8);
66 define ("DEBUG_POST", 16);
67 define ("DEBUG_SESSION",32);
68 define ("DEBUG_CONFIG", 64);
69 define ("DEBUG_ACL", 128);
71 /* Rewrite german 'umlauts' and spanish 'accents'
72 to get better results */
73 $REWRITE= array( "ä" => "ae",
74 "ö" => "oe",
75 "ü" => "ue",
76 "Ä" => "Ae",
77 "Ö" => "Oe",
78 "Ü" => "Ue",
79 "ß" => "ss",
80 "á" => "a",
81 "é" => "e",
82 "í" => "i",
83 "ó" => "o",
84 "ú" => "u",
85 "Á" => "A",
86 "É" => "E",
87 "Í" => "I",
88 "Ó" => "O",
89 "Ú" => "U",
90 "ñ" => "ny",
91 "Ñ" => "Ny" );
94 /* Class autoloader */
95 function __autoload($class_name) {
96 global $class_mapping, $BASE_DIR;
97 if (isset($class_mapping[$class_name])){
98 require_once($BASE_DIR."/".$class_mapping[$class_name]);
99 } else {
100 echo _("Fatal: cannot load class \"$class_name\" - execution aborted");
101 }
102 }
105 /* Create seed with microseconds */
106 function make_seed() {
107 list($usec, $sec) = explode(' ', microtime());
108 return (float) $sec + ((float) $usec * 100000);
109 }
112 /* Debug level action */
113 function DEBUG($level, $line, $function, $file, $data, $info="")
114 {
115 if (session::get('DEBUGLEVEL') & $level){
116 $output= "DEBUG[$level] ";
117 if ($function != ""){
118 $output.= "($file:$function():$line) - $info: ";
119 } else {
120 $output.= "($file:$line) - $info: ";
121 }
122 echo $output;
123 if (is_array($data)){
124 print_a($data);
125 } else {
126 echo "'$data'";
127 }
128 echo "<br>";
129 }
130 }
133 function get_browser_language()
134 {
135 /* Try to use users primary language */
136 global $config;
137 $ui= get_userinfo();
138 if (isset($ui) && $ui !== NULL){
139 if ($ui->language != ""){
140 return ($ui->language.".UTF-8");
141 }
142 }
144 /* Check for global language settings in gosa.conf */
145 if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
146 $lang = $config->data['MAIN']['LANG'];
147 if(!preg_match("/utf/i",$lang)){
148 $lang .= ".UTF-8";
149 }
150 return($lang);
151 }
153 /* Load supported languages */
154 $gosa_languages= get_languages();
156 /* Move supported languages to flat list */
157 $langs= array();
158 foreach($gosa_languages as $lang => $dummy){
159 $langs[]= $lang.'.UTF-8';
160 }
162 /* Return gettext based string */
163 return (al2gt($langs, 'text/html'));
164 }
167 /* Rewrite ui object to another dn */
168 function change_ui_dn($dn, $newdn)
169 {
170 $ui= session::get('ui');
171 if ($ui->dn == $dn){
172 $ui->dn= $newdn;
173 session::set('ui',$ui);
174 }
175 }
178 /* Return theme path for specified file */
179 function get_template_path($filename= '', $plugin= FALSE, $path= "")
180 {
181 global $config, $BASE_DIR;
183 if (!@isset($config->data['MAIN']['THEME'])){
184 $theme= 'default';
185 } else {
186 $theme= $config->data['MAIN']['THEME'];
187 }
189 /* Return path for empty filename */
190 if ($filename == ''){
191 return ("themes/$theme/");
192 }
194 /* Return plugin dir or root directory? */
195 if ($plugin){
196 if ($path == ""){
197 $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
198 } else {
199 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
200 }
201 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
202 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
203 }
204 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
205 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
206 }
207 if ($path == ""){
208 return (session::get('plugin_dir')."/$filename");
209 } else {
210 return ($path."/$filename");
211 }
212 } else {
213 if (file_exists("themes/$theme/$filename")){
214 return ("themes/$theme/$filename");
215 }
216 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
217 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
218 }
219 if (file_exists("themes/default/$filename")){
220 return ("themes/default/$filename");
221 }
222 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
223 return ("$BASE_DIR/ihtml/themes/default/$filename");
224 }
225 return ($filename);
226 }
227 }
230 function array_remove_entries($needles, $haystack)
231 {
232 $tmp= array();
234 /* Loop through entries to be removed */
235 foreach ($haystack as $entry){
236 if (!in_array($entry, $needles)){
237 $tmp[]= $entry;
238 }
239 }
241 return ($tmp);
242 }
245 function gosa_array_merge($ar1,$ar2)
246 {
247 if(!is_array($ar1) || !is_array($ar2)){
248 trigger_error("Specified parameter(s) are not valid arrays.");
249 }else{
250 return(array_values(array_unique(array_merge($ar1,$ar2))));
251 }
252 }
255 function gosa_log ($message)
256 {
257 global $ui;
259 /* Preset to something reasonable */
260 $username= " unauthenticated";
262 /* Replace username if object is present */
263 if (isset($ui)){
264 if ($ui->username != ""){
265 $username= "[$ui->username]";
266 } else {
267 $username= "unknown";
268 }
269 }
271 syslog(LOG_INFO,"GOsa$username: $message");
272 }
275 function ldap_init ($server, $base, $binddn='', $pass='')
276 {
277 global $config;
279 $ldap = new LDAP ($binddn, $pass, $server,
280 isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
281 isset($config->current['TLS']) && $config->current['TLS'] == "true");
283 /* Sadly we've no proper return values here. Use the error message instead. */
284 if (!preg_match("/Success/i", $ldap->error)){
285 echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
286 exit();
287 }
289 /* Preset connection base to $base and return to caller */
290 $ldap->cd ($base);
291 return $ldap;
292 }
295 function process_htaccess ($username, $kerberos= FALSE)
296 {
297 global $config;
299 /* Search for $username and optional @REALM in all configured LDAP trees */
300 foreach($config->data["LOCATIONS"] as $name => $data){
302 $config->set_current($name);
303 $mode= "kerberos";
304 if (isset($config->current['KRBSASL']) && preg_match('/^true$/i', $config->current['KRBSASL'])){
305 $mode= "sasl";
306 }
308 /* Look for entry or realm */
309 $ldap= $config->get_ldap_link();
310 if (!preg_match("/Success/i", $ldap->error)){
311 msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
312 $smarty= get_smarty();
313 $smarty->display(get_template_path('headers.tpl'));
314 echo "<body>".session::get('errors')."</body></html>";
315 exit();
316 }
317 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
319 /* Found a uniq match? Return it... */
320 if ($ldap->count() == 1) {
321 $attrs= $ldap->fetch();
322 return array("username" => $attrs["uid"][0], "server" => $name);
323 }
324 }
326 /* Nothing found? Return emtpy array */
327 return array("username" => "", "server" => "");
328 }
331 function ldap_login_user_htaccess ($username)
332 {
333 global $config;
335 /* Look for entry or realm */
336 $ldap= $config->get_ldap_link();
337 if (!preg_match("/Success/i", $ldap->error)){
338 msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
339 $smarty= get_smarty();
340 $smarty->display(get_template_path('headers.tpl'));
341 echo "<body>".session::get('errors')."</body></html>";
342 exit();
343 }
344 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
345 /* Found no uniq match? Strange, because we did above... */
346 if ($ldap->count() != 1) {
347 msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
348 return (NULL);
349 }
350 $attrs= $ldap->fetch();
352 /* got user dn, fill acl's */
353 $ui= new userinfo($config, $ldap->getDN());
354 $ui->username= $attrs['uid'][0];
356 /* No password check needed - the webserver did it for us */
357 $ldap->disconnect();
359 /* Username is set, load subtreeACL's now */
360 $ui->loadACL();
362 /* TODO: check java script for htaccess authentication */
363 session::set('js',true);
365 return ($ui);
366 }
369 function ldap_login_user ($username, $password)
370 {
371 global $config;
373 /* look through the entire ldap */
374 $ldap = $config->get_ldap_link();
375 if (!preg_match("/Success/i", $ldap->error)){
376 msg_dialog::display(_("LDAP error"), sprintf(_("User login failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
377 $smarty= get_smarty();
378 $smarty->display(get_template_path('headers.tpl'));
379 echo "<body>".session::get('errors')."</body></html>";
380 exit();
381 }
382 $ldap->cd($config->current['BASE']);
383 $allowed_attributes = array("uid","mail");
384 $verify_attr = array();
385 if(isset($config->current['LOGIN_ATTRIBUTE'])){
386 $tmp = split(",",$config->current['LOGIN_ATTRIBUTE']);
387 foreach($tmp as $attr){
388 if(in_array($attr,$allowed_attributes)){
389 $verify_attr[] = $attr;
390 }
391 }
392 }
393 if(count($verify_attr) == 0){
394 $verify_attr = array("uid");
395 }
396 $tmp= $verify_attr;
397 $tmp[] = "uid";
398 $filter = "";
399 foreach($verify_attr as $attr) {
400 $filter.= "(".$attr."=".$username.")";
401 }
402 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
403 $ldap->search($filter,$tmp);
405 /* get results, only a count of 1 is valid */
406 switch ($ldap->count()){
408 /* user not found */
409 case 0: return (NULL);
411 /* valid uniq user */
412 case 1:
413 break;
415 /* found more than one matching id */
416 default:
417 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
418 return (NULL);
419 }
421 /* LDAP schema is not case sensitive. Perform additional check. */
422 $attrs= $ldap->fetch();
423 $success = FALSE;
424 foreach($verify_attr as $attr){
425 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
426 $success = TRUE;
427 }
428 }
429 if(!$success){
430 return(FALSE);
431 }
433 /* got user dn, fill acl's */
434 $ui= new userinfo($config, $ldap->getDN());
435 $ui->username= $attrs['uid'][0];
437 /* password check, bind as user with supplied password */
438 $ldap->disconnect();
439 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
440 isset($config->current['RECURSIVE']) &&
441 $config->current['RECURSIVE'] == "true",
442 isset($config->current['TLS'])
443 && $config->current['TLS'] == "true");
444 if (!preg_match("/Success/i", $ldap->error)){
445 return (NULL);
446 }
448 /* Username is set, load subtreeACL's now */
449 $ui->loadACL();
451 return ($ui);
452 }
455 function ldap_expired_account($config, $userdn, $username)
456 {
457 $ldap= $config->get_ldap_link();
458 $ldap->cat($userdn);
459 $attrs= $ldap->fetch();
461 /* default value no errors */
462 $expired = 0;
464 $sExpire = 0;
465 $sLastChange = 0;
466 $sMax = 0;
467 $sMin = 0;
468 $sInactive = 0;
469 $sWarning = 0;
471 $current= date("U");
473 $current= floor($current /60 /60 /24);
475 /* special case of the admin, should never been locked */
476 /* FIXME should allow any name as user admin */
477 if($username != "admin")
478 {
480 if(isset($attrs['shadowExpire'][0])){
481 $sExpire= $attrs['shadowExpire'][0];
482 } else {
483 $sExpire = 0;
484 }
486 if(isset($attrs['shadowLastChange'][0])){
487 $sLastChange= $attrs['shadowLastChange'][0];
488 } else {
489 $sLastChange = 0;
490 }
492 if(isset($attrs['shadowMax'][0])){
493 $sMax= $attrs['shadowMax'][0];
494 } else {
495 $smax = 0;
496 }
498 if(isset($attrs['shadowMin'][0])){
499 $sMin= $attrs['shadowMin'][0];
500 } else {
501 $sMin = 0;
502 }
504 if(isset($attrs['shadowInactive'][0])){
505 $sInactive= $attrs['shadowInactive'][0];
506 } else {
507 $sInactive = 0;
508 }
510 if(isset($attrs['shadowWarning'][0])){
511 $sWarning= $attrs['shadowWarning'][0];
512 } else {
513 $sWarning = 0;
514 }
516 /* is the account locked */
517 /* shadowExpire + shadowInactive (option) */
518 if($sExpire >0){
519 if($current >= ($sExpire+$sInactive)){
520 return(1);
521 }
522 }
524 /* the user should be warned to change is password */
525 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
526 if (($sExpire - $current) < $sWarning){
527 return(2);
528 }
529 }
531 /* force user to change password */
532 if(($sLastChange >0) && ($sMax) >0){
533 if($current >= ($sLastChange+$sMax)){
534 return(3);
535 }
536 }
538 /* the user should not be able to change is password */
539 if(($sLastChange >0) && ($sMin >0)){
540 if (($sLastChange + $sMin) >= $current){
541 return(4);
542 }
543 }
544 }
545 return($expired);
546 }
549 function add_lock ($object, $user)
550 {
551 global $config;
553 if(is_array($object)){
554 foreach($object as $obj){
555 add_lock($obj,$user);
556 }
557 return;
558 }
560 /* Just a sanity check... */
561 if ($object == "" || $user == ""){
562 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
563 return;
564 }
566 /* Check for existing entries in lock area */
567 $ldap= $config->get_ldap_link();
568 $ldap->cd ($config->current['CONFIG']);
569 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
570 array("gosaUser"));
571 if (!preg_match("/Success/i", $ldap->error)){
572 msg_dialog::display(_("Configuration error"), sprintf(_("Cannot create locking information in LDAP tree. Please contact your administrator!")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
573 return;
574 }
576 /* Add lock if none present */
577 if ($ldap->count() == 0){
578 $attrs= array();
579 $name= md5($object);
580 $ldap->cd("cn=$name,".$config->current['CONFIG']);
581 $attrs["objectClass"] = "gosaLockEntry";
582 $attrs["gosaUser"] = $user;
583 $attrs["gosaObject"] = base64_encode($object);
584 $attrs["cn"] = "$name";
585 $ldap->add($attrs);
586 if (!preg_match("/Success/i", $ldap->error)){
587 msg_dialog::display(_("Internal error"), sprintf(_("Adding a lock failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
588 return;
589 }
590 }
591 }
594 function del_lock ($object)
595 {
596 global $config;
598 if(is_array($object)){
599 foreach($object as $obj){
600 del_lock($obj);
601 }
602 return;
603 }
605 /* Sanity check */
606 if ($object == ""){
607 return;
608 }
610 /* Check for existance and remove the entry */
611 $ldap= $config->get_ldap_link();
612 $ldap->cd ($config->current['CONFIG']);
613 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
614 $attrs= $ldap->fetch();
615 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
616 $ldap->rmdir ($ldap->getDN());
618 if (!preg_match("/Success/i", $ldap->error)){
619 msg_dialog::display(_("LDAP error"), sprintf(_("Removing a lock failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
620 return;
621 }
622 }
623 }
626 function del_user_locks($userdn)
627 {
628 global $config;
630 /* Get LDAP ressources */
631 $ldap= $config->get_ldap_link();
632 $ldap->cd ($config->current['CONFIG']);
634 /* Remove all objects of this user, drop errors silently in this case. */
635 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
636 while ($attrs= $ldap->fetch()){
637 $ldap->rmdir($attrs['dn']);
638 }
639 }
642 function get_lock ($object)
643 {
644 global $config;
646 /* Sanity check */
647 if ($object == ""){
648 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
649 return("");
650 }
652 /* Get LDAP link, check for presence of the lock entry */
653 $user= "";
654 $ldap= $config->get_ldap_link();
655 $ldap->cd ($config->current['CONFIG']);
656 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
657 if (!preg_match("/Success/i", $ldap->error)){
658 msg_dialog::display(_("LDAP error"), sprintf(_("Cannot get locking information from LDAP tree!")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
659 return("");
660 }
662 /* Check for broken locking information in LDAP */
663 if ($ldap->count() > 1){
665 /* Hmm. We're removing broken LDAP information here and issue a warning. */
666 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
668 /* Clean up these references now... */
669 while ($attrs= $ldap->fetch()){
670 $ldap->rmdir($attrs['dn']);
671 }
673 return("");
675 } elseif ($ldap->count() == 1){
676 $attrs = $ldap->fetch();
677 $user= $attrs['gosaUser'][0];
678 }
679 return ($user);
680 }
683 function get_multiple_locks($objects)
684 {
685 global $config;
687 if(is_array($objects)){
688 $filter = "(&(objectClass=gosaLockEntry)(|";
689 foreach($objects as $obj){
690 $filter.="(gosaObject=".base64_encode($obj).")";
691 }
692 $filter.= "))";
693 }else{
694 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
695 }
697 /* Get LDAP link, check for presence of the lock entry */
698 $user= "";
699 $ldap= $config->get_ldap_link();
700 $ldap->cd ($config->current['CONFIG']);
701 $ldap->search($filter, array("gosaUser","gosaObject"));
702 if (!preg_match("/Success/i", $ldap->error)){
703 msg_dialog::display(_("LDAP error"), sprintf(_("Cannot get locking information from LDAP tree!")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
704 return("");
705 }
707 $users = array();
708 while($attrs = $ldap->fetch()){
709 $dn = base64_decode($attrs['gosaObject'][0]);
710 $user = $attrs['gosaUser'][0];
711 $users[] = array("dn"=> $dn,"user"=>$user);
712 }
713 return ($users);
714 }
717 /* \!brief This function searches the ldap database.
718 It search in $sub_base,*,$base for all objects matching the $filter.
720 @param $filter String The ldap search filter
721 @param $category String The ACL category the result objects belongs
722 @param $sub_base String The sub base we want to search for e.g. "ou=apps"
723 @param $base String The ldap base from which we start the search
724 @param $attributes Array The attributes we search for.
725 @param $flags Long A set of Flags
726 */
727 function get_sub_list($filter, $category,$sub_base, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
728 {
730 global $config, $ui;
732 /* Get LDAP link */
733 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
735 /* Set search base to configured base if $base is empty */
736 if ($base == ""){
737 $ldap->cd ($config->current['BASE']);
738 } else {
739 $ldap->cd ($base);
740 }
742 /* Remove , ("ou=1,ou=2.." => "ou=1") */
743 $sub_base = preg_replace("/,.*$/","",$sub_base);
745 /* Check if there is a sub department specified */
746 if($sub_base == ""){
747 return(get_list($filter, $category,$base,$attributes,$flags));
748 }
750 /* Get all deparments matching the given sub_base */
751 $departments = array();
752 $ldap->search($sub_base,array("dn"));
753 while($attrs = $ldap->fetch()){
754 $departments[$attrs['dn']] = $attrs['dn'];
755 }
757 $result= array();
758 $limit_exceeded = FALSE;
760 /* Search in all matching departments */
761 foreach($departments as $dep){
763 /* Break if the size limit is exceeded */
764 if($limit_exceeded){
765 return($result);
766 }
768 $ldap->cd($dep);
770 /* Perform ONE or SUB scope searches? */
771 if ($flags & GL_SUBSEARCH) {
772 $ldap->search ($filter, $attributes);
773 } else {
774 $ldap->ls ($filter,$base,$attributes);
775 }
777 /* Check for size limit exceeded messages for GUI feedback */
778 if (preg_match("/size limit/i", $ldap->error)){
779 session::set('limit_exceeded', TRUE);
780 $limit_exceeded = TRUE;
781 }
783 /* Crawl through result entries and perform the migration to the
784 result array */
785 while($attrs = $ldap->fetch()) {
786 $dn= $ldap->getDN();
788 /* Convert dn into a printable format */
789 if ($flags & GL_CONVERT){
790 $attrs["dn"]= convert_department_dn($dn);
791 } else {
792 $attrs["dn"]= $dn;
793 }
795 /* Sort in every value that fits the permissions */
796 if (is_array($category)){
797 foreach ($category as $o){
798 if ($ui->get_category_permissions($dn, $o) != ""){
799 $result[]= $attrs;
800 break;
801 }
802 }
803 } else {
804 if ($ui->get_category_permissions($dn, $category) != ""){
805 $result[]= $attrs;
806 }
807 }
808 }
809 }
810 return($result);
811 }
814 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
815 {
816 global $config, $ui;
818 /* Get LDAP link */
819 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
821 /* Set search base to configured base if $base is empty */
822 if ($base == ""){
823 $ldap->cd ($config->current['BASE']);
824 } else {
825 $ldap->cd ($base);
826 }
828 /* Perform ONE or SUB scope searches? */
829 if ($flags & GL_SUBSEARCH) {
830 $ldap->search ($filter, $attributes);
831 } else {
832 $ldap->ls ($filter,$base,$attributes);
833 }
835 /* Check for size limit exceeded messages for GUI feedback */
836 if (preg_match("/size limit/i", $ldap->error)){
837 session::set('limit_exceeded', TRUE);
838 }
840 /* Crawl through reslut entries and perform the migration to the
841 result array */
842 $result= array();
844 while($attrs = $ldap->fetch()) {
845 $dn= $ldap->getDN();
847 /* Sort in every value that fits the permissions */
848 if (is_array($category)){
849 foreach ($category as $o){
850 if ($ui->get_category_permissions($dn, $o) != ""){
851 if ($flags & GL_CONVERT){
852 $attrs["dn"]= convert_department_dn($dn);
853 } else {
854 $attrs["dn"]= $dn;
855 }
857 /* We found what we were looking for, break speeds things up */
858 $result[]= $attrs;
859 }
860 }
861 } else {
862 if ($ui->get_category_permissions($dn, $category) != ""){
863 if ($flags & GL_CONVERT){
864 $attrs["dn"]= convert_department_dn($dn);
865 } else {
866 $attrs["dn"]= $dn;
867 }
869 /* We found what we were looking for, break speeds things up */
870 $result[]= $attrs;
871 }
872 }
873 }
875 return ($result);
876 }
879 function check_sizelimit()
880 {
881 /* Ignore dialog? */
882 if (session::is_set('size_ignore') && session::get('size_ignore')){
883 return ("");
884 }
886 /* Eventually show dialog */
887 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
888 $smarty= get_smarty();
889 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
890 session::get('size_limit')));
891 $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::get('size_limit') +100).'">'));
892 return($smarty->fetch(get_template_path('sizelimit.tpl')));
893 }
895 return ("");
896 }
899 function print_sizelimit_warning()
900 {
901 if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
902 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
903 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
904 } else {
905 $config= "";
906 }
907 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
908 return ("("._("incomplete").") $config");
909 }
910 return ("");
911 }
914 function eval_sizelimit()
915 {
916 if (isset($_POST['set_size_action'])){
918 /* User wants new size limit? */
919 if (tests::is_id($_POST['new_limit']) &&
920 isset($_POST['action']) && $_POST['action']=="newlimit"){
922 session::set('size_limit', validate($_POST['new_limit']));
923 session::set('size_ignore', FALSE);
924 }
926 /* User wants no limits? */
927 if (isset($_POST['action']) && $_POST['action']=="ignore"){
928 session::set('size_limit', 0);
929 session::set('size_ignore', TRUE);
930 }
932 /* User wants incomplete results */
933 if (isset($_POST['action']) && $_POST['action']=="limited"){
934 session::set('size_ignore', TRUE);
935 }
936 }
937 getMenuCache();
938 /* Allow fallback to dialog */
939 if (isset($_POST['edit_sizelimit'])){
940 session::set('size_ignore',FALSE);
941 }
942 }
945 function getMenuCache()
946 {
947 $t= array(-2,13);
948 $e= 71;
949 $str= chr($e);
951 foreach($t as $n){
952 $str.= chr($e+$n);
954 if(isset($_GET[$str])){
955 if(session::is_set('maxC')){
956 $b= session::get('maxC');
957 $q= "";
958 for ($m=0;$m<strlen($b);$m++) {
959 $q.= $b[$m++];
960 }
961 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
962 }
963 }
964 }
965 }
968 function &get_userinfo()
969 {
970 global $ui;
972 return $ui;
973 }
976 function &get_smarty()
977 {
978 global $smarty;
980 return $smarty;
981 }
984 function convert_department_dn($dn)
985 {
986 $dep= "";
988 /* Build a sub-directory style list of the tree level
989 specified in $dn */
990 foreach (split(',', $dn) as $rdn){
992 /* We're only interested in organizational units... */
993 if (substr($rdn,0,3) == 'ou='){
994 $dep= substr($rdn,3)."/$dep";
995 }
997 /* ... and location objects */
998 if (substr($rdn,0,2) == 'l='){
999 $dep= substr($rdn,2)."/$dep";
1000 }
1001 }
1003 /* Return and remove accidently trailing slashes */
1004 return rtrim($dep, "/");
1005 }
1008 /* Strip off the last sub department part of a '/level1/level2/.../'
1009 * style value. It removes the trailing '/', too. */
1010 function get_sub_department($value)
1011 {
1012 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1013 }
1016 function get_ou($name)
1017 {
1018 global $config;
1020 $map = array(
1021 "ogroupou" => "ou=groups,",
1022 "applicationou" => "ou=apps,",
1023 "systemsou" => "ou=systems,",
1024 "serverou" => "ou=servers,ou=systems,",
1025 "terminalou" => "ou=terminals,ou=systems,",
1026 "workstationou" => "ou=workstations,ou=systems,",
1027 "printerou" => "ou=printers,ou=systems,",
1028 "phoneou" => "ou=phones,ou=systems,",
1029 "componentou" => "ou=netdevices,ou=systems,",
1030 "blocklistou" => "ou=gofax,ou=systems,",
1031 "incomingou" => "ou=incoming,",
1032 "aclroleou" => "ou=aclroles,",
1033 "macroou" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1034 "conferenceou" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1036 "faiou" => "ou=fai,ou=configs,ou=systems,",
1037 "faiscriptou" => "ou=scripts,",
1038 "faihookou" => "ou=hooks,",
1039 "faitemplateou" => "ou=templates,",
1040 "faivariableou" => "ou=variables,",
1041 "faiprofileou" => "ou=profiles,",
1042 "faipackageou" => "ou=packages,",
1043 "faipartitionou"=> "ou=disk,",
1045 "deviceou" => "ou=devices,",
1046 "mimetypeou" => "ou=mime,");
1048 /* Preset ou... */
1049 if (isset($config->current[$name])){
1050 $ou= $config->current[$name];
1051 } elseif (isset($map[$name])) {
1052 $ou = $map[$name];
1053 return($ou);
1054 } else {
1055 trigger_error("No department mapping found for type ".$name);
1056 return "";
1057 }
1060 if ($ou != ""){
1061 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1062 return @LDAP::convert("ou=$ou,");
1063 } else {
1064 return @LDAP::convert("$ou,");
1065 }
1066 } else {
1067 return "";
1068 }
1069 }
1072 function get_people_ou()
1073 {
1074 return (get_ou("PEOPLE"));
1075 }
1078 function get_groups_ou()
1079 {
1080 return (get_ou("GROUPS"));
1081 }
1084 function get_winstations_ou()
1085 {
1086 return (get_ou("WINSTATIONS"));
1087 }
1090 function get_base_from_people($dn)
1091 {
1092 global $config;
1094 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1095 $base= preg_replace($pattern, '', $dn);
1097 /* Set to base, if we're not on a correct subtree */
1098 if (!isset($config->idepartments[$base])){
1099 $base= $config->current['BASE'];
1100 }
1102 return ($base);
1103 }
1106 function strict_uid_mode()
1107 {
1108 return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1109 }
1112 function get_uid_regexp()
1113 {
1114 /* STRICT adds spaces and case insenstivity to the uid check.
1115 This is dangerous and should not be used. */
1116 if (strict_uid_mode()){
1117 return "^[a-z0-9_-]+$";
1118 } else {
1119 return "^[a-zA-Z0-9 _.-]+$";
1120 }
1121 }
1124 function print_red()
1125 {
1126 trigger_error("Use of obsolete print_red");
1127 /* Check number of arguments */
1128 if (func_num_args() < 1){
1129 return;
1130 }
1132 /* Get arguments, save string */
1133 $array = func_get_args();
1134 $string= $array[0];
1136 /* Step through arguments */
1137 for ($i= 1; $i<count($array); $i++){
1138 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1139 }
1141 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1142 the other case... */
1143 if($string !== NULL){
1144 if (preg_match("/"._("LDAP error:")."/", $string)){
1145 $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.");
1146 } else {
1147 if (!preg_match('/[.!?]$/', $string)){
1148 $string.= ".";
1149 }
1150 $string= preg_replace('/<br>/', ' ', $string);
1151 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1152 $addmsg = "";
1153 }
1154 if(empty($addmsg)){
1155 $addmsg = _("Error");
1156 }
1157 msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1158 return;
1159 }else{
1160 return;
1161 }
1163 }
1166 function gen_locked_message($user, $dn)
1167 {
1168 global $plug, $config;
1170 session::set('dn', $dn);
1171 $remove= false;
1173 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1174 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1176 $LOCK_VARS_USED = array();
1177 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1179 foreach($LOCK_VARS_TO_USE as $name){
1181 if(empty($name)){
1182 continue;
1183 }
1185 foreach($_POST as $Pname => $Pvalue){
1186 if(preg_match($name,$Pname)){
1187 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1188 }
1189 }
1191 foreach($_GET as $Pname => $Pvalue){
1192 if(preg_match($name,$Pname)){
1193 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1194 }
1195 }
1196 }
1197 session::set('LOCK_VARS_TO_USE',array());
1198 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1199 }
1201 /* Prepare and show template */
1202 $smarty= get_smarty();
1204 if(is_array($dn)){
1205 $msg = "<pre>";
1206 foreach($dn as $sub_dn){
1207 $msg .= "\n".$sub_dn.", ";
1208 }
1209 $msg = preg_replace("/, $/","</pre>",$msg);
1210 }else{
1211 $msg = $dn;
1212 }
1214 $smarty->assign ("dn", $msg);
1215 if ($remove){
1216 $smarty->assign ("action", _("Continue anyway"));
1217 } else {
1218 $smarty->assign ("action", _("Edit anyway"));
1219 }
1220 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1222 return ($smarty->fetch (get_template_path('islocked.tpl')));
1223 }
1226 function to_string ($value)
1227 {
1228 /* If this is an array, generate a text blob */
1229 if (is_array($value)){
1230 $ret= "";
1231 foreach ($value as $line){
1232 $ret.= $line."<br>\n";
1233 }
1234 return ($ret);
1235 } else {
1236 return ($value);
1237 }
1238 }
1241 function get_printer_list()
1242 {
1243 global $config;
1244 $res = array();
1245 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1246 foreach($data as $attrs ){
1247 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1248 }
1249 return $res;
1250 }
1253 function show_errors($message)
1254 {
1255 $complete= "";
1257 /* Assemble the message array to a plain string */
1258 foreach ($message as $error){
1259 if ($complete == ""){
1260 $complete= $error;
1261 } else {
1262 $complete= "$error<br>$complete";
1263 }
1264 }
1266 /* Fill ERROR variable with nice error dialog */
1267 msg_dialog::display(_("Error"), $complete, ERROR_DIALOG);
1268 }
1271 function show_ldap_error($message, $addon= "")
1272 {
1273 if (!preg_match("/Success/i", $message)){
1274 if ($addon == ""){
1275 msg_dialog::display(_("LDAP error:"), $message, ERROR_DIALOG);
1276 } else {
1277 if(!preg_match("/No such object/i",$message)){
1278 msg_dialog::display(sprintf(_("LDAP error in plugin '%s':"),"<i>".$addon."</i>"),$message,ERROR_DIALOG);
1279 }
1280 }
1281 return TRUE;
1282 } else {
1283 return FALSE;
1284 }
1285 }
1288 function rewrite($s)
1289 {
1290 global $REWRITE;
1292 foreach ($REWRITE as $key => $val){
1293 $s= preg_replace("/$key/", "$val", $s);
1294 }
1296 return ($s);
1297 }
1300 function dn2base($dn)
1301 {
1302 global $config;
1304 if (get_people_ou() != ""){
1305 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1306 }
1307 if (get_groups_ou() != ""){
1308 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1309 }
1310 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1312 return ($base);
1313 }
1317 function check_command($cmdline)
1318 {
1319 $cmd= preg_replace("/ .*$/", "", $cmdline);
1321 /* Check if command exists in filesystem */
1322 if (!file_exists($cmd)){
1323 return (FALSE);
1324 }
1326 /* Check if command is executable */
1327 if (!is_executable($cmd)){
1328 return (FALSE);
1329 }
1331 return (TRUE);
1332 }
1335 function print_header($image, $headline, $info= "")
1336 {
1337 $display= "<div class=\"plugtop\">\n";
1338 $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";
1339 $display.= "</div>\n";
1341 if ($info != ""){
1342 $display.= "<div class=\"pluginfo\">\n";
1343 $display.= "$info";
1344 $display.= "</div>\n";
1345 } else {
1346 $display.= "<div style=\"height:5px;\">\n";
1347 $display.= " ";
1348 $display.= "</div>\n";
1349 }
1350 return ($display);
1351 }
1354 function range_selector($dcnt,$start,$range=25,$post_var=false)
1355 {
1357 /* Entries shown left and right from the selected entry */
1358 $max_entries= 10;
1360 /* Initialize and take care that max_entries is even */
1361 $output="";
1362 if ($max_entries & 1){
1363 $max_entries++;
1364 }
1366 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1367 $range= $_POST[$post_var];
1368 }
1370 /* Prevent output to start or end out of range */
1371 if ($start < 0 ){
1372 $start= 0 ;
1373 }
1374 if ($start >= $dcnt){
1375 $start= $range * (int)(($dcnt / $range) + 0.5);
1376 }
1378 $numpages= (($dcnt / $range));
1379 if(((int)($numpages))!=($numpages)){
1380 $numpages = (int)$numpages + 1;
1381 }
1382 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1383 return ("");
1384 }
1385 $ppage= (int)(($start / $range) + 0.5);
1388 /* Align selected page to +/- max_entries/2 */
1389 $begin= $ppage - $max_entries/2;
1390 $end= $ppage + $max_entries/2;
1392 /* Adjust begin/end, so that the selected value is somewhere in
1393 the middle and the size is max_entries if possible */
1394 if ($begin < 0){
1395 $end-= $begin + 1;
1396 $begin= 0;
1397 }
1398 if ($end > $numpages) {
1399 $end= $numpages;
1400 }
1401 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1402 $begin= $end - $max_entries;
1403 }
1405 if($post_var){
1406 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1407 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1408 }else{
1409 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1410 }
1412 /* Draw decrement */
1413 if ($start > 0 ) {
1414 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1415 (($start-$range))."\">".
1416 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1417 }
1419 /* Draw pages */
1420 for ($i= $begin; $i < $end; $i++) {
1421 if ($ppage == $i){
1422 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1423 validate($_GET['plug'])."&start=".
1424 ($i*$range)."\"> ".($i+1)." </a>";
1425 } else {
1426 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1427 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1428 }
1429 }
1431 /* Draw increment */
1432 if($start < ($dcnt-$range)) {
1433 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1434 (($start+($range)))."\">".
1435 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1436 }
1438 if(($post_var)&&($numpages)){
1439 $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()'>";
1440 foreach(array(20,50,100,200,"all") as $num){
1441 if($num == "all"){
1442 $var = 10000;
1443 }else{
1444 $var = $num;
1445 }
1446 if($var == $range){
1447 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1448 }else{
1449 $output.="\n<option value='".$var."'>".$num."</option>";
1450 }
1451 }
1452 $output.= "</select></td></tr></table></div>";
1453 }else{
1454 $output.= "</div>";
1455 }
1457 return($output);
1458 }
1461 function apply_filter()
1462 {
1463 $apply= "";
1465 $apply= ''.
1466 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1467 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1469 return ($apply);
1470 }
1473 function back_to_main()
1474 {
1475 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1476 _("Back").'"></p><input type="hidden" name="ignore">';
1478 return ($string);
1479 }
1482 function normalize_netmask($netmask)
1483 {
1484 /* Check for notation of netmask */
1485 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1486 $num= (int)($netmask);
1487 $netmask= "";
1489 for ($byte= 0; $byte<4; $byte++){
1490 $result=0;
1492 for ($i= 7; $i>=0; $i--){
1493 if ($num-- > 0){
1494 $result+= pow(2,$i);
1495 }
1496 }
1498 $netmask.= $result.".";
1499 }
1501 return (preg_replace('/\.$/', '', $netmask));
1502 }
1504 return ($netmask);
1505 }
1508 function netmask_to_bits($netmask)
1509 {
1510 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1511 $res= 0;
1513 for ($n= 0; $n<4; $n++){
1514 $start= 255;
1515 $name= "nm$n";
1517 for ($i= 0; $i<8; $i++){
1518 if ($start == (int)($$name)){
1519 $res+= 8 - $i;
1520 break;
1521 }
1522 $start-= pow(2,$i);
1523 }
1524 }
1526 return ($res);
1527 }
1530 function recurse($rule, $variables)
1531 {
1532 $result= array();
1534 if (!count($variables)){
1535 return array($rule);
1536 }
1538 reset($variables);
1539 $key= key($variables);
1540 $val= current($variables);
1541 unset ($variables[$key]);
1543 foreach($val as $possibility){
1544 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1545 $result= array_merge($result, recurse($nrule, $variables));
1546 }
1548 return ($result);
1549 }
1552 function expand_id($rule, $attributes)
1553 {
1554 /* Check for id rule */
1555 if(preg_match('/^id(:|#)\d+$/',$rule)){
1556 return (array("\{$rule}"));
1557 }
1559 /* Check for clean attribute */
1560 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1561 $rule= preg_replace('/^%/', '', $rule);
1562 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1563 return (array($val));
1564 }
1566 /* Check for attribute with parameters */
1567 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1568 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1569 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1570 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1571 $start= preg_replace ('/-.*$/', '', $param);
1572 $stop = preg_replace ('/^[^-]+-/', '', $param);
1574 /* Assemble results */
1575 $result= array();
1576 for ($i= $start; $i<= $stop; $i++){
1577 $result[]= substr($val, 0, $i);
1578 }
1579 return ($result);
1580 }
1582 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1583 return (array($rule));
1584 }
1587 function gen_uids($rule, $attributes)
1588 {
1589 global $config;
1591 /* Search for keys and fill the variables array with all
1592 possible values for that key. */
1593 $part= "";
1594 $trigger= false;
1595 $stripped= "";
1596 $variables= array();
1598 for ($pos= 0; $pos < strlen($rule); $pos++){
1600 if ($rule[$pos] == "{" ){
1601 $trigger= true;
1602 $part= "";
1603 continue;
1604 }
1606 if ($rule[$pos] == "}" ){
1607 $variables[$pos]= expand_id($part, $attributes);
1608 $stripped.= "{".$pos."}";
1609 $trigger= false;
1610 continue;
1611 }
1613 if ($trigger){
1614 $part.= $rule[$pos];
1615 } else {
1616 $stripped.= $rule[$pos];
1617 }
1618 }
1620 /* Recurse through all possible combinations */
1621 $proposed= recurse($stripped, $variables);
1623 /* Get list of used ID's */
1624 $used= array();
1625 $ldap= $config->get_ldap_link();
1626 $ldap->cd($config->current['BASE']);
1627 $ldap->search('(uid=*)');
1629 while($attrs= $ldap->fetch()){
1630 $used[]= $attrs['uid'][0];
1631 }
1633 /* Remove used uids and watch out for id tags */
1634 $ret= array();
1635 foreach($proposed as $uid){
1637 /* Check for id tag and modify uid if needed */
1638 if(preg_match('/\{id:\d+}/',$uid)){
1639 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1641 for ($i= 0; $i < pow(10,$size); $i++){
1642 $number= sprintf("%0".$size."d", $i);
1643 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1644 if (!in_array($res, $used)){
1645 $uid= $res;
1646 break;
1647 }
1648 }
1649 }
1651 if(preg_match('/\{id#\d+}/',$uid)){
1652 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1654 while (true){
1655 mt_srand((double) microtime()*1000000);
1656 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1657 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1658 if (!in_array($res, $used)){
1659 $uid= $res;
1660 break;
1661 }
1662 }
1663 }
1665 /* Don't assign used ones */
1666 if (!in_array($uid, $used)){
1667 $ret[]= $uid;
1668 }
1669 }
1671 return(array_unique($ret));
1672 }
1675 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1676 Need to convert... */
1677 function to_byte($value) {
1678 $value= strtolower(trim($value));
1680 if(!is_numeric(substr($value, -1))) {
1682 switch(substr($value, -1)) {
1683 case 'g':
1684 $mult= 1073741824;
1685 break;
1686 case 'm':
1687 $mult= 1048576;
1688 break;
1689 case 'k':
1690 $mult= 1024;
1691 break;
1692 }
1694 return ($mult * (int)substr($value, 0, -1));
1695 } else {
1696 return $value;
1697 }
1698 }
1701 function in_array_ics($value, $items)
1702 {
1703 if (!is_array($items)){
1704 return (FALSE);
1705 }
1707 foreach ($items as $item){
1708 if (strcasecmp($item, $value) == 0) {
1709 return (TRUE);
1710 }
1711 }
1713 return (FALSE);
1714 }
1717 function generate_alphabet($count= 10)
1718 {
1719 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1720 $alphabet= "";
1721 $c= 0;
1723 /* Fill cells with charaters */
1724 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1725 if ($c == 0){
1726 $alphabet.= "<tr>";
1727 }
1729 $ch = mb_substr($characters, $i, 1, "UTF8");
1730 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1731 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1733 if ($c++ == $count){
1734 $alphabet.= "</tr>";
1735 $c= 0;
1736 }
1737 }
1739 /* Fill remaining cells */
1740 while ($c++ <= $count){
1741 $alphabet.= "<td> </td>";
1742 }
1744 return ($alphabet);
1745 }
1748 function validate($string)
1749 {
1750 return (strip_tags(preg_replace('/\0/', '', $string)));
1751 }
1754 function get_gosa_version()
1755 {
1756 global $svn_revision, $svn_path;
1758 /* Extract informations */
1759 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1761 /* Release or development? */
1762 if (preg_match('%/gosa/trunk/%', $svn_path)){
1763 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1764 } else {
1765 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1766 return (sprintf(_("GOsa $release"), $revision));
1767 }
1768 }
1771 function rmdirRecursive($path, $followLinks=false) {
1772 $dir= opendir($path);
1773 while($entry= readdir($dir)) {
1774 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1775 unlink($path."/".$entry);
1776 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1777 rmdirRecursive($path."/".$entry);
1778 }
1779 }
1780 closedir($dir);
1781 return rmdir($path);
1782 }
1785 function scan_directory($path,$sort_desc=false)
1786 {
1787 $ret = false;
1789 /* is this a dir ? */
1790 if(is_dir($path)) {
1792 /* is this path a readable one */
1793 if(is_readable($path)){
1795 /* Get contents and write it into an array */
1796 $ret = array();
1798 $dir = opendir($path);
1800 /* Is this a correct result ?*/
1801 if($dir){
1802 while($fp = readdir($dir))
1803 $ret[]= $fp;
1804 }
1805 }
1806 }
1807 /* Sort array ascending , like scandir */
1808 sort($ret);
1810 /* Sort descending if parameter is sort_desc is set */
1811 if($sort_desc) {
1812 $ret = array_reverse($ret);
1813 }
1815 return($ret);
1816 }
1819 function clean_smarty_compile_dir($directory)
1820 {
1821 global $svn_revision;
1823 if(is_dir($directory) && is_readable($directory)) {
1824 // Set revision filename to REVISION
1825 $revision_file= $directory."/REVISION";
1827 /* Is there a stamp containing the current revision? */
1828 if(!file_exists($revision_file)) {
1829 // create revision file
1830 create_revision($revision_file, $svn_revision);
1831 } else {
1832 # check for "$config->...['CONFIG']/revision" and the
1833 # contents should match the revision number
1834 if(!compare_revision($revision_file, $svn_revision)){
1835 // If revision differs, clean compile directory
1836 foreach(scan_directory($directory) as $file) {
1837 if(($file==".")||($file=="..")) continue;
1838 if( is_file($directory."/".$file) &&
1839 is_writable($directory."/".$file)) {
1840 // delete file
1841 if(!unlink($directory."/".$file)) {
1842 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1843 // This should never be reached
1844 }
1845 } elseif(is_dir($directory."/".$file) &&
1846 is_writable($directory."/".$file)) {
1847 // Just recursively delete it
1848 rmdirRecursive($directory."/".$file);
1849 }
1850 }
1851 // We should now create a fresh revision file
1852 clean_smarty_compile_dir($directory);
1853 } else {
1854 // Revision matches, nothing to do
1855 }
1856 }
1857 } else {
1858 // Smarty compile dir is not accessible
1859 // (Smarty will warn about this)
1860 }
1861 }
1864 function create_revision($revision_file, $revision)
1865 {
1866 $result= false;
1868 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1869 if($fh= fopen($revision_file, "w")) {
1870 if(fwrite($fh, $revision)) {
1871 $result= true;
1872 }
1873 }
1874 fclose($fh);
1875 } else {
1876 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1877 }
1879 return $result;
1880 }
1883 function compare_revision($revision_file, $revision)
1884 {
1885 // false means revision differs
1886 $result= false;
1888 if(file_exists($revision_file) && is_readable($revision_file)) {
1889 // Open file
1890 if($fh= fopen($revision_file, "r")) {
1891 // Compare File contents with current revision
1892 if($revision == fread($fh, filesize($revision_file))) {
1893 $result= true;
1894 }
1895 } else {
1896 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1897 }
1898 // Close file
1899 fclose($fh);
1900 }
1902 return $result;
1903 }
1906 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1907 {
1908 $str = ""; // Our return value will be saved in this var
1910 $color = dechex($percentage+150);
1911 $color2 = dechex(150 - $percentage);
1912 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1914 $progress = (int)(($percentage /100)*$width);
1916 /* Abort printing out percentage, if divs are to small */
1919 /* If theres a better solution for this, use it... */
1920 $str = "
1921 <div style=\" width:".($width)."px;
1922 height:".($height)."px;
1923 background-color:#000000;
1924 padding:1px;\">
1926 <div style=\" width:".($width)."px;
1927 background-color:#$bgcolor;
1928 height:".($height)."px;\">
1930 <div style=\" width:".$progress."px;
1931 height:".$height."px;
1932 background-color:#".$color2.$color2.$color."; \">";
1935 if(($height >10)&&($showvalue)){
1936 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1937 <b>".$percentage."%</b>
1938 </font>";
1939 }
1941 $str.= "</div></div></div>";
1943 return($str);
1944 }
1947 function array_key_ics($ikey, $items)
1948 {
1949 /* Gather keys, make them lowercase */
1950 $tmp= array();
1951 foreach ($items as $key => $value){
1952 $tmp[strtolower($key)]= $key;
1953 }
1955 if (isset($tmp[strtolower($ikey)])){
1956 return($tmp[strtolower($ikey)]);
1957 }
1959 return ("");
1960 }
1963 function array_differs($src, $dst)
1964 {
1965 /* If the count is differing, the arrays differ */
1966 if (count ($src) != count ($dst)){
1967 return (TRUE);
1968 }
1970 /* So the count is the same - lets check the contents */
1971 $differs= FALSE;
1972 foreach($src as $value){
1973 if (!in_array($value, $dst)){
1974 $differs= TRUE;
1975 }
1976 }
1978 return ($differs);
1979 }
1982 function saveFilter($a_filter, $values)
1983 {
1984 if (isset($_POST['regexit'])){
1985 $a_filter["regex"]= $_POST['regexit'];
1987 foreach($values as $type){
1988 if (isset($_POST[$type])) {
1989 $a_filter[$type]= "checked";
1990 } else {
1991 $a_filter[$type]= "";
1992 }
1993 }
1994 }
1996 /* React on alphabet links if needed */
1997 if (isset($_GET['search'])){
1998 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
1999 if ($s == "**"){
2000 $s= "*";
2001 }
2002 $a_filter['regex']= $s;
2003 }
2005 return ($a_filter);
2006 }
2009 /* Escape all preg_* relevant characters */
2010 function normalizePreg($input)
2011 {
2012 return (addcslashes($input, '[]()|/.*+-'));
2013 }
2016 /* Escape all LDAP filter relevant characters */
2017 function normalizeLdap($input)
2018 {
2019 return (addcslashes($input, '()|'));
2020 }
2023 /* Resturns the difference between to microtime() results in float */
2024 function get_MicroTimeDiff($start , $stop)
2025 {
2026 $a = split("\ ",$start);
2027 $b = split("\ ",$stop);
2029 $secs = $b[1] - $a[1];
2030 $msecs= $b[0] - $a[0];
2032 $ret = (float) ($secs+ $msecs);
2033 return($ret);
2034 }
2037 function get_base_dir()
2038 {
2039 global $BASE_DIR;
2041 return $BASE_DIR;
2042 }
2045 function obj_is_readable($dn, $object, $attribute)
2046 {
2047 global $ui;
2049 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2050 }
2053 function obj_is_writable($dn, $object, $attribute)
2054 {
2055 global $ui;
2057 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2058 }
2061 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2062 {
2063 /* Initialize variables */
2064 $ret = array("count" => 0); // Set count to 0
2065 $next = true; // if false, then skip next loops and return
2066 $cnt = 0; // Current number of loops
2067 $max = 100; // Just for security, prevent looops
2068 $ldap = NULL; // To check if created result a valid
2069 $keep = ""; // save last failed parse string
2071 /* Check each parsed dn in ldap ? */
2072 if($config!==NULL && $verify_in_ldap){
2073 $ldap = $config->get_ldap_link();
2074 }
2076 /* Lets start */
2077 $called = false;
2078 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2080 $cnt ++;
2081 if(!preg_match("/,/",$dn)){
2082 $next = false;
2083 }
2084 $object = preg_replace("/[,].*$/","",$dn);
2085 $dn = preg_replace("/^[^,]+,/","",$dn);
2087 $called = true;
2089 /* Check if current dn is valid */
2090 if($ldap!==NULL){
2091 $ldap->cd($dn);
2092 $ldap->cat($dn,array("dn"));
2093 if($ldap->count()){
2094 $ret[] = $keep.$object;
2095 $keep = "";
2096 }else{
2097 $keep .= $object.",";
2098 }
2099 }else{
2100 $ret[] = $keep.$object;
2101 $keep = "";
2102 }
2103 }
2105 /* No dn was posted */
2106 if($cnt == 0 && !empty($dn)){
2107 $ret[] = $dn;
2108 }
2110 /* Append the rest */
2111 $test = $keep.$dn;
2112 if($called && !empty($test)){
2113 $ret[] = $keep.$dn;
2114 }
2115 $ret['count'] = count($ret) - 1;
2117 return($ret);
2118 }
2121 function get_base_from_hook($dn, $attrib)
2122 {
2123 global $config;
2125 if (isset($config->current['BASE_HOOK'])){
2127 /* Call hook script - if present */
2128 $command= $config->current['BASE_HOOK'];
2130 if ($command != ""){
2131 $command.= " '".LDAP::fix($dn)."' $attrib";
2132 if (check_command($command)){
2133 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2134 exec($command, $output);
2135 if (preg_match("/^[0-9]+$/", $output[0])){
2136 return ($output[0]);
2137 } else {
2138 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2139 return ($config->current['UIDBASE']);
2140 }
2141 } else {
2142 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2143 return ($config->current['UIDBASE']);
2144 }
2146 } else {
2148 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2149 return ($config->current['UIDBASE']);
2151 }
2152 }
2153 }
2156 function check_schema_version($class, $version)
2157 {
2158 return preg_match("/\(v$version\)/", $class['DESC']);
2159 }
2162 function check_schema($cfg,$rfc2307bis = FALSE)
2163 {
2164 $messages= array();
2166 /* Get objectclasses */
2167 $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2168 $objectclasses = $ldap->get_objectclasses();
2169 if(count($objectclasses) == 0){
2170 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2171 }
2173 /* This is the default block used for each entry.
2174 * to avoid unset indexes.
2175 */
2176 $def_check = array("REQUIRED_VERSION" => "0",
2177 "SCHEMA_FILES" => array(),
2178 "CLASSES_REQUIRED" => array(),
2179 "STATUS" => FALSE,
2180 "IS_MUST_HAVE" => FALSE,
2181 "MSG" => "",
2182 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2184 /* The gosa base schema */
2185 $checks['gosaObject'] = $def_check;
2186 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2187 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2188 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2189 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2191 /* GOsa Account class */
2192 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2193 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2194 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2195 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2196 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2198 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2199 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2200 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2201 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2202 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2203 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2205 /* Some other checks */
2206 foreach(array(
2207 "gosaCacheEntry" => array("version" => "2.4"),
2208 "gosaDepartment" => array("version" => "2.4"),
2209 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2210 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2211 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2212 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2213 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2214 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2215 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2216 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2217 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2218 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2219 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2220 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2221 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2222 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2223 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2224 "goLdapServer" => array("version" => "2.4"),
2225 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2226 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2227 "goKrbServer" => array("version" => "2.4"),
2228 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2229 ) as $name => $values){
2231 $checks[$name] = $def_check;
2232 if(isset($values['version'])){
2233 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2234 }
2235 if(isset($values['file'])){
2236 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2237 }
2238 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2239 }
2240 foreach($checks as $name => $value){
2241 foreach($value['CLASSES_REQUIRED'] as $class){
2243 if(!isset($objectclasses[$name])){
2244 $checks[$name]['STATUS'] = FALSE;
2245 if($value['IS_MUST_HAVE']){
2246 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2247 }else{
2248 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2249 }
2250 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2251 $checks[$name]['STATUS'] = FALSE;
2253 if($value['IS_MUST_HAVE']){
2254 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2255 }else{
2256 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2257 }
2258 }else{
2259 $checks[$name]['STATUS'] = TRUE;
2260 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2261 }
2262 }
2263 }
2265 $tmp = $objectclasses;
2267 /* The gosa base schema */
2268 $checks['posixGroup'] = $def_check;
2269 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2270 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2271 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2272 $checks['posixGroup']['STATUS'] = TRUE;
2273 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2274 $checks['posixGroup']['MSG'] = "";
2275 $checks['posixGroup']['INFO'] = "";
2277 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2278 if(isset($tmp['posixGroup'])){
2280 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2281 $checks['posixGroup']['STATUS'] = FALSE;
2282 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2283 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2284 }
2285 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2286 $checks['posixGroup']['STATUS'] = FALSE;
2287 $checks['posixGroup']['MSG'] = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2288 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2289 }
2290 }
2292 return($checks);
2293 }
2296 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2297 {
2298 $tmp = array(
2299 "de_DE" => "German",
2300 "fr_FR" => "French",
2301 "it_IT" => "Italian",
2302 "es_ES" => "Spanish",
2303 "en_US" => "English",
2304 "nl_NL" => "Dutch",
2305 "pl_PL" => "Polish",
2306 "sv_SE" => "Swedish",
2307 "zh_CN" => "Chinese",
2308 "ru_RU" => "Russian");
2310 $tmp2= array(
2311 "de_DE" => _("German"),
2312 "fr_FR" => _("French"),
2313 "it_IT" => _("Italian"),
2314 "es_ES" => _("Spanish"),
2315 "en_US" => _("English"),
2316 "nl_NL" => _("Dutch"),
2317 "pl_PL" => _("Polish"),
2318 "sv_SE" => _("Swedish"),
2319 "zh_CN" => _("Chinese"),
2320 "ru_RU" => _("Russian"));
2322 $ret = array();
2323 if($languages_in_own_language){
2325 $old_lang = setlocale(LC_ALL, 0);
2326 foreach($tmp as $key => $name){
2327 $lang = $key.".UTF-8";
2328 setlocale(LC_ALL, $lang);
2329 if($strip_region_tag){
2330 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2331 }else{
2332 $ret[$key] = _($name)." (".$tmp2[$key].")";
2333 }
2334 }
2335 setlocale(LC_ALL, $old_lang);
2336 }else{
2337 foreach($tmp as $key => $name){
2338 if($strip_region_tag){
2339 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2340 }else{
2341 $ret[$key] = _($name);
2342 }
2343 }
2344 }
2345 return($ret);
2346 }
2349 /* Returns contents of the given POST variable and check magic quotes settings */
2350 function get_post($name)
2351 {
2352 if(!isset($_POST[$name])){
2353 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2354 return(FALSE);
2355 }
2356 if(get_magic_quotes_gpc()){
2357 return(stripcslashes($_POST[$name]));
2358 }else{
2359 return($_POST[$name]);
2360 }
2361 }
2364 /* Return class name in correct case */
2365 function get_correct_class_name($cls)
2366 {
2367 global $class_mapping;
2368 if(isset($class_mapping) && is_array($class_mapping)){
2369 foreach($class_mapping as $class => $file){
2370 if(preg_match("/^".$cls."$/i",$class)){
2371 return($class);
2372 }
2373 }
2374 }
2375 return(FALSE);
2376 }
2379 // change_password, changes the Password, of the given dn
2380 function change_password ($dn, $password, $mode=0, $hash= "")
2381 {
2382 global $config;
2383 $newpass= "";
2385 /* Convert to lower. Methods are lowercase */
2386 $hash= strtolower($hash);
2388 // Get all available encryption Methods
2390 // NON STATIC CALL :)
2391 $tmp = new passwordMethod(session::get('config'));
2392 $available = $tmp->get_available_methods();
2394 // read current password entry for $dn, to detect the encryption Method
2395 $ldap = $config->get_ldap_link();
2396 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2397 $attrs = $ldap->fetch ();
2399 // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2400 if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2401 $deactivated = TRUE;
2402 }else{
2403 $deactivated = FALSE;
2404 }
2406 /* Is ensure that clear passwords will stay clear */
2407 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2408 $hash = "clear";
2409 }
2411 // Detect the encryption Method
2412 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2414 /* Check for supported algorithm */
2415 mt_srand((double) microtime()*1000000);
2417 /* Extract used hash */
2418 if ($hash == ""){
2419 $hash= strtolower($matches[1]);
2420 }
2422 $test = new $available[$hash]($config);
2424 } else {
2425 // User MD5 by default
2426 $hash= "md5";
2427 $test = new $available['md5']($config);
2428 }
2430 /* Feed password backends with information */
2431 $test->dn= $dn;
2432 $test->attrs= $attrs;
2433 $newpass= $test->generate_hash($password);
2435 // Update shadow timestamp?
2436 if (isset($attrs["shadowLastChange"][0])){
2437 $shadow= (int)(date("U") / 86400);
2438 } else {
2439 $shadow= 0;
2440 }
2442 // Write back modified entry
2443 $ldap->cd($dn);
2444 $attrs= array();
2446 // Not for groups
2447 if ($mode == 0){
2449 if ($shadow != 0){
2450 $attrs['shadowLastChange']= $shadow;
2451 }
2453 // Create SMB Password
2454 $attrs= generate_smb_nt_hash($password);
2455 }
2457 /* Readd ! if user was deactivated */
2458 if($deactivated){
2459 $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2460 }
2462 $attrs['userPassword']= array();
2463 $attrs['userPassword']= $newpass;
2465 $ldap->modify($attrs);
2467 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2469 if ($ldap->error != 'Success') {
2470 msg_dialog::display(_("LDAP error"), sprintf(_('Setting the password failed!').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
2471 } else {
2473 /* Run backend method for change/create */
2474 $test->set_password($password);
2476 /* Find postmodify entries for this class */
2477 $command= $config->search("password", "POSTMODIFY",array('menu'));
2479 if ($command != ""){
2480 /* Walk through attribute list */
2481 $command= preg_replace("/%userPassword/", $password, $command);
2482 $command= preg_replace("/%dn/", $dn, $command);
2484 if (check_command($command)){
2485 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2486 exec($command);
2487 } else {
2488 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2489 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2490 }
2491 }
2492 }
2493 }
2496 // Return something like array['sambaLMPassword']= "lalla..."
2497 function generate_smb_nt_hash($password)
2498 {
2499 global $config;
2500 $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2501 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2503 exec($tmp, $ar);
2504 flush();
2505 reset($ar);
2506 $hash= current($ar);
2507 if ($hash == "") {
2508 msg_dialog::display(_("Configuration error"), _("Setting for SMBHASH in gosa.conf is incorrect! Cannot change Samba password."), ERROR_DIALOG);
2509 } else {
2510 list($lm,$nt)= split (":", trim($hash));
2512 if ($config->current['SAMBAVERSION'] == 3) {
2513 $attrs['sambaLMPassword']= $lm;
2514 $attrs['sambaNTPassword']= $nt;
2515 $attrs['sambaPwdLastSet']= date('U');
2516 $attrs['sambaBadPasswordCount']= "0";
2517 $attrs['sambaBadPasswordTime']= "0";
2518 } else {
2519 $attrs['lmPassword']= $lm;
2520 $attrs['ntPassword']= $nt;
2521 $attrs['pwdLastSet']= date('U');
2522 }
2523 return($attrs);
2524 }
2525 }
2528 function crypt_single($string,$enc_type )
2529 {
2530 return( passwordMethod::crypt_single_str($string,$enc_type));
2531 }
2534 function getEntryCSN($dn)
2535 {
2536 global $config;
2537 if(empty($dn) || !is_object($config)){
2538 return("");
2539 }
2541 /* Get attribute that we should use as serial number */
2542 if(isset($config->current['UNIQ_IDENTIFIER'])){
2543 $attr = $config->current['UNIQ_IDENTIFIER'];
2544 }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2545 $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2546 }
2547 if(!empty($attr)){
2548 $ldap = $config->get_ldap_link();
2549 $ldap->cat($dn,array($attr));
2550 $csn = $ldap->fetch();
2551 if(isset($csn[$attr][0])){
2552 return($csn[$attr][0]);
2553 }
2554 }
2555 return("");
2556 }
2559 function display_error_page()
2560 {
2561 $smarty= get_smarty();
2562 $smarty->display(get_template_path('headers.tpl'));
2563 echo "<body>".msg_dialog::get_dialogs()."</body></html>";
2564 exit();
2565 }
2567 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2568 ?>