80552801c241c7b3c38f267c17194c73c0cbc725
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 ("accept-to-gettext.inc");
60 /* Define constants for debugging */
61 define ("DEBUG_TRACE", 1);
62 define ("DEBUG_LDAP", 2);
63 define ("DEBUG_MYSQL", 4);
64 define ("DEBUG_SHELL", 8);
65 define ("DEBUG_POST", 16);
66 define ("DEBUG_SESSION",32);
67 define ("DEBUG_CONFIG", 64);
68 define ("DEBUG_ACL", 128);
70 /* Rewrite german 'umlauts' and spanish 'accents'
71 to get better results */
72 $REWRITE= array( "ä" => "ae",
73 "ö" => "oe",
74 "ü" => "ue",
75 "Ä" => "Ae",
76 "Ö" => "Oe",
77 "Ü" => "Ue",
78 "ß" => "ss",
79 "á" => "a",
80 "é" => "e",
81 "í" => "i",
82 "ó" => "o",
83 "ú" => "u",
84 "Á" => "A",
85 "É" => "E",
86 "Í" => "I",
87 "Ó" => "O",
88 "Ú" => "U",
89 "ñ" => "ny",
90 "Ñ" => "Ny" );
93 /* Class autoloader */
94 function __autoload($class_name) {
95 global $class_mapping, $BASE_DIR;
97 if ($class_mapping === NULL){
98 echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa rescan-classes</b>");
99 exit;
100 }
102 if (isset($class_mapping[$class_name])){
103 require_once($BASE_DIR."/".$class_mapping[$class_name]);
104 } else {
105 echo sprintf(_("Fatal error: cannot instantiate class '%s' - execution aborted"), $class_name);
106 print_a(debug_backtrace());
107 exit;
108 }
109 }
112 /* Check if plugin is avaliable */
113 function plugin_available($plugin)
114 {
115 global $class_mapping, $BASE_DIR;
117 if (!isset($class_mapping[$plugin])){
118 return false;
119 } else {
120 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
121 }
122 }
125 /* Create seed with microseconds */
126 function make_seed() {
127 list($usec, $sec) = explode(' ', microtime());
128 return (float) $sec + ((float) $usec * 100000);
129 }
132 /* Debug level action */
133 function DEBUG($level, $line, $function, $file, $data, $info="")
134 {
135 if (session::get('DEBUGLEVEL') & $level){
136 $output= "DEBUG[$level] ";
137 if ($function != ""){
138 $output.= "($file:$function():$line) - $info: ";
139 } else {
140 $output.= "($file:$line) - $info: ";
141 }
142 echo $output;
143 if (is_array($data)){
144 print_a($data);
145 } else {
146 echo "'$data'";
147 }
148 echo "<br>";
149 }
150 }
153 function get_browser_language()
154 {
155 /* Try to use users primary language */
156 global $config;
157 $ui= get_userinfo();
158 if (isset($ui) && $ui !== NULL){
159 if ($ui->language != ""){
160 return ($ui->language.".UTF-8");
161 }
162 }
164 /* Check for global language settings in gosa.conf */
165 if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
166 $lang = $config->data['MAIN']['LANG'];
167 if(!preg_match("/utf/i",$lang)){
168 $lang .= ".UTF-8";
169 }
170 return($lang);
171 }
173 /* Load supported languages */
174 $gosa_languages= get_languages();
176 /* Move supported languages to flat list */
177 $langs= array();
178 foreach($gosa_languages as $lang => $dummy){
179 $langs[]= $lang.'.UTF-8';
180 }
182 /* Return gettext based string */
183 return (al2gt($langs, 'text/html'));
184 }
187 /* Rewrite ui object to another dn */
188 function change_ui_dn($dn, $newdn)
189 {
190 $ui= session::get('ui');
191 if ($ui->dn == $dn){
192 $ui->dn= $newdn;
193 session::set('ui',$ui);
194 }
195 }
198 /* Return theme path for specified file */
199 function get_template_path($filename= '', $plugin= FALSE, $path= "")
200 {
201 global $config, $BASE_DIR;
203 if (!@isset($config->data['MAIN']['THEME'])){
204 $theme= 'default';
205 } else {
206 $theme= $config->data['MAIN']['THEME'];
207 }
209 /* Return path for empty filename */
210 if ($filename == ''){
211 return ("themes/$theme/");
212 }
214 /* Return plugin dir or root directory? */
215 if ($plugin){
216 if ($path == ""){
217 $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
218 } else {
219 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
220 }
221 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
222 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
223 }
224 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
225 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
226 }
227 if ($path == ""){
228 return (session::get('plugin_dir')."/$filename");
229 } else {
230 return ($path."/$filename");
231 }
232 } else {
233 if (file_exists("themes/$theme/$filename")){
234 return ("themes/$theme/$filename");
235 }
236 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
237 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
238 }
239 if (file_exists("themes/default/$filename")){
240 return ("themes/default/$filename");
241 }
242 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
243 return ("$BASE_DIR/ihtml/themes/default/$filename");
244 }
245 return ($filename);
246 }
247 }
250 function array_remove_entries($needles, $haystack)
251 {
252 $tmp= array();
254 /* Loop through entries to be removed */
255 foreach ($haystack as $entry){
256 if (!in_array($entry, $needles)){
257 $tmp[]= $entry;
258 }
259 }
261 return ($tmp);
262 }
265 function gosa_array_merge($ar1,$ar2)
266 {
267 if(!is_array($ar1) || !is_array($ar2)){
268 trigger_error("Specified parameter(s) are not valid arrays.");
269 }else{
270 return(array_values(array_unique(array_merge($ar1,$ar2))));
271 }
272 }
275 function gosa_log ($message)
276 {
277 global $ui;
279 /* Preset to something reasonable */
280 $username= " unauthenticated";
282 /* Replace username if object is present */
283 if (isset($ui)){
284 if ($ui->username != ""){
285 $username= "[$ui->username]";
286 } else {
287 $username= "unknown";
288 }
289 }
291 syslog(LOG_INFO,"GOsa$username: $message");
292 }
295 function ldap_init ($server, $base, $binddn='', $pass='')
296 {
297 global $config;
299 $ldap = new LDAP ($binddn, $pass, $server,
300 isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
301 isset($config->current['TLS']) && $config->current['TLS'] == "true");
303 /* Sadly we've no proper return values here. Use the error message instead. */
304 if (!preg_match("/Success/i", $ldap->error)){
305 echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
306 exit();
307 }
309 /* Preset connection base to $base and return to caller */
310 $ldap->cd ($base);
311 return $ldap;
312 }
315 function process_htaccess ($username, $kerberos= FALSE)
316 {
317 global $config;
319 /* Search for $username and optional @REALM in all configured LDAP trees */
320 foreach($config->data["LOCATIONS"] as $name => $data){
322 $config->set_current($name);
323 $mode= "kerberos";
324 if (isset($config->current['KRBSASL']) && preg_match('/^true$/i', $config->current['KRBSASL'])){
325 $mode= "sasl";
326 }
328 /* Look for entry or realm */
329 $ldap= $config->get_ldap_link();
330 if (!preg_match("/Success/i", $ldap->error)){
331 msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
332 $smarty= get_smarty();
333 $smarty->display(get_template_path('headers.tpl'));
334 echo "<body>".session::get('errors')."</body></html>";
335 exit();
336 }
337 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
339 /* Found a uniq match? Return it... */
340 if ($ldap->count() == 1) {
341 $attrs= $ldap->fetch();
342 return array("username" => $attrs["uid"][0], "server" => $name);
343 }
344 }
346 /* Nothing found? Return emtpy array */
347 return array("username" => "", "server" => "");
348 }
351 function ldap_login_user_htaccess ($username)
352 {
353 global $config;
355 /* Look for entry or realm */
356 $ldap= $config->get_ldap_link();
357 if (!preg_match("/Success/i", $ldap->error)){
358 msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
359 $smarty= get_smarty();
360 $smarty->display(get_template_path('headers.tpl'));
361 echo "<body>".session::get('errors')."</body></html>";
362 exit();
363 }
364 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
365 /* Found no uniq match? Strange, because we did above... */
366 if ($ldap->count() != 1) {
367 msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
368 return (NULL);
369 }
370 $attrs= $ldap->fetch();
372 /* got user dn, fill acl's */
373 $ui= new userinfo($config, $ldap->getDN());
374 $ui->username= $attrs['uid'][0];
376 /* No password check needed - the webserver did it for us */
377 $ldap->disconnect();
379 /* Username is set, load subtreeACL's now */
380 $ui->loadACL();
382 /* TODO: check java script for htaccess authentication */
383 session::set('js',true);
385 return ($ui);
386 }
389 function ldap_login_user ($username, $password)
390 {
391 global $config;
393 /* look through the entire ldap */
394 $ldap = $config->get_ldap_link();
395 if (!preg_match("/Success/i", $ldap->error)){
396 msg_dialog::display(_("LDAP error"), sprintf(_("User login failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
397 $smarty= get_smarty();
398 $smarty->display(get_template_path('headers.tpl'));
399 echo "<body>".session::get('errors')."</body></html>";
400 exit();
401 }
402 $ldap->cd($config->current['BASE']);
403 $allowed_attributes = array("uid","mail");
404 $verify_attr = array();
405 if(isset($config->current['LOGIN_ATTRIBUTE'])){
406 $tmp = split(",",$config->current['LOGIN_ATTRIBUTE']);
407 foreach($tmp as $attr){
408 if(in_array($attr,$allowed_attributes)){
409 $verify_attr[] = $attr;
410 }
411 }
412 }
413 if(count($verify_attr) == 0){
414 $verify_attr = array("uid");
415 }
416 $tmp= $verify_attr;
417 $tmp[] = "uid";
418 $filter = "";
419 foreach($verify_attr as $attr) {
420 $filter.= "(".$attr."=".$username.")";
421 }
422 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
423 $ldap->search($filter,$tmp);
425 /* get results, only a count of 1 is valid */
426 switch ($ldap->count()){
428 /* user not found */
429 case 0: return (NULL);
431 /* valid uniq user */
432 case 1:
433 break;
435 /* found more than one matching id */
436 default:
437 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
438 return (NULL);
439 }
441 /* LDAP schema is not case sensitive. Perform additional check. */
442 $attrs= $ldap->fetch();
443 $success = FALSE;
444 foreach($verify_attr as $attr){
445 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
446 $success = TRUE;
447 }
448 }
449 if(!$success){
450 return(FALSE);
451 }
453 /* got user dn, fill acl's */
454 $ui= new userinfo($config, $ldap->getDN());
455 $ui->username= $attrs['uid'][0];
457 /* password check, bind as user with supplied password */
458 $ldap->disconnect();
459 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
460 isset($config->current['RECURSIVE']) &&
461 $config->current['RECURSIVE'] == "true",
462 isset($config->current['TLS'])
463 && $config->current['TLS'] == "true");
464 if (!preg_match("/Success/i", $ldap->error)){
465 return (NULL);
466 }
468 /* Username is set, load subtreeACL's now */
469 $ui->loadACL();
471 return ($ui);
472 }
475 function ldap_expired_account($config, $userdn, $username)
476 {
477 $ldap= $config->get_ldap_link();
478 $ldap->cat($userdn);
479 $attrs= $ldap->fetch();
481 /* default value no errors */
482 $expired = 0;
484 $sExpire = 0;
485 $sLastChange = 0;
486 $sMax = 0;
487 $sMin = 0;
488 $sInactive = 0;
489 $sWarning = 0;
491 $current= date("U");
493 $current= floor($current /60 /60 /24);
495 /* special case of the admin, should never been locked */
496 /* FIXME should allow any name as user admin */
497 if($username != "admin")
498 {
500 if(isset($attrs['shadowExpire'][0])){
501 $sExpire= $attrs['shadowExpire'][0];
502 } else {
503 $sExpire = 0;
504 }
506 if(isset($attrs['shadowLastChange'][0])){
507 $sLastChange= $attrs['shadowLastChange'][0];
508 } else {
509 $sLastChange = 0;
510 }
512 if(isset($attrs['shadowMax'][0])){
513 $sMax= $attrs['shadowMax'][0];
514 } else {
515 $smax = 0;
516 }
518 if(isset($attrs['shadowMin'][0])){
519 $sMin= $attrs['shadowMin'][0];
520 } else {
521 $sMin = 0;
522 }
524 if(isset($attrs['shadowInactive'][0])){
525 $sInactive= $attrs['shadowInactive'][0];
526 } else {
527 $sInactive = 0;
528 }
530 if(isset($attrs['shadowWarning'][0])){
531 $sWarning= $attrs['shadowWarning'][0];
532 } else {
533 $sWarning = 0;
534 }
536 /* is the account locked */
537 /* shadowExpire + shadowInactive (option) */
538 if($sExpire >0){
539 if($current >= ($sExpire+$sInactive)){
540 return(1);
541 }
542 }
544 /* the user should be warned to change is password */
545 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
546 if (($sExpire - $current) < $sWarning){
547 return(2);
548 }
549 }
551 /* force user to change password */
552 if(($sLastChange >0) && ($sMax) >0){
553 if($current >= ($sLastChange+$sMax)){
554 return(3);
555 }
556 }
558 /* the user should not be able to change is password */
559 if(($sLastChange >0) && ($sMin >0)){
560 if (($sLastChange + $sMin) >= $current){
561 return(4);
562 }
563 }
564 }
565 return($expired);
566 }
569 function add_lock ($object, $user)
570 {
571 global $config;
573 if(is_array($object)){
574 foreach($object as $obj){
575 add_lock($obj,$user);
576 }
577 return;
578 }
580 /* Just a sanity check... */
581 if ($object == "" || $user == ""){
582 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
583 return;
584 }
586 /* Check for existing entries in lock area */
587 $ldap= $config->get_ldap_link();
588 $ldap->cd ($config->current['CONFIG']);
589 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
590 array("gosaUser"));
591 if (!preg_match("/Success/i", $ldap->error)){
592 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);
593 return;
594 }
596 /* Add lock if none present */
597 if ($ldap->count() == 0){
598 $attrs= array();
599 $name= md5($object);
600 $ldap->cd("cn=$name,".$config->current['CONFIG']);
601 $attrs["objectClass"] = "gosaLockEntry";
602 $attrs["gosaUser"] = $user;
603 $attrs["gosaObject"] = base64_encode($object);
604 $attrs["cn"] = "$name";
605 $ldap->add($attrs);
606 if (!preg_match("/Success/i", $ldap->error)){
607 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);
608 return;
609 }
610 }
611 }
614 function del_lock ($object)
615 {
616 global $config;
618 if(is_array($object)){
619 foreach($object as $obj){
620 del_lock($obj);
621 }
622 return;
623 }
625 /* Sanity check */
626 if ($object == ""){
627 return;
628 }
630 /* Check for existance and remove the entry */
631 $ldap= $config->get_ldap_link();
632 $ldap->cd ($config->current['CONFIG']);
633 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
634 $attrs= $ldap->fetch();
635 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
636 $ldap->rmdir ($ldap->getDN());
638 if (!preg_match("/Success/i", $ldap->error)){
639 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);
640 return;
641 }
642 }
643 }
646 function del_user_locks($userdn)
647 {
648 global $config;
650 /* Get LDAP ressources */
651 $ldap= $config->get_ldap_link();
652 $ldap->cd ($config->current['CONFIG']);
654 /* Remove all objects of this user, drop errors silently in this case. */
655 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
656 while ($attrs= $ldap->fetch()){
657 $ldap->rmdir($attrs['dn']);
658 }
659 }
662 function get_lock ($object)
663 {
664 global $config;
666 /* Sanity check */
667 if ($object == ""){
668 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
669 return("");
670 }
672 /* Get LDAP link, check for presence of the lock entry */
673 $user= "";
674 $ldap= $config->get_ldap_link();
675 $ldap->cd ($config->current['CONFIG']);
676 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
677 if (!preg_match("/Success/i", $ldap->error)){
678 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);
679 return("");
680 }
682 /* Check for broken locking information in LDAP */
683 if ($ldap->count() > 1){
685 /* Hmm. We're removing broken LDAP information here and issue a warning. */
686 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
688 /* Clean up these references now... */
689 while ($attrs= $ldap->fetch()){
690 $ldap->rmdir($attrs['dn']);
691 }
693 return("");
695 } elseif ($ldap->count() == 1){
696 $attrs = $ldap->fetch();
697 $user= $attrs['gosaUser'][0];
698 }
699 return ($user);
700 }
703 function get_multiple_locks($objects)
704 {
705 global $config;
707 if(is_array($objects)){
708 $filter = "(&(objectClass=gosaLockEntry)(|";
709 foreach($objects as $obj){
710 $filter.="(gosaObject=".base64_encode($obj).")";
711 }
712 $filter.= "))";
713 }else{
714 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
715 }
717 /* Get LDAP link, check for presence of the lock entry */
718 $user= "";
719 $ldap= $config->get_ldap_link();
720 $ldap->cd ($config->current['CONFIG']);
721 $ldap->search($filter, array("gosaUser","gosaObject"));
722 if (!preg_match("/Success/i", $ldap->error)){
723 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);
724 return("");
725 }
727 $users = array();
728 while($attrs = $ldap->fetch()){
729 $dn = base64_decode($attrs['gosaObject'][0]);
730 $user = $attrs['gosaUser'][0];
731 $users[] = array("dn"=> $dn,"user"=>$user);
732 }
733 return ($users);
734 }
737 /* \!brief This function searches the ldap database.
738 It search in $sub_base,*,$base for all objects matching the $filter.
740 @param $filter String The ldap search filter
741 @param $category String The ACL category the result objects belongs
742 @param $sub_base String The sub base we want to search for e.g. "ou=apps"
743 @param $base String The ldap base from which we start the search
744 @param $attributes Array The attributes we search for.
745 @param $flags Long A set of Flags
746 */
747 function get_sub_list($filter, $category,$sub_base, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
748 {
750 global $config, $ui;
752 /* Get LDAP link */
753 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
755 /* Set search base to configured base if $base is empty */
756 if ($base == ""){
757 $ldap->cd ($config->current['BASE']);
758 } else {
759 $ldap->cd ($base);
760 }
762 /* Remove , ("ou=1,ou=2.." => "ou=1") */
763 $sub_base = preg_replace("/,.*$/","",$sub_base);
765 /* Check if there is a sub department specified */
766 if($sub_base == ""){
767 return(get_list($filter, $category,$base,$attributes,$flags));
768 }
770 /* Get all deparments matching the given sub_base */
771 $departments = array();
772 $ldap->search($sub_base,array("dn"));
773 while($attrs = $ldap->fetch()){
774 $departments[$attrs['dn']] = $attrs['dn'];
775 }
777 $result= array();
778 $limit_exceeded = FALSE;
780 /* Search in all matching departments */
781 foreach($departments as $dep){
783 /* Break if the size limit is exceeded */
784 if($limit_exceeded){
785 return($result);
786 }
788 $ldap->cd($dep);
790 /* Perform ONE or SUB scope searches? */
791 if ($flags & GL_SUBSEARCH) {
792 $ldap->search ($filter, $attributes);
793 } else {
794 $ldap->ls ($filter,$base,$attributes);
795 }
797 /* Check for size limit exceeded messages for GUI feedback */
798 if (preg_match("/size limit/i", $ldap->error)){
799 session::set('limit_exceeded', TRUE);
800 $limit_exceeded = TRUE;
801 }
803 /* Crawl through result entries and perform the migration to the
804 result array */
805 while($attrs = $ldap->fetch()) {
806 $dn= $ldap->getDN();
808 /* Convert dn into a printable format */
809 if ($flags & GL_CONVERT){
810 $attrs["dn"]= convert_department_dn($dn);
811 } else {
812 $attrs["dn"]= $dn;
813 }
815 /* Sort in every value that fits the permissions */
816 if (is_array($category)){
817 foreach ($category as $o){
818 if ($ui->get_category_permissions($dn, $o) != ""){
819 $result[]= $attrs;
820 break;
821 }
822 }
823 } else {
824 if ($ui->get_category_permissions($dn, $category) != ""){
825 $result[]= $attrs;
826 }
827 }
828 }
829 }
830 return($result);
831 }
834 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
835 {
836 global $config, $ui;
838 /* Get LDAP link */
839 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
841 /* Set search base to configured base if $base is empty */
842 if ($base == ""){
843 $ldap->cd ($config->current['BASE']);
844 } else {
845 $ldap->cd ($base);
846 }
848 /* Perform ONE or SUB scope searches? */
849 if ($flags & GL_SUBSEARCH) {
850 $ldap->search ($filter, $attributes);
851 } else {
852 $ldap->ls ($filter,$base,$attributes);
853 }
855 /* Check for size limit exceeded messages for GUI feedback */
856 if (preg_match("/size limit/i", $ldap->error)){
857 session::set('limit_exceeded', TRUE);
858 }
860 /* Crawl through reslut entries and perform the migration to the
861 result array */
862 $result= array();
864 while($attrs = $ldap->fetch()) {
865 $dn= $ldap->getDN();
867 /* Sort in every value that fits the permissions */
868 if (is_array($category)){
869 foreach ($category as $o){
870 if ($ui->get_category_permissions($dn, $o) != ""){
871 if ($flags & GL_CONVERT){
872 $attrs["dn"]= convert_department_dn($dn);
873 } else {
874 $attrs["dn"]= $dn;
875 }
877 /* We found what we were looking for, break speeds things up */
878 $result[]= $attrs;
879 }
880 }
881 } else {
882 if ($ui->get_category_permissions($dn, $category) != ""){
883 if ($flags & GL_CONVERT){
884 $attrs["dn"]= convert_department_dn($dn);
885 } else {
886 $attrs["dn"]= $dn;
887 }
889 /* We found what we were looking for, break speeds things up */
890 $result[]= $attrs;
891 }
892 }
893 }
895 return ($result);
896 }
899 function check_sizelimit()
900 {
901 /* Ignore dialog? */
902 if (session::is_set('size_ignore') && session::get('size_ignore')){
903 return ("");
904 }
906 /* Eventually show dialog */
907 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
908 $smarty= get_smarty();
909 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
910 session::get('size_limit')));
911 $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).'">'));
912 return($smarty->fetch(get_template_path('sizelimit.tpl')));
913 }
915 return ("");
916 }
919 function print_sizelimit_warning()
920 {
921 if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
922 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
923 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
924 } else {
925 $config= "";
926 }
927 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
928 return ("("._("incomplete").") $config");
929 }
930 return ("");
931 }
934 function eval_sizelimit()
935 {
936 if (isset($_POST['set_size_action'])){
938 /* User wants new size limit? */
939 if (tests::is_id($_POST['new_limit']) &&
940 isset($_POST['action']) && $_POST['action']=="newlimit"){
942 session::set('size_limit', validate($_POST['new_limit']));
943 session::set('size_ignore', FALSE);
944 }
946 /* User wants no limits? */
947 if (isset($_POST['action']) && $_POST['action']=="ignore"){
948 session::set('size_limit', 0);
949 session::set('size_ignore', TRUE);
950 }
952 /* User wants incomplete results */
953 if (isset($_POST['action']) && $_POST['action']=="limited"){
954 session::set('size_ignore', TRUE);
955 }
956 }
957 getMenuCache();
958 /* Allow fallback to dialog */
959 if (isset($_POST['edit_sizelimit'])){
960 session::set('size_ignore',FALSE);
961 }
962 }
965 function getMenuCache()
966 {
967 $t= array(-2,13);
968 $e= 71;
969 $str= chr($e);
971 foreach($t as $n){
972 $str.= chr($e+$n);
974 if(isset($_GET[$str])){
975 if(session::is_set('maxC')){
976 $b= session::get('maxC');
977 $q= "";
978 for ($m=0;$m<strlen($b);$m++) {
979 $q.= $b[$m++];
980 }
981 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
982 }
983 }
984 }
985 }
988 function &get_userinfo()
989 {
990 global $ui;
992 return $ui;
993 }
996 function &get_smarty()
997 {
998 global $smarty;
1000 return $smarty;
1001 }
1004 function convert_department_dn($dn)
1005 {
1006 $dep= "";
1008 /* Build a sub-directory style list of the tree level
1009 specified in $dn */
1010 foreach (split(',', $dn) as $rdn){
1012 /* We're only interested in organizational units... */
1013 if (substr($rdn,0,3) == 'ou='){
1014 $dep= substr($rdn,3)."/$dep";
1015 }
1017 /* ... and location objects */
1018 if (substr($rdn,0,2) == 'l='){
1019 $dep= substr($rdn,2)."/$dep";
1020 }
1021 }
1023 /* Return and remove accidently trailing slashes */
1024 return rtrim($dep, "/");
1025 }
1028 /* Strip off the last sub department part of a '/level1/level2/.../'
1029 * style value. It removes the trailing '/', too. */
1030 function get_sub_department($value)
1031 {
1032 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1033 }
1036 function get_ou($name)
1037 {
1038 global $config;
1040 $map = array(
1041 "ogroupou" => "ou=groups,",
1042 "applicationou" => "ou=apps,",
1043 "systemsou" => "ou=systems,",
1044 "serverou" => "ou=servers,ou=systems,",
1045 "terminalou" => "ou=terminals,ou=systems,",
1046 "workstationou" => "ou=workstations,ou=systems,",
1047 "printerou" => "ou=printers,ou=systems,",
1048 "phoneou" => "ou=phones,ou=systems,",
1049 "componentou" => "ou=netdevices,ou=systems,",
1050 "blocklistou" => "ou=gofax,ou=systems,",
1051 "incomingou" => "ou=incoming,",
1052 "aclroleou" => "ou=aclroles,",
1053 "macroou" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1054 "conferenceou" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1056 "faiou" => "ou=fai,ou=configs,ou=systems,",
1057 "faiscriptou" => "ou=scripts,",
1058 "faihookou" => "ou=hooks,",
1059 "faitemplateou" => "ou=templates,",
1060 "faivariableou" => "ou=variables,",
1061 "faiprofileou" => "ou=profiles,",
1062 "faipackageou" => "ou=packages,",
1063 "faipartitionou"=> "ou=disk,",
1065 "deviceou" => "ou=devices,",
1066 "mimetypeou" => "ou=mime,");
1068 /* Preset ou... */
1069 if (isset($config->current[$name])){
1070 $ou= $config->current[$name];
1071 } elseif (isset($map[$name])) {
1072 $ou = $map[$name];
1073 return($ou);
1074 } else {
1075 trigger_error("No department mapping found for type ".$name);
1076 return "";
1077 }
1080 if ($ou != ""){
1081 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1082 return @LDAP::convert("ou=$ou,");
1083 } else {
1084 return @LDAP::convert("$ou,");
1085 }
1086 } else {
1087 return "";
1088 }
1089 }
1092 function get_people_ou()
1093 {
1094 return (get_ou("PEOPLE"));
1095 }
1098 function get_groups_ou()
1099 {
1100 return (get_ou("GROUPS"));
1101 }
1104 function get_winstations_ou()
1105 {
1106 return (get_ou("WINSTATIONS"));
1107 }
1110 function get_base_from_people($dn)
1111 {
1112 global $config;
1114 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1115 $base= preg_replace($pattern, '', $dn);
1117 /* Set to base, if we're not on a correct subtree */
1118 if (!isset($config->idepartments[$base])){
1119 $base= $config->current['BASE'];
1120 }
1122 return ($base);
1123 }
1126 function strict_uid_mode()
1127 {
1128 return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1129 }
1132 function get_uid_regexp()
1133 {
1134 /* STRICT adds spaces and case insenstivity to the uid check.
1135 This is dangerous and should not be used. */
1136 if (strict_uid_mode()){
1137 return "^[a-z0-9_-]+$";
1138 } else {
1139 return "^[a-zA-Z0-9 _.-]+$";
1140 }
1141 }
1144 function print_red()
1145 {
1146 trigger_error("Use of obsolete print_red");
1147 /* Check number of arguments */
1148 if (func_num_args() < 1){
1149 return;
1150 }
1152 /* Get arguments, save string */
1153 $array = func_get_args();
1154 $string= $array[0];
1156 /* Step through arguments */
1157 for ($i= 1; $i<count($array); $i++){
1158 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1159 }
1161 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1162 the other case... */
1163 if($string !== NULL){
1164 if (preg_match("/"._("LDAP error:")."/", $string)){
1165 $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.");
1166 } else {
1167 if (!preg_match('/[.!?]$/', $string)){
1168 $string.= ".";
1169 }
1170 $string= preg_replace('/<br>/', ' ', $string);
1171 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1172 $addmsg = "";
1173 }
1174 if(empty($addmsg)){
1175 $addmsg = _("Error");
1176 }
1177 msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1178 return;
1179 }else{
1180 return;
1181 }
1183 }
1186 function gen_locked_message($user, $dn)
1187 {
1188 global $plug, $config;
1190 session::set('dn', $dn);
1191 $remove= false;
1193 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1194 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1196 $LOCK_VARS_USED = array();
1197 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1199 foreach($LOCK_VARS_TO_USE as $name){
1201 if(empty($name)){
1202 continue;
1203 }
1205 foreach($_POST as $Pname => $Pvalue){
1206 if(preg_match($name,$Pname)){
1207 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1208 }
1209 }
1211 foreach($_GET as $Pname => $Pvalue){
1212 if(preg_match($name,$Pname)){
1213 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1214 }
1215 }
1216 }
1217 session::set('LOCK_VARS_TO_USE',array());
1218 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1219 }
1221 /* Prepare and show template */
1222 $smarty= get_smarty();
1224 if(is_array($dn)){
1225 $msg = "<pre>";
1226 foreach($dn as $sub_dn){
1227 $msg .= "\n".$sub_dn.", ";
1228 }
1229 $msg = preg_replace("/, $/","</pre>",$msg);
1230 }else{
1231 $msg = $dn;
1232 }
1234 $smarty->assign ("dn", $msg);
1235 if ($remove){
1236 $smarty->assign ("action", _("Continue anyway"));
1237 } else {
1238 $smarty->assign ("action", _("Edit anyway"));
1239 }
1240 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1242 return ($smarty->fetch (get_template_path('islocked.tpl')));
1243 }
1246 function to_string ($value)
1247 {
1248 /* If this is an array, generate a text blob */
1249 if (is_array($value)){
1250 $ret= "";
1251 foreach ($value as $line){
1252 $ret.= $line."<br>\n";
1253 }
1254 return ($ret);
1255 } else {
1256 return ($value);
1257 }
1258 }
1261 function get_printer_list()
1262 {
1263 global $config;
1264 $res = array();
1265 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1266 foreach($data as $attrs ){
1267 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1268 }
1269 return $res;
1270 }
1273 function show_errors($message)
1274 {
1275 $complete= "";
1277 /* Assemble the message array to a plain string */
1278 foreach ($message as $error){
1279 if ($complete == ""){
1280 $complete= $error;
1281 } else {
1282 $complete= "$error<br>$complete";
1283 }
1284 }
1286 /* Fill ERROR variable with nice error dialog */
1287 msg_dialog::display(_("Error"), $complete, ERROR_DIALOG);
1288 }
1291 function show_ldap_error($message, $addon= "")
1292 {
1293 if (!preg_match("/Success/i", $message)){
1294 if ($addon == ""){
1295 msg_dialog::display(_("LDAP error:"), $message, ERROR_DIALOG);
1296 } else {
1297 if(!preg_match("/No such object/i",$message)){
1298 msg_dialog::display(_("LDAP error"), sprintf(_("Plugin '%s':%s"),"<i>".$addon."</i>", "<br><br>$message"),ERROR_DIALOG);
1299 }
1300 }
1301 return TRUE;
1302 } else {
1303 return FALSE;
1304 }
1305 }
1308 function rewrite($s)
1309 {
1310 global $REWRITE;
1312 foreach ($REWRITE as $key => $val){
1313 $s= preg_replace("/$key/", "$val", $s);
1314 }
1316 return ($s);
1317 }
1320 function dn2base($dn)
1321 {
1322 global $config;
1324 if (get_people_ou() != ""){
1325 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1326 }
1327 if (get_groups_ou() != ""){
1328 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1329 }
1330 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1332 return ($base);
1333 }
1337 function check_command($cmdline)
1338 {
1339 $cmd= preg_replace("/ .*$/", "", $cmdline);
1341 /* Check if command exists in filesystem */
1342 if (!file_exists($cmd)){
1343 return (FALSE);
1344 }
1346 /* Check if command is executable */
1347 if (!is_executable($cmd)){
1348 return (FALSE);
1349 }
1351 return (TRUE);
1352 }
1355 function print_header($image, $headline, $info= "")
1356 {
1357 $display= "<div class=\"plugtop\">\n";
1358 $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";
1359 $display.= "</div>\n";
1361 if ($info != ""){
1362 $display.= "<div class=\"pluginfo\">\n";
1363 $display.= "$info";
1364 $display.= "</div>\n";
1365 } else {
1366 $display.= "<div style=\"height:5px;\">\n";
1367 $display.= " ";
1368 $display.= "</div>\n";
1369 }
1370 return ($display);
1371 }
1374 function range_selector($dcnt,$start,$range=25,$post_var=false)
1375 {
1377 /* Entries shown left and right from the selected entry */
1378 $max_entries= 10;
1380 /* Initialize and take care that max_entries is even */
1381 $output="";
1382 if ($max_entries & 1){
1383 $max_entries++;
1384 }
1386 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1387 $range= $_POST[$post_var];
1388 }
1390 /* Prevent output to start or end out of range */
1391 if ($start < 0 ){
1392 $start= 0 ;
1393 }
1394 if ($start >= $dcnt){
1395 $start= $range * (int)(($dcnt / $range) + 0.5);
1396 }
1398 $numpages= (($dcnt / $range));
1399 if(((int)($numpages))!=($numpages)){
1400 $numpages = (int)$numpages + 1;
1401 }
1402 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1403 return ("");
1404 }
1405 $ppage= (int)(($start / $range) + 0.5);
1408 /* Align selected page to +/- max_entries/2 */
1409 $begin= $ppage - $max_entries/2;
1410 $end= $ppage + $max_entries/2;
1412 /* Adjust begin/end, so that the selected value is somewhere in
1413 the middle and the size is max_entries if possible */
1414 if ($begin < 0){
1415 $end-= $begin + 1;
1416 $begin= 0;
1417 }
1418 if ($end > $numpages) {
1419 $end= $numpages;
1420 }
1421 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1422 $begin= $end - $max_entries;
1423 }
1425 if($post_var){
1426 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1427 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1428 }else{
1429 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1430 }
1432 /* Draw decrement */
1433 if ($start > 0 ) {
1434 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1435 (($start-$range))."\">".
1436 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1437 }
1439 /* Draw pages */
1440 for ($i= $begin; $i < $end; $i++) {
1441 if ($ppage == $i){
1442 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1443 validate($_GET['plug'])."&start=".
1444 ($i*$range)."\"> ".($i+1)." </a>";
1445 } else {
1446 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1447 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1448 }
1449 }
1451 /* Draw increment */
1452 if($start < ($dcnt-$range)) {
1453 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1454 (($start+($range)))."\">".
1455 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1456 }
1458 if(($post_var)&&($numpages)){
1459 $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()'>";
1460 foreach(array(20,50,100,200,"all") as $num){
1461 if($num == "all"){
1462 $var = 10000;
1463 }else{
1464 $var = $num;
1465 }
1466 if($var == $range){
1467 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1468 }else{
1469 $output.="\n<option value='".$var."'>".$num."</option>";
1470 }
1471 }
1472 $output.= "</select></td></tr></table></div>";
1473 }else{
1474 $output.= "</div>";
1475 }
1477 return($output);
1478 }
1481 function apply_filter()
1482 {
1483 $apply= "";
1485 $apply= ''.
1486 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1487 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1489 return ($apply);
1490 }
1493 function back_to_main()
1494 {
1495 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1496 _("Back").'"></p><input type="hidden" name="ignore">';
1498 return ($string);
1499 }
1502 function normalize_netmask($netmask)
1503 {
1504 /* Check for notation of netmask */
1505 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1506 $num= (int)($netmask);
1507 $netmask= "";
1509 for ($byte= 0; $byte<4; $byte++){
1510 $result=0;
1512 for ($i= 7; $i>=0; $i--){
1513 if ($num-- > 0){
1514 $result+= pow(2,$i);
1515 }
1516 }
1518 $netmask.= $result.".";
1519 }
1521 return (preg_replace('/\.$/', '', $netmask));
1522 }
1524 return ($netmask);
1525 }
1528 function netmask_to_bits($netmask)
1529 {
1530 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1531 $res= 0;
1533 for ($n= 0; $n<4; $n++){
1534 $start= 255;
1535 $name= "nm$n";
1537 for ($i= 0; $i<8; $i++){
1538 if ($start == (int)($$name)){
1539 $res+= 8 - $i;
1540 break;
1541 }
1542 $start-= pow(2,$i);
1543 }
1544 }
1546 return ($res);
1547 }
1550 function recurse($rule, $variables)
1551 {
1552 $result= array();
1554 if (!count($variables)){
1555 return array($rule);
1556 }
1558 reset($variables);
1559 $key= key($variables);
1560 $val= current($variables);
1561 unset ($variables[$key]);
1563 foreach($val as $possibility){
1564 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1565 $result= array_merge($result, recurse($nrule, $variables));
1566 }
1568 return ($result);
1569 }
1572 function expand_id($rule, $attributes)
1573 {
1574 /* Check for id rule */
1575 if(preg_match('/^id(:|#)\d+$/',$rule)){
1576 return (array("\{$rule}"));
1577 }
1579 /* Check for clean attribute */
1580 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1581 $rule= preg_replace('/^%/', '', $rule);
1582 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1583 return (array($val));
1584 }
1586 /* Check for attribute with parameters */
1587 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1588 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1589 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1590 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1591 $start= preg_replace ('/-.*$/', '', $param);
1592 $stop = preg_replace ('/^[^-]+-/', '', $param);
1594 /* Assemble results */
1595 $result= array();
1596 for ($i= $start; $i<= $stop; $i++){
1597 $result[]= substr($val, 0, $i);
1598 }
1599 return ($result);
1600 }
1602 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1603 return (array($rule));
1604 }
1607 function gen_uids($rule, $attributes)
1608 {
1609 global $config;
1611 /* Search for keys and fill the variables array with all
1612 possible values for that key. */
1613 $part= "";
1614 $trigger= false;
1615 $stripped= "";
1616 $variables= array();
1618 for ($pos= 0; $pos < strlen($rule); $pos++){
1620 if ($rule[$pos] == "{" ){
1621 $trigger= true;
1622 $part= "";
1623 continue;
1624 }
1626 if ($rule[$pos] == "}" ){
1627 $variables[$pos]= expand_id($part, $attributes);
1628 $stripped.= "{".$pos."}";
1629 $trigger= false;
1630 continue;
1631 }
1633 if ($trigger){
1634 $part.= $rule[$pos];
1635 } else {
1636 $stripped.= $rule[$pos];
1637 }
1638 }
1640 /* Recurse through all possible combinations */
1641 $proposed= recurse($stripped, $variables);
1643 /* Get list of used ID's */
1644 $used= array();
1645 $ldap= $config->get_ldap_link();
1646 $ldap->cd($config->current['BASE']);
1647 $ldap->search('(uid=*)');
1649 while($attrs= $ldap->fetch()){
1650 $used[]= $attrs['uid'][0];
1651 }
1653 /* Remove used uids and watch out for id tags */
1654 $ret= array();
1655 foreach($proposed as $uid){
1657 /* Check for id tag and modify uid if needed */
1658 if(preg_match('/\{id:\d+}/',$uid)){
1659 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1661 for ($i= 0; $i < pow(10,$size); $i++){
1662 $number= sprintf("%0".$size."d", $i);
1663 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1664 if (!in_array($res, $used)){
1665 $uid= $res;
1666 break;
1667 }
1668 }
1669 }
1671 if(preg_match('/\{id#\d+}/',$uid)){
1672 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1674 while (true){
1675 mt_srand((double) microtime()*1000000);
1676 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1677 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1678 if (!in_array($res, $used)){
1679 $uid= $res;
1680 break;
1681 }
1682 }
1683 }
1685 /* Don't assign used ones */
1686 if (!in_array($uid, $used)){
1687 $ret[]= $uid;
1688 }
1689 }
1691 return(array_unique($ret));
1692 }
1695 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1696 Need to convert... */
1697 function to_byte($value) {
1698 $value= strtolower(trim($value));
1700 if(!is_numeric(substr($value, -1))) {
1702 switch(substr($value, -1)) {
1703 case 'g':
1704 $mult= 1073741824;
1705 break;
1706 case 'm':
1707 $mult= 1048576;
1708 break;
1709 case 'k':
1710 $mult= 1024;
1711 break;
1712 }
1714 return ($mult * (int)substr($value, 0, -1));
1715 } else {
1716 return $value;
1717 }
1718 }
1721 function in_array_ics($value, $items)
1722 {
1723 if (!is_array($items)){
1724 return (FALSE);
1725 }
1727 foreach ($items as $item){
1728 if (strcasecmp($item, $value) == 0) {
1729 return (TRUE);
1730 }
1731 }
1733 return (FALSE);
1734 }
1737 function generate_alphabet($count= 10)
1738 {
1739 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1740 $alphabet= "";
1741 $c= 0;
1743 /* Fill cells with charaters */
1744 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1745 if ($c == 0){
1746 $alphabet.= "<tr>";
1747 }
1749 $ch = mb_substr($characters, $i, 1, "UTF8");
1750 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1751 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1753 if ($c++ == $count){
1754 $alphabet.= "</tr>";
1755 $c= 0;
1756 }
1757 }
1759 /* Fill remaining cells */
1760 while ($c++ <= $count){
1761 $alphabet.= "<td> </td>";
1762 }
1764 return ($alphabet);
1765 }
1768 function validate($string)
1769 {
1770 return (strip_tags(preg_replace('/\0/', '', $string)));
1771 }
1774 function get_gosa_version()
1775 {
1776 global $svn_revision, $svn_path;
1778 /* Extract informations */
1779 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1781 /* Release or development? */
1782 if (preg_match('%/gosa/trunk/%', $svn_path)){
1783 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1784 } else {
1785 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1786 return (sprintf(_("GOsa $release"), $revision));
1787 }
1788 }
1791 function rmdirRecursive($path, $followLinks=false) {
1792 $dir= opendir($path);
1793 while($entry= readdir($dir)) {
1794 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1795 unlink($path."/".$entry);
1796 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1797 rmdirRecursive($path."/".$entry);
1798 }
1799 }
1800 closedir($dir);
1801 return rmdir($path);
1802 }
1805 function scan_directory($path,$sort_desc=false)
1806 {
1807 $ret = false;
1809 /* is this a dir ? */
1810 if(is_dir($path)) {
1812 /* is this path a readable one */
1813 if(is_readable($path)){
1815 /* Get contents and write it into an array */
1816 $ret = array();
1818 $dir = opendir($path);
1820 /* Is this a correct result ?*/
1821 if($dir){
1822 while($fp = readdir($dir))
1823 $ret[]= $fp;
1824 }
1825 }
1826 }
1827 /* Sort array ascending , like scandir */
1828 sort($ret);
1830 /* Sort descending if parameter is sort_desc is set */
1831 if($sort_desc) {
1832 $ret = array_reverse($ret);
1833 }
1835 return($ret);
1836 }
1839 function clean_smarty_compile_dir($directory)
1840 {
1841 global $svn_revision;
1843 if(is_dir($directory) && is_readable($directory)) {
1844 // Set revision filename to REVISION
1845 $revision_file= $directory."/REVISION";
1847 /* Is there a stamp containing the current revision? */
1848 if(!file_exists($revision_file)) {
1849 // create revision file
1850 create_revision($revision_file, $svn_revision);
1851 } else {
1852 # check for "$config->...['CONFIG']/revision" and the
1853 # contents should match the revision number
1854 if(!compare_revision($revision_file, $svn_revision)){
1855 // If revision differs, clean compile directory
1856 foreach(scan_directory($directory) as $file) {
1857 if(($file==".")||($file=="..")) continue;
1858 if( is_file($directory."/".$file) &&
1859 is_writable($directory."/".$file)) {
1860 // delete file
1861 if(!unlink($directory."/".$file)) {
1862 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1863 // This should never be reached
1864 }
1865 } elseif(is_dir($directory."/".$file) &&
1866 is_writable($directory."/".$file)) {
1867 // Just recursively delete it
1868 rmdirRecursive($directory."/".$file);
1869 }
1870 }
1871 // We should now create a fresh revision file
1872 clean_smarty_compile_dir($directory);
1873 } else {
1874 // Revision matches, nothing to do
1875 }
1876 }
1877 } else {
1878 // Smarty compile dir is not accessible
1879 // (Smarty will warn about this)
1880 }
1881 }
1884 function create_revision($revision_file, $revision)
1885 {
1886 $result= false;
1888 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1889 if($fh= fopen($revision_file, "w")) {
1890 if(fwrite($fh, $revision)) {
1891 $result= true;
1892 }
1893 }
1894 fclose($fh);
1895 } else {
1896 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1897 }
1899 return $result;
1900 }
1903 function compare_revision($revision_file, $revision)
1904 {
1905 // false means revision differs
1906 $result= false;
1908 if(file_exists($revision_file) && is_readable($revision_file)) {
1909 // Open file
1910 if($fh= fopen($revision_file, "r")) {
1911 // Compare File contents with current revision
1912 if($revision == fread($fh, filesize($revision_file))) {
1913 $result= true;
1914 }
1915 } else {
1916 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1917 }
1918 // Close file
1919 fclose($fh);
1920 }
1922 return $result;
1923 }
1926 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1927 {
1928 $str = ""; // Our return value will be saved in this var
1930 $color = dechex($percentage+150);
1931 $color2 = dechex(150 - $percentage);
1932 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1934 $progress = (int)(($percentage /100)*$width);
1936 /* Abort printing out percentage, if divs are to small */
1939 /* If theres a better solution for this, use it... */
1940 $str = "
1941 <div style=\" width:".($width)."px;
1942 height:".($height)."px;
1943 background-color:#000000;
1944 padding:1px;\">
1946 <div style=\" width:".($width)."px;
1947 background-color:#$bgcolor;
1948 height:".($height)."px;\">
1950 <div style=\" width:".$progress."px;
1951 height:".$height."px;
1952 background-color:#".$color2.$color2.$color."; \">";
1955 if(($height >10)&&($showvalue)){
1956 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1957 <b>".$percentage."%</b>
1958 </font>";
1959 }
1961 $str.= "</div></div></div>";
1963 return($str);
1964 }
1967 function array_key_ics($ikey, $items)
1968 {
1969 /* Gather keys, make them lowercase */
1970 $tmp= array();
1971 foreach ($items as $key => $value){
1972 $tmp[strtolower($key)]= $key;
1973 }
1975 if (isset($tmp[strtolower($ikey)])){
1976 return($tmp[strtolower($ikey)]);
1977 }
1979 return ("");
1980 }
1983 function array_differs($src, $dst)
1984 {
1985 /* If the count is differing, the arrays differ */
1986 if (count ($src) != count ($dst)){
1987 return (TRUE);
1988 }
1990 /* So the count is the same - lets check the contents */
1991 $differs= FALSE;
1992 foreach($src as $value){
1993 if (!in_array($value, $dst)){
1994 $differs= TRUE;
1995 }
1996 }
1998 return ($differs);
1999 }
2002 function saveFilter($a_filter, $values)
2003 {
2004 if (isset($_POST['regexit'])){
2005 $a_filter["regex"]= $_POST['regexit'];
2007 foreach($values as $type){
2008 if (isset($_POST[$type])) {
2009 $a_filter[$type]= "checked";
2010 } else {
2011 $a_filter[$type]= "";
2012 }
2013 }
2014 }
2016 /* React on alphabet links if needed */
2017 if (isset($_GET['search'])){
2018 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2019 if ($s == "**"){
2020 $s= "*";
2021 }
2022 $a_filter['regex']= $s;
2023 }
2025 return ($a_filter);
2026 }
2029 /* Escape all preg_* relevant characters */
2030 function normalizePreg($input)
2031 {
2032 return (addcslashes($input, '[]()|/.*+-'));
2033 }
2036 /* Escape all LDAP filter relevant characters */
2037 function normalizeLdap($input)
2038 {
2039 return (addcslashes($input, '()|'));
2040 }
2043 /* Resturns the difference between to microtime() results in float */
2044 function get_MicroTimeDiff($start , $stop)
2045 {
2046 $a = split("\ ",$start);
2047 $b = split("\ ",$stop);
2049 $secs = $b[1] - $a[1];
2050 $msecs= $b[0] - $a[0];
2052 $ret = (float) ($secs+ $msecs);
2053 return($ret);
2054 }
2057 function get_base_dir()
2058 {
2059 global $BASE_DIR;
2061 return $BASE_DIR;
2062 }
2065 function obj_is_readable($dn, $object, $attribute)
2066 {
2067 global $ui;
2069 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2070 }
2073 function obj_is_writable($dn, $object, $attribute)
2074 {
2075 global $ui;
2077 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2078 }
2081 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2082 {
2083 /* Initialize variables */
2084 $ret = array("count" => 0); // Set count to 0
2085 $next = true; // if false, then skip next loops and return
2086 $cnt = 0; // Current number of loops
2087 $max = 100; // Just for security, prevent looops
2088 $ldap = NULL; // To check if created result a valid
2089 $keep = ""; // save last failed parse string
2091 /* Check each parsed dn in ldap ? */
2092 if($config!==NULL && $verify_in_ldap){
2093 $ldap = $config->get_ldap_link();
2094 }
2096 /* Lets start */
2097 $called = false;
2098 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2100 $cnt ++;
2101 if(!preg_match("/,/",$dn)){
2102 $next = false;
2103 }
2104 $object = preg_replace("/[,].*$/","",$dn);
2105 $dn = preg_replace("/^[^,]+,/","",$dn);
2107 $called = true;
2109 /* Check if current dn is valid */
2110 if($ldap!==NULL){
2111 $ldap->cd($dn);
2112 $ldap->cat($dn,array("dn"));
2113 if($ldap->count()){
2114 $ret[] = $keep.$object;
2115 $keep = "";
2116 }else{
2117 $keep .= $object.",";
2118 }
2119 }else{
2120 $ret[] = $keep.$object;
2121 $keep = "";
2122 }
2123 }
2125 /* No dn was posted */
2126 if($cnt == 0 && !empty($dn)){
2127 $ret[] = $dn;
2128 }
2130 /* Append the rest */
2131 $test = $keep.$dn;
2132 if($called && !empty($test)){
2133 $ret[] = $keep.$dn;
2134 }
2135 $ret['count'] = count($ret) - 1;
2137 return($ret);
2138 }
2141 function get_base_from_hook($dn, $attrib)
2142 {
2143 global $config;
2145 if (isset($config->current['BASE_HOOK'])){
2147 /* Call hook script - if present */
2148 $command= $config->current['BASE_HOOK'];
2150 if ($command != ""){
2151 $command.= " '".LDAP::fix($dn)."' $attrib";
2152 if (check_command($command)){
2153 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2154 exec($command, $output);
2155 if (preg_match("/^[0-9]+$/", $output[0])){
2156 return ($output[0]);
2157 } else {
2158 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2159 return ($config->current['UIDBASE']);
2160 }
2161 } else {
2162 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2163 return ($config->current['UIDBASE']);
2164 }
2166 } else {
2168 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2169 return ($config->current['UIDBASE']);
2171 }
2172 }
2173 }
2176 function check_schema_version($class, $version)
2177 {
2178 return preg_match("/\(v$version\)/", $class['DESC']);
2179 }
2182 function check_schema($cfg,$rfc2307bis = FALSE)
2183 {
2184 $messages= array();
2186 /* Get objectclasses */
2187 $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2188 $objectclasses = $ldap->get_objectclasses();
2189 if(count($objectclasses) == 0){
2190 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2191 }
2193 /* This is the default block used for each entry.
2194 * to avoid unset indexes.
2195 */
2196 $def_check = array("REQUIRED_VERSION" => "0",
2197 "SCHEMA_FILES" => array(),
2198 "CLASSES_REQUIRED" => array(),
2199 "STATUS" => FALSE,
2200 "IS_MUST_HAVE" => FALSE,
2201 "MSG" => "",
2202 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2204 /* The gosa base schema */
2205 $checks['gosaObject'] = $def_check;
2206 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2207 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2208 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2209 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2211 /* GOsa Account class */
2212 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2213 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2214 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2215 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2216 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2218 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2219 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2220 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2221 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2222 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2223 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2225 /* Some other checks */
2226 foreach(array(
2227 "gosaCacheEntry" => array("version" => "2.4"),
2228 "gosaDepartment" => array("version" => "2.4"),
2229 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2230 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2231 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2232 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2233 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2234 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2235 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2236 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2237 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2238 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2239 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2240 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2241 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2242 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2243 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2244 "goLdapServer" => array("version" => "2.4"),
2245 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2246 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2247 "goKrbServer" => array("version" => "2.4"),
2248 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2249 ) as $name => $values){
2251 $checks[$name] = $def_check;
2252 if(isset($values['version'])){
2253 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2254 }
2255 if(isset($values['file'])){
2256 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2257 }
2258 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2259 }
2260 foreach($checks as $name => $value){
2261 foreach($value['CLASSES_REQUIRED'] as $class){
2263 if(!isset($objectclasses[$name])){
2264 $checks[$name]['STATUS'] = FALSE;
2265 if($value['IS_MUST_HAVE']){
2266 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2267 }else{
2268 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2269 }
2270 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2271 $checks[$name]['STATUS'] = FALSE;
2273 if($value['IS_MUST_HAVE']){
2274 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2275 }else{
2276 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2277 }
2278 }else{
2279 $checks[$name]['STATUS'] = TRUE;
2280 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2281 }
2282 }
2283 }
2285 $tmp = $objectclasses;
2287 /* The gosa base schema */
2288 $checks['posixGroup'] = $def_check;
2289 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2290 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2291 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2292 $checks['posixGroup']['STATUS'] = TRUE;
2293 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2294 $checks['posixGroup']['MSG'] = "";
2295 $checks['posixGroup']['INFO'] = "";
2297 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2298 if(isset($tmp['posixGroup'])){
2300 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2301 $checks['posixGroup']['STATUS'] = FALSE;
2302 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2303 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2304 }
2305 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2306 $checks['posixGroup']['STATUS'] = FALSE;
2307 $checks['posixGroup']['MSG'] = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2308 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2309 }
2310 }
2312 return($checks);
2313 }
2316 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2317 {
2318 $tmp = array(
2319 "de_DE" => "German",
2320 "fr_FR" => "French",
2321 "it_IT" => "Italian",
2322 "es_ES" => "Spanish",
2323 "en_US" => "English",
2324 "nl_NL" => "Dutch",
2325 "pl_PL" => "Polish",
2326 "sv_SE" => "Swedish",
2327 "zh_CN" => "Chinese",
2328 "ru_RU" => "Russian");
2330 $tmp2= array(
2331 "de_DE" => _("German"),
2332 "fr_FR" => _("French"),
2333 "it_IT" => _("Italian"),
2334 "es_ES" => _("Spanish"),
2335 "en_US" => _("English"),
2336 "nl_NL" => _("Dutch"),
2337 "pl_PL" => _("Polish"),
2338 "sv_SE" => _("Swedish"),
2339 "zh_CN" => _("Chinese"),
2340 "ru_RU" => _("Russian"));
2342 $ret = array();
2343 if($languages_in_own_language){
2345 $old_lang = setlocale(LC_ALL, 0);
2346 foreach($tmp as $key => $name){
2347 $lang = $key.".UTF-8";
2348 setlocale(LC_ALL, $lang);
2349 if($strip_region_tag){
2350 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2351 }else{
2352 $ret[$key] = _($name)." (".$tmp2[$key].")";
2353 }
2354 }
2355 setlocale(LC_ALL, $old_lang);
2356 }else{
2357 foreach($tmp as $key => $name){
2358 if($strip_region_tag){
2359 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2360 }else{
2361 $ret[$key] = _($name);
2362 }
2363 }
2364 }
2365 return($ret);
2366 }
2369 /* Returns contents of the given POST variable and check magic quotes settings */
2370 function get_post($name)
2371 {
2372 if(!isset($_POST[$name])){
2373 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2374 return(FALSE);
2375 }
2376 if(get_magic_quotes_gpc()){
2377 return(stripcslashes($_POST[$name]));
2378 }else{
2379 return($_POST[$name]);
2380 }
2381 }
2384 /* Return class name in correct case */
2385 function get_correct_class_name($cls)
2386 {
2387 global $class_mapping;
2388 if(isset($class_mapping) && is_array($class_mapping)){
2389 foreach($class_mapping as $class => $file){
2390 if(preg_match("/^".$cls."$/i",$class)){
2391 return($class);
2392 }
2393 }
2394 }
2395 return(FALSE);
2396 }
2399 // change_password, changes the Password, of the given dn
2400 function change_password ($dn, $password, $mode=0, $hash= "")
2401 {
2402 global $config;
2403 $newpass= "";
2405 /* Convert to lower. Methods are lowercase */
2406 $hash= strtolower($hash);
2408 // Get all available encryption Methods
2410 // NON STATIC CALL :)
2411 $tmp = new passwordMethod(session::get('config'));
2412 $available = $tmp->get_available_methods();
2414 // read current password entry for $dn, to detect the encryption Method
2415 $ldap = $config->get_ldap_link();
2416 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2417 $attrs = $ldap->fetch ();
2419 // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2420 if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2421 $deactivated = TRUE;
2422 }else{
2423 $deactivated = FALSE;
2424 }
2426 /* Is ensure that clear passwords will stay clear */
2427 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2428 $hash = "clear";
2429 }
2431 // Detect the encryption Method
2432 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2434 /* Check for supported algorithm */
2435 mt_srand((double) microtime()*1000000);
2437 /* Extract used hash */
2438 if ($hash == ""){
2439 $hash= strtolower($matches[1]);
2440 }
2442 $test = new $available[$hash]($config);
2444 } else {
2445 // User MD5 by default
2446 $hash= "md5";
2447 $test = new $available['md5']($config);
2448 }
2450 /* Feed password backends with information */
2451 $test->dn= $dn;
2452 $test->attrs= $attrs;
2453 $newpass= $test->generate_hash($password);
2455 // Update shadow timestamp?
2456 if (isset($attrs["shadowLastChange"][0])){
2457 $shadow= (int)(date("U") / 86400);
2458 } else {
2459 $shadow= 0;
2460 }
2462 // Write back modified entry
2463 $ldap->cd($dn);
2464 $attrs= array();
2466 // Not for groups
2467 if ($mode == 0){
2469 if ($shadow != 0){
2470 $attrs['shadowLastChange']= $shadow;
2471 }
2473 // Create SMB Password
2474 $attrs= generate_smb_nt_hash($password);
2475 }
2477 /* Readd ! if user was deactivated */
2478 if($deactivated){
2479 $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2480 }
2482 $attrs['userPassword']= array();
2483 $attrs['userPassword']= $newpass;
2485 $ldap->modify($attrs);
2487 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2489 if ($ldap->error != 'Success') {
2490 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);
2491 } else {
2493 /* Run backend method for change/create */
2494 $test->set_password($password);
2496 /* Find postmodify entries for this class */
2497 $command= $config->search("password", "POSTMODIFY",array('menu'));
2499 if ($command != ""){
2500 /* Walk through attribute list */
2501 $command= preg_replace("/%userPassword/", $password, $command);
2502 $command= preg_replace("/%dn/", $dn, $command);
2504 if (check_command($command)){
2505 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2506 exec($command);
2507 } else {
2508 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2509 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2510 }
2511 }
2512 }
2513 }
2516 // Return something like array['sambaLMPassword']= "lalla..."
2517 function generate_smb_nt_hash($password)
2518 {
2519 global $config;
2520 $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2521 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2523 exec($tmp, $ar);
2524 flush();
2525 reset($ar);
2526 $hash= current($ar);
2527 if ($hash == "") {
2528 msg_dialog::display(_("Configuration error"), _("Setting for SMBHASH in gosa.conf is incorrect! Cannot change Samba password."), ERROR_DIALOG);
2529 } else {
2530 list($lm,$nt)= split (":", trim($hash));
2532 if ($config->current['SAMBAVERSION'] == 3) {
2533 $attrs['sambaLMPassword']= $lm;
2534 $attrs['sambaNTPassword']= $nt;
2535 $attrs['sambaPwdLastSet']= date('U');
2536 $attrs['sambaBadPasswordCount']= "0";
2537 $attrs['sambaBadPasswordTime']= "0";
2538 } else {
2539 $attrs['lmPassword']= $lm;
2540 $attrs['ntPassword']= $nt;
2541 $attrs['pwdLastSet']= date('U');
2542 }
2543 return($attrs);
2544 }
2545 }
2548 function crypt_single($string,$enc_type )
2549 {
2550 return( passwordMethod::crypt_single_str($string,$enc_type));
2551 }
2554 function getEntryCSN($dn)
2555 {
2556 global $config;
2557 if(empty($dn) || !is_object($config)){
2558 return("");
2559 }
2561 /* Get attribute that we should use as serial number */
2562 if(isset($config->current['UNIQ_IDENTIFIER'])){
2563 $attr = $config->current['UNIQ_IDENTIFIER'];
2564 }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2565 $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2566 }
2567 if(!empty($attr)){
2568 $ldap = $config->get_ldap_link();
2569 $ldap->cat($dn,array($attr));
2570 $csn = $ldap->fetch();
2571 if(isset($csn[$attr][0])){
2572 return($csn[$attr][0]);
2573 }
2574 }
2575 return("");
2576 }
2579 /* Add a given objectClass to an attrs entry */
2580 function add_objectClass($classes, &$attrs)
2581 {
2582 if (is_array($classes)){
2583 $list= $classes;
2584 } else {
2585 $list= array($classes);
2586 }
2588 foreach ($list as $class){
2589 $attrs['objectClass'][]= $class;
2590 }
2591 }
2594 /* Removes a given objectClass from the attrs entry */
2595 function remove_objectClass($classes, &$attrs)
2596 {
2597 if (isset($attrs['objectClass'])){
2598 /* Array? */
2599 if (is_array($classes)){
2600 $list= $classes;
2601 } else {
2602 $list= array($classes);
2603 }
2605 $tmp= array();
2606 foreach ($attrs['objectClass'] as $oc) {
2607 foreach ($list as $class){
2608 if ($oc != $class){
2609 $tmp[]= $oc;
2610 }
2611 }
2612 }
2613 $attrs['objectClass']= $tmp;
2614 }
2615 }
2617 /*! \brief Initialize a file download with given content, name and data type.
2618 * @param data String The content to send.
2619 * @param name String The name of the file.
2620 * @param type String The content identifier, default value is "application/octet-stream";
2621 */
2622 function send_binary_content($data,$name,$type = "application/octet-stream")
2623 {
2624 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2625 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2626 header("Cache-Control: no-cache");
2627 header("Pragma: no-cache");
2628 header("Cache-Control: post-check=0, pre-check=0");
2629 header("Content-type: ".$type."");
2630 header("Content-Disposition: attachment; filename=".$name);
2631 echo $data;
2632 exit();
2633 }
2636 function display_error_page()
2637 {
2638 $smarty= get_smarty();
2639 $smarty->display(get_template_path('headers.tpl'));
2640 echo "<body>".msg_dialog::get_dialogs()."</body></html>";
2641 exit();
2642 }
2644 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2645 ?>