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);
32 define("GL_NO_ACL_CHECK", 8);
34 /* Heimdal stuff */
35 define('UNIVERSAL',0x00);
36 define('INTEGER',0x02);
37 define('OCTET_STRING',0x04);
38 define('OBJECT_IDENTIFIER ',0x06);
39 define('SEQUENCE',0x10);
40 define('SEQUENCE_OF',0x10);
41 define('SET',0x11);
42 define('SET_OF',0x11);
43 define('DEBUG',false);
44 define('HDB_KU_MKEY',0x484442);
45 define('TWO_BIT_SHIFTS',0x7efc);
46 define('DES_CBC_CRC',1);
47 define('DES_CBC_MD4',2);
48 define('DES_CBC_MD5',3);
49 define('DES3_CBC_MD5',5);
50 define('DES3_CBC_SHA1',16);
52 /* Define globals for revision comparing */
53 $svn_path = '$HeadURL$';
54 $svn_revision = '$Revision$';
56 /* Include required files */
57 require_once("class_location.inc");
58 require_once ("functions_debug.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;
98 if ($class_mapping === NULL){
99 echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
100 exit;
101 }
103 if (isset($class_mapping[$class_name])){
104 require_once($BASE_DIR."/".$class_mapping[$class_name]);
105 } else {
106 echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
107 exit;
108 }
109 }
112 /*! \brief Checks if a class is available.
113 * @param name String The class name.
114 * @return boolean True if class is available, else false.
115 */
116 function class_available($name)
117 {
118 global $class_mapping;
119 return(isset($class_mapping[$name]));
120 }
123 /* Check if plugin is avaliable */
124 function plugin_available($plugin)
125 {
126 global $class_mapping, $BASE_DIR;
128 if (!isset($class_mapping[$plugin])){
129 return false;
130 } else {
131 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
132 }
133 }
136 /* Create seed with microseconds */
137 function make_seed() {
138 list($usec, $sec) = explode(' ', microtime());
139 return (float) $sec + ((float) $usec * 100000);
140 }
143 /* Debug level action */
144 function DEBUG($level, $line, $function, $file, $data, $info="")
145 {
146 if (session::get('DEBUGLEVEL') & $level){
147 $output= "DEBUG[$level] ";
148 if ($function != ""){
149 $output.= "($file:$function():$line) - $info: ";
150 } else {
151 $output.= "($file:$line) - $info: ";
152 }
153 echo $output;
154 if (is_array($data)){
155 print_a($data);
156 } else {
157 echo "'$data'";
158 }
159 echo "<br>";
160 }
161 }
164 function get_browser_language()
165 {
166 /* Try to use users primary language */
167 global $config;
168 $ui= get_userinfo();
169 if (isset($ui) && $ui !== NULL){
170 if ($ui->language != ""){
171 return ($ui->language.".UTF-8");
172 }
173 }
175 /* Check for global language settings in gosa.conf */
176 if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
177 $lang = $config->data['MAIN']['LANG'];
178 if(!preg_match("/utf/i",$lang)){
179 $lang .= ".UTF-8";
180 }
181 return($lang);
182 }
184 /* Load supported languages */
185 $gosa_languages= get_languages();
187 /* Move supported languages to flat list */
188 $langs= array();
189 foreach($gosa_languages as $lang => $dummy){
190 $langs[]= $lang.'.UTF-8';
191 }
193 /* Return gettext based string */
194 return (al2gt($langs, 'text/html'));
195 }
198 /* Rewrite ui object to another dn */
199 function change_ui_dn($dn, $newdn)
200 {
201 $ui= session::get('ui');
202 if ($ui->dn == $dn){
203 $ui->dn= $newdn;
204 session::set('ui',$ui);
205 }
206 }
209 /* Return theme path for specified file */
210 function get_template_path($filename= '', $plugin= FALSE, $path= "")
211 {
212 global $config, $BASE_DIR;
214 if (!@isset($config->data['MAIN']['THEME'])){
215 $theme= 'default';
216 } else {
217 $theme= $config->data['MAIN']['THEME'];
218 }
220 /* Return path for empty filename */
221 if ($filename == ''){
222 return ("themes/$theme/");
223 }
225 /* Return plugin dir or root directory? */
226 if ($plugin){
227 if ($path == ""){
228 $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
229 } else {
230 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
231 }
232 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
233 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
234 }
235 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
236 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
237 }
238 if ($path == ""){
239 return (session::get('plugin_dir')."/$filename");
240 } else {
241 return ($path."/$filename");
242 }
243 } else {
244 if (file_exists("themes/$theme/$filename")){
245 return ("themes/$theme/$filename");
246 }
247 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
248 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
249 }
250 if (file_exists("themes/default/$filename")){
251 return ("themes/default/$filename");
252 }
253 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
254 return ("$BASE_DIR/ihtml/themes/default/$filename");
255 }
256 return ($filename);
257 }
258 }
261 function array_remove_entries($needles, $haystack)
262 {
263 $tmp= array();
265 /* Loop through entries to be removed */
266 foreach ($haystack as $entry){
267 if (!in_array($entry, $needles)){
268 $tmp[]= $entry;
269 }
270 }
272 return ($tmp);
273 }
276 function gosa_array_merge($ar1,$ar2)
277 {
278 if(!is_array($ar1) || !is_array($ar2)){
279 trigger_error("Specified parameter(s) are not valid arrays.");
280 }else{
281 return(array_values(array_unique(array_merge($ar1,$ar2))));
282 }
283 }
286 function gosa_log ($message)
287 {
288 global $ui;
290 /* Preset to something reasonable */
291 $username= " unauthenticated";
293 /* Replace username if object is present */
294 if (isset($ui)){
295 if ($ui->username != ""){
296 $username= "[$ui->username]";
297 } else {
298 $username= "unknown";
299 }
300 }
302 syslog(LOG_INFO,"GOsa$username: $message");
303 }
306 function ldap_init ($server, $base, $binddn='', $pass='')
307 {
308 global $config;
310 $ldap = new LDAP ($binddn, $pass, $server,
311 isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
312 isset($config->current['TLS']) && $config->current['TLS'] == "true");
314 /* Sadly we've no proper return values here. Use the error message instead. */
315 if (!preg_match("/Success/i", $ldap->error)){
316 echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
317 exit();
318 }
320 /* Preset connection base to $base and return to caller */
321 $ldap->cd ($base);
322 return $ldap;
323 }
326 function process_htaccess ($username, $kerberos= FALSE)
327 {
328 global $config;
330 /* Search for $username and optional @REALM in all configured LDAP trees */
331 foreach($config->data["LOCATIONS"] as $name => $data){
333 $config->set_current($name);
334 $mode= "kerberos";
335 if (isset($config->current['KRBSASL']) && preg_match('/^true$/i', $config->current['KRBSASL'])){
336 $mode= "sasl";
337 }
339 /* Look for entry or realm */
340 $ldap= $config->get_ldap_link();
341 if (!preg_match("/Success/i", $ldap->error)){
342 msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
343 $smarty= get_smarty();
344 $smarty->display(get_template_path('headers.tpl'));
345 echo "<body>".session::get('errors')."</body></html>";
346 exit();
347 }
348 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
350 /* Found a uniq match? Return it... */
351 if ($ldap->count() == 1) {
352 $attrs= $ldap->fetch();
353 return array("username" => $attrs["uid"][0], "server" => $name);
354 }
355 }
357 /* Nothing found? Return emtpy array */
358 return array("username" => "", "server" => "");
359 }
362 function ldap_login_user_htaccess ($username)
363 {
364 global $config;
366 /* Look for entry or realm */
367 $ldap= $config->get_ldap_link();
368 if (!preg_match("/Success/i", $ldap->error)){
369 msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), FATAL_ERROR_DIALOG);
370 $smarty= get_smarty();
371 $smarty->display(get_template_path('headers.tpl'));
372 echo "<body>".session::get('errors')."</body></html>";
373 exit();
374 }
375 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
376 /* Found no uniq match? Strange, because we did above... */
377 if ($ldap->count() != 1) {
378 msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
379 return (NULL);
380 }
381 $attrs= $ldap->fetch();
383 /* got user dn, fill acl's */
384 $ui= new userinfo($config, $ldap->getDN());
385 $ui->username= $attrs['uid'][0];
387 /* No password check needed - the webserver did it for us */
388 $ldap->disconnect();
390 /* Username is set, load subtreeACL's now */
391 $ui->loadACL();
393 /* TODO: check java script for htaccess authentication */
394 session::set('js',true);
396 return ($ui);
397 }
400 function ldap_login_user ($username, $password)
401 {
402 global $config;
404 /* look through the entire ldap */
405 $ldap = $config->get_ldap_link();
406 if (!preg_match("/Success/i", $ldap->error)){
407 msg_dialog::display(_("LDAP error"), sprintf(_("User login failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), FATAL_ERROR_DIALOG);
408 $smarty= get_smarty();
409 $smarty->display(get_template_path('headers.tpl'));
410 echo "<body>".session::get('errors')."</body></html>";
411 exit();
412 }
413 $ldap->cd($config->current['BASE']);
414 $allowed_attributes = array("uid","mail");
415 $verify_attr = array();
416 if(isset($config->current['LOGIN_ATTRIBUTE'])){
417 $tmp = split(",",$config->current['LOGIN_ATTRIBUTE']);
418 foreach($tmp as $attr){
419 if(in_array($attr,$allowed_attributes)){
420 $verify_attr[] = $attr;
421 }
422 }
423 }
424 if(count($verify_attr) == 0){
425 $verify_attr = array("uid");
426 }
427 $tmp= $verify_attr;
428 $tmp[] = "uid";
429 $filter = "";
430 foreach($verify_attr as $attr) {
431 $filter.= "(".$attr."=".$username.")";
432 }
433 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
434 $ldap->search($filter,$tmp);
436 /* get results, only a count of 1 is valid */
437 switch ($ldap->count()){
439 /* user not found */
440 case 0: return (NULL);
442 /* valid uniq user */
443 case 1:
444 break;
446 /* found more than one matching id */
447 default:
448 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
449 return (NULL);
450 }
452 /* LDAP schema is not case sensitive. Perform additional check. */
453 $attrs= $ldap->fetch();
454 $success = FALSE;
455 foreach($verify_attr as $attr){
456 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
457 $success = TRUE;
458 }
459 }
460 if(!$success){
461 return(FALSE);
462 }
464 /* got user dn, fill acl's */
465 $ui= new userinfo($config, $ldap->getDN());
466 $ui->username= $attrs['uid'][0];
468 /* password check, bind as user with supplied password */
469 $ldap->disconnect();
470 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
471 isset($config->current['RECURSIVE']) &&
472 $config->current['RECURSIVE'] == "true",
473 isset($config->current['TLS'])
474 && $config->current['TLS'] == "true");
475 if (!preg_match("/Success/i", $ldap->error)){
476 return (NULL);
477 }
479 /* Username is set, load subtreeACL's now */
480 $ui->loadACL();
482 return ($ui);
483 }
486 function ldap_expired_account($config, $userdn, $username)
487 {
488 $ldap= $config->get_ldap_link();
489 $ldap->cat($userdn);
490 $attrs= $ldap->fetch();
492 /* default value no errors */
493 $expired = 0;
495 $sExpire = 0;
496 $sLastChange = 0;
497 $sMax = 0;
498 $sMin = 0;
499 $sInactive = 0;
500 $sWarning = 0;
502 $current= date("U");
504 $current= floor($current /60 /60 /24);
506 /* special case of the admin, should never been locked */
507 /* FIXME should allow any name as user admin */
508 if($username != "admin")
509 {
511 if(isset($attrs['shadowExpire'][0])){
512 $sExpire= $attrs['shadowExpire'][0];
513 } else {
514 $sExpire = 0;
515 }
517 if(isset($attrs['shadowLastChange'][0])){
518 $sLastChange= $attrs['shadowLastChange'][0];
519 } else {
520 $sLastChange = 0;
521 }
523 if(isset($attrs['shadowMax'][0])){
524 $sMax= $attrs['shadowMax'][0];
525 } else {
526 $smax = 0;
527 }
529 if(isset($attrs['shadowMin'][0])){
530 $sMin= $attrs['shadowMin'][0];
531 } else {
532 $sMin = 0;
533 }
535 if(isset($attrs['shadowInactive'][0])){
536 $sInactive= $attrs['shadowInactive'][0];
537 } else {
538 $sInactive = 0;
539 }
541 if(isset($attrs['shadowWarning'][0])){
542 $sWarning= $attrs['shadowWarning'][0];
543 } else {
544 $sWarning = 0;
545 }
547 /* is the account locked */
548 /* shadowExpire + shadowInactive (option) */
549 if($sExpire >0){
550 if($current >= ($sExpire+$sInactive)){
551 return(1);
552 }
553 }
555 /* the user should be warned to change is password */
556 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
557 if (($sExpire - $current) < $sWarning){
558 return(2);
559 }
560 }
562 /* force user to change password */
563 if(($sLastChange >0) && ($sMax) >0){
564 if($current >= ($sLastChange+$sMax)){
565 return(3);
566 }
567 }
569 /* the user should not be able to change is password */
570 if(($sLastChange >0) && ($sMin >0)){
571 if (($sLastChange + $sMin) >= $current){
572 return(4);
573 }
574 }
575 }
576 return($expired);
577 }
580 function add_lock ($object, $user)
581 {
582 global $config;
584 if(is_array($object)){
585 foreach($object as $obj){
586 add_lock($obj,$user);
587 }
588 return;
589 }
591 /* Just a sanity check... */
592 if ($object == "" || $user == ""){
593 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
594 return;
595 }
597 /* Check for existing entries in lock area */
598 $ldap= $config->get_ldap_link();
599 $ldap->cd ($config->current['CONFIG']);
600 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
601 array("gosaUser"));
602 if (!preg_match("/Success/i", $ldap->error)){
603 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);
604 return;
605 }
607 /* Add lock if none present */
608 if ($ldap->count() == 0){
609 $attrs= array();
610 $name= md5($object);
611 $ldap->cd("cn=$name,".$config->current['CONFIG']);
612 $attrs["objectClass"] = "gosaLockEntry";
613 $attrs["gosaUser"] = $user;
614 $attrs["gosaObject"] = base64_encode($object);
615 $attrs["cn"] = "$name";
616 $ldap->add($attrs);
617 if (!preg_match("/Success/i", $ldap->error)){
618 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);
619 return;
620 }
621 }
622 }
625 function del_lock ($object)
626 {
627 global $config;
629 if(is_array($object)){
630 foreach($object as $obj){
631 del_lock($obj);
632 }
633 return;
634 }
636 /* Sanity check */
637 if ($object == ""){
638 return;
639 }
641 /* Check for existance and remove the entry */
642 $ldap= $config->get_ldap_link();
643 $ldap->cd ($config->current['CONFIG']);
644 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
645 $attrs= $ldap->fetch();
646 if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
647 $ldap->rmdir ($ldap->getDN());
649 if (!preg_match("/Success/i", $ldap->error)){
650 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);
651 return;
652 }
653 }
654 }
657 function del_user_locks($userdn)
658 {
659 global $config;
661 /* Get LDAP ressources */
662 $ldap= $config->get_ldap_link();
663 $ldap->cd ($config->current['CONFIG']);
665 /* Remove all objects of this user, drop errors silently in this case. */
666 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
667 while ($attrs= $ldap->fetch()){
668 $ldap->rmdir($attrs['dn']);
669 }
670 }
673 function get_lock ($object)
674 {
675 global $config;
677 /* Sanity check */
678 if ($object == ""){
679 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
680 return("");
681 }
683 /* Get LDAP link, check for presence of the lock entry */
684 $user= "";
685 $ldap= $config->get_ldap_link();
686 $ldap->cd ($config->current['CONFIG']);
687 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
688 if (!preg_match("/Success/i", $ldap->error)){
689 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);
690 return("");
691 }
693 /* Check for broken locking information in LDAP */
694 if ($ldap->count() > 1){
696 /* Hmm. We're removing broken LDAP information here and issue a warning. */
697 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
699 /* Clean up these references now... */
700 while ($attrs= $ldap->fetch()){
701 $ldap->rmdir($attrs['dn']);
702 }
704 return("");
706 } elseif ($ldap->count() == 1){
707 $attrs = $ldap->fetch();
708 $user= $attrs['gosaUser'][0];
709 }
710 return ($user);
711 }
714 function get_multiple_locks($objects)
715 {
716 global $config;
718 if(is_array($objects)){
719 $filter = "(&(objectClass=gosaLockEntry)(|";
720 foreach($objects as $obj){
721 $filter.="(gosaObject=".base64_encode($obj).")";
722 }
723 $filter.= "))";
724 }else{
725 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
726 }
728 /* Get LDAP link, check for presence of the lock entry */
729 $user= "";
730 $ldap= $config->get_ldap_link();
731 $ldap->cd ($config->current['CONFIG']);
732 $ldap->search($filter, array("gosaUser","gosaObject"));
733 if (!preg_match("/Success/i", $ldap->error)){
734 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);
735 return("");
736 }
738 $users = array();
739 while($attrs = $ldap->fetch()){
740 $dn = base64_decode($attrs['gosaObject'][0]);
741 $user = $attrs['gosaUser'][0];
742 $users[] = array("dn"=> $dn,"user"=>$user);
743 }
744 return ($users);
745 }
748 /* \!brief This function searches the ldap database.
749 It search in $sub_bases,*,$base for all objects matching the $filter.
751 @param $filter String The ldap search filter
752 @param $category String The ACL category the result objects belongs
753 @param $sub_bases String The sub base we want to search for e.g. "ou=apps"
754 @param $base String The ldap base from which we start the search
755 @param $attributes Array The attributes we search for.
756 @param $flags Long A set of Flags
757 */
758 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
759 {
760 global $config, $ui;
761 $departments = array();
763 # $start = microtime(TRUE);
765 /* Get LDAP link */
766 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
768 /* Set search base to configured base if $base is empty */
769 if ($base == ""){
770 $base = $config->current['BASE'];
771 }
772 $ldap->cd ($base);
774 /* Ensure we have an array as department list */
775 if(is_string($sub_deps)){
776 $sub_deps = array($sub_deps);
777 }
779 /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
780 $sub_bases = array();
781 foreach($sub_deps as $key => $sub_base){
782 if(empty($sub_base)){
784 /* Subsearch is activated and we got an empty sub_base.
785 * (This may be the case if you have empty people/group ous).
786 * Fall back to old get_list().
787 * A log entry will be written.
788 */
789 if($flags & GL_SUBSEARCH){
790 $sub_bases = array();
791 break;
792 }else{
794 /* Do NOT search within subtrees is requeste and the sub base is empty.
795 * Append all known departments that matches the base.
796 */
797 $departments[$base] = $base;
798 }
799 }else{
800 $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
801 }
802 }
804 /* If there is no sub_department specified, fall back to old method, get_list().
805 */
806 if(!count($sub_bases) && !count($departments)){
808 /* Log this fall back, it may be an unpredicted behaviour.
809 */
810 if(!count($sub_bases) && !count($departments)){
811 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
812 new log("debug","all",__FILE__,$attributes,
813 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
814 " This may slow down GOsa. Search was: '%s'",$filter));
815 }
816 $tmp = get_list($filter, $category,$base,$attributes,$flags);
817 return($tmp);
818 }
820 /* Get all deparments matching the given sub_bases */
821 $base_filter= "";
822 foreach($sub_bases as $sub_base){
823 $base_filter .= "(".$sub_base.")";
824 }
825 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
826 $ldap->search($base_filter,array("dn"));
827 while($attrs = $ldap->fetch()){
828 foreach($sub_deps as $sub_dep){
830 /* Only add those departments that match the reuested list of departments.
831 *
832 * e.g. sub_deps = array("ou=servers,ou=systems,");
833 *
834 * In this case we have search for "ou=servers" and we may have also fetched
835 * departments like this "ou=servers,ou=blafasel,..."
836 * Here we filter out those blafasel departments.
837 */
838 if(preg_match("/".normalizePreg($sub_dep)."/",$attrs['dn'])){
839 $departments[$attrs['dn']] = $attrs['dn'];
840 break;
841 }
842 }
843 }
845 $result= array();
846 $limit_exceeded = FALSE;
848 /* Search in all matching departments */
849 foreach($departments as $dep){
851 /* Break if the size limit is exceeded */
852 if($limit_exceeded){
853 return($result);
854 }
856 $ldap->cd($dep);
858 /* Perform ONE or SUB scope searches? */
859 if ($flags & GL_SUBSEARCH) {
860 $ldap->search ($filter, $attributes);
861 } else {
862 $ldap->ls ($filter,$dep,$attributes);
863 }
865 /* Check for size limit exceeded messages for GUI feedback */
866 if (preg_match("/size limit/i", $ldap->error)){
867 session::set('limit_exceeded', TRUE);
868 $limit_exceeded = TRUE;
869 }
871 /* Crawl through result entries and perform the migration to the
872 result array */
873 while($attrs = $ldap->fetch()) {
874 $dn= $ldap->getDN();
876 /* Convert dn into a printable format */
877 if ($flags & GL_CONVERT){
878 $attrs["dn"]= convert_department_dn($dn);
879 } else {
880 $attrs["dn"]= $dn;
881 }
883 /* Skip ACL checks if we are forced to skip those checks */
884 if($flags & GL_NO_ACL_CHECK){
885 $result[]= $attrs;
886 }else{
888 /* Sort in every value that fits the permissions */
889 if (is_array($category)){
890 foreach ($category as $o){
891 if ($ui->get_category_permissions($dn, $o) != ""){
892 $result[]= $attrs;
893 break;
894 }
895 }
896 } else {
897 if ( $ui->get_category_permissions($dn, $category) != ""){
898 $result[]= $attrs;
899 }
900 }
901 }
902 }
903 }
904 # if(microtime(TRUE) - $start > 0.1){
905 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
906 # }
907 return($result);
908 }
911 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
912 {
913 global $config, $ui;
915 # $start = microtime(TRUE);
917 /* Get LDAP link */
918 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
920 /* Set search base to configured base if $base is empty */
921 if ($base == ""){
922 $ldap->cd ($config->current['BASE']);
923 } else {
924 $ldap->cd ($base);
925 }
927 /* Perform ONE or SUB scope searches? */
928 if ($flags & GL_SUBSEARCH) {
929 $ldap->search ($filter, $attributes);
930 } else {
931 $ldap->ls ($filter,$base,$attributes);
932 }
934 /* Check for size limit exceeded messages for GUI feedback */
935 if (preg_match("/size limit/i", $ldap->error)){
936 session::set('limit_exceeded', TRUE);
937 }
939 /* Crawl through reslut entries and perform the migration to the
940 result array */
941 $result= array();
943 while($attrs = $ldap->fetch()) {
945 $dn= $ldap->getDN();
947 /* Convert dn into a printable format */
948 if ($flags & GL_CONVERT){
949 $attrs["dn"]= convert_department_dn($dn);
950 } else {
951 $attrs["dn"]= $dn;
952 }
954 if($flags & GL_NO_ACL_CHECK){
955 $result[]= $attrs;
956 }else{
958 /* Sort in every value that fits the permissions */
959 if (is_array($category)){
960 foreach ($category as $o){
961 if ($ui->get_category_permissions($dn, $o) != ""){
963 /* We found what we were looking for, break speeds things up */
964 $result[]= $attrs;
965 }
966 }
967 } else {
968 if ($ui->get_category_permissions($dn, $category) != ""){
970 /* We found what we were looking for, break speeds things up */
971 $result[]= $attrs;
972 }
973 }
974 }
975 }
977 # if(microtime(TRUE) - $start > 0.1){
978 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
979 # }
980 return ($result);
981 }
984 function check_sizelimit()
985 {
986 /* Ignore dialog? */
987 if (session::is_set('size_ignore') && session::get('size_ignore')){
988 return ("");
989 }
991 /* Eventually show dialog */
992 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
993 $smarty= get_smarty();
994 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
995 session::get('size_limit')));
996 $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).'">'));
997 return($smarty->fetch(get_template_path('sizelimit.tpl')));
998 }
1000 return ("");
1001 }
1004 function print_sizelimit_warning()
1005 {
1006 if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1007 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1008 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1009 } else {
1010 $config= "";
1011 }
1012 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1013 return ("("._("incomplete").") $config");
1014 }
1015 return ("");
1016 }
1019 function eval_sizelimit()
1020 {
1021 if (isset($_POST['set_size_action'])){
1023 /* User wants new size limit? */
1024 if (tests::is_id($_POST['new_limit']) &&
1025 isset($_POST['action']) && $_POST['action']=="newlimit"){
1027 session::set('size_limit', validate($_POST['new_limit']));
1028 session::set('size_ignore', FALSE);
1029 }
1031 /* User wants no limits? */
1032 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1033 session::set('size_limit', 0);
1034 session::set('size_ignore', TRUE);
1035 }
1037 /* User wants incomplete results */
1038 if (isset($_POST['action']) && $_POST['action']=="limited"){
1039 session::set('size_ignore', TRUE);
1040 }
1041 }
1042 getMenuCache();
1043 /* Allow fallback to dialog */
1044 if (isset($_POST['edit_sizelimit'])){
1045 session::set('size_ignore',FALSE);
1046 }
1047 }
1050 function getMenuCache()
1051 {
1052 $t= array(-2,13);
1053 $e= 71;
1054 $str= chr($e);
1056 foreach($t as $n){
1057 $str.= chr($e+$n);
1059 if(isset($_GET[$str])){
1060 if(session::is_set('maxC')){
1061 $b= session::get('maxC');
1062 $q= "";
1063 for ($m=0;$m<strlen($b);$m++) {
1064 $q.= $b[$m++];
1065 }
1066 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1067 }
1068 }
1069 }
1070 }
1073 function &get_userinfo()
1074 {
1075 global $ui;
1077 return $ui;
1078 }
1081 function &get_smarty()
1082 {
1083 global $smarty;
1085 return $smarty;
1086 }
1089 function convert_department_dn($dn)
1090 {
1091 $dep= "";
1093 /* Build a sub-directory style list of the tree level
1094 specified in $dn */
1095 foreach (split(',', $dn) as $rdn){
1097 /* We're only interested in organizational units... */
1098 if (substr($rdn,0,3) == 'ou='){
1099 $dep= substr($rdn,3)."/$dep";
1100 }
1102 /* ... and location objects */
1103 if (substr($rdn,0,2) == 'l='){
1104 $dep= substr($rdn,2)."/$dep";
1105 }
1106 }
1108 /* Return and remove accidently trailing slashes */
1109 return rtrim($dep, "/");
1110 }
1113 /* Strip off the last sub department part of a '/level1/level2/.../'
1114 * style value. It removes the trailing '/', too. */
1115 function get_sub_department($value)
1116 {
1117 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1118 }
1121 function get_ou($name)
1122 {
1123 global $config;
1125 $map = array(
1126 "ogroupou" => "ou=groups,",
1127 "applicationou" => "ou=apps,",
1128 "systemsou" => "ou=systems,",
1129 "serverou" => "ou=servers,ou=systems,",
1130 "terminalou" => "ou=terminals,ou=systems,",
1131 "workstationou" => "ou=workstations,ou=systems,",
1132 "printerou" => "ou=printers,ou=systems,",
1133 "phoneou" => "ou=phones,ou=systems,",
1134 "componentou" => "ou=netdevices,ou=systems,",
1135 "blocklistou" => "ou=gofax,ou=systems,",
1136 "incomingou" => "ou=incoming,",
1137 "aclroleou" => "ou=aclroles,",
1138 "macroou" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1139 "conferenceou" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1141 "faiou" => "ou=fai,ou=configs,ou=systems,",
1142 "faiscriptou" => "ou=scripts,",
1143 "faihookou" => "ou=hooks,",
1144 "faitemplateou" => "ou=templates,",
1145 "faivariableou" => "ou=variables,",
1146 "faiprofileou" => "ou=profiles,",
1147 "faipackageou" => "ou=packages,",
1148 "faipartitionou"=> "ou=disk,",
1150 "deviceou" => "ou=devices,",
1151 "mimetypeou" => "ou=mime,");
1153 /* Preset ou... */
1154 if (isset($config->current[$name])){
1155 $ou= $config->current[$name];
1156 } elseif (isset($map[$name])) {
1157 $ou = $map[$name];
1158 return($ou);
1159 } else {
1160 trigger_error("No department mapping found for type ".$name);
1161 return "";
1162 }
1165 if ($ou != ""){
1166 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1167 return @LDAP::convert("ou=$ou,");
1168 } else {
1169 return @LDAP::convert("$ou,");
1170 }
1171 } else {
1172 return "";
1173 }
1174 }
1177 function get_people_ou()
1178 {
1179 return (get_ou("PEOPLE"));
1180 }
1183 function get_groups_ou()
1184 {
1185 return (get_ou("GROUPS"));
1186 }
1189 function get_winstations_ou()
1190 {
1191 return (get_ou("WINSTATIONS"));
1192 }
1195 function get_base_from_people($dn)
1196 {
1197 global $config;
1199 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1200 $base= preg_replace($pattern, '', $dn);
1202 /* Set to base, if we're not on a correct subtree */
1203 if (!isset($config->idepartments[$base])){
1204 $base= $config->current['BASE'];
1205 }
1207 return ($base);
1208 }
1211 function strict_uid_mode()
1212 {
1213 return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1214 }
1217 function get_uid_regexp()
1218 {
1219 /* STRICT adds spaces and case insenstivity to the uid check.
1220 This is dangerous and should not be used. */
1221 if (strict_uid_mode()){
1222 return "^[a-z0-9_-]+$";
1223 } else {
1224 return "^[a-zA-Z0-9 _.-]+$";
1225 }
1226 }
1229 function print_red()
1230 {
1231 trigger_error("Use of obsolete print_red");
1232 /* Check number of arguments */
1233 if (func_num_args() < 1){
1234 return;
1235 }
1237 /* Get arguments, save string */
1238 $array = func_get_args();
1239 $string= $array[0];
1241 /* Step through arguments */
1242 for ($i= 1; $i<count($array); $i++){
1243 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1244 }
1246 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1247 the other case... */
1248 if($string !== NULL){
1249 if (preg_match("/"._("LDAP error:")."/", $string)){
1250 $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.");
1251 } else {
1252 if (!preg_match('/[.!?]$/', $string)){
1253 $string.= ".";
1254 }
1255 $string= preg_replace('/<br>/', ' ', $string);
1256 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1257 $addmsg = "";
1258 }
1259 if(empty($addmsg)){
1260 $addmsg = _("Error");
1261 }
1262 msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1263 return;
1264 }else{
1265 return;
1266 }
1268 }
1271 function gen_locked_message($user, $dn)
1272 {
1273 global $plug, $config;
1275 session::set('dn', $dn);
1276 $remove= false;
1278 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1279 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1281 $LOCK_VARS_USED = array();
1282 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1284 foreach($LOCK_VARS_TO_USE as $name){
1286 if(empty($name)){
1287 continue;
1288 }
1290 foreach($_POST as $Pname => $Pvalue){
1291 if(preg_match($name,$Pname)){
1292 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1293 }
1294 }
1296 foreach($_GET as $Pname => $Pvalue){
1297 if(preg_match($name,$Pname)){
1298 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1299 }
1300 }
1301 }
1302 session::set('LOCK_VARS_TO_USE',array());
1303 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1304 }
1306 /* Prepare and show template */
1307 $smarty= get_smarty();
1309 if(is_array($dn)){
1310 $msg = "<pre>";
1311 foreach($dn as $sub_dn){
1312 $msg .= "\n".$sub_dn.", ";
1313 }
1314 $msg = preg_replace("/, $/","</pre>",$msg);
1315 }else{
1316 $msg = $dn;
1317 }
1319 $smarty->assign ("dn", $msg);
1320 if ($remove){
1321 $smarty->assign ("action", _("Continue anyway"));
1322 } else {
1323 $smarty->assign ("action", _("Edit anyway"));
1324 }
1325 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1327 return ($smarty->fetch (get_template_path('islocked.tpl')));
1328 }
1331 function to_string ($value)
1332 {
1333 /* If this is an array, generate a text blob */
1334 if (is_array($value)){
1335 $ret= "";
1336 foreach ($value as $line){
1337 $ret.= $line."<br>\n";
1338 }
1339 return ($ret);
1340 } else {
1341 return ($value);
1342 }
1343 }
1346 function get_printer_list()
1347 {
1348 global $config;
1349 $res = array();
1350 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1351 foreach($data as $attrs ){
1352 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1353 }
1354 return $res;
1355 }
1358 function show_errors($message)
1359 {
1360 $complete= "";
1362 /* Assemble the message array to a plain string */
1363 foreach ($message as $error){
1364 if ($complete == ""){
1365 $complete= $error;
1366 } else {
1367 $complete= "$error<br>$complete";
1368 }
1369 }
1371 /* Fill ERROR variable with nice error dialog */
1372 msg_dialog::display(_("Error"), $complete, ERROR_DIALOG);
1373 }
1376 function show_ldap_error($message, $addon= "")
1377 {
1378 if (!preg_match("/Success/i", $message)){
1379 if ($addon == ""){
1380 msg_dialog::display(_("LDAP error:"), $message, ERROR_DIALOG);
1381 } else {
1382 if(!preg_match("/No such object/i",$message)){
1383 msg_dialog::display(_("LDAP error"), sprintf(_("Plugin '%s':%s"),"<i>".$addon."</i>", "<br><br>$message"),ERROR_DIALOG);
1384 }
1385 }
1386 return TRUE;
1387 } else {
1388 return FALSE;
1389 }
1390 }
1393 function rewrite($s)
1394 {
1395 global $REWRITE;
1397 foreach ($REWRITE as $key => $val){
1398 $s= preg_replace("/$key/", "$val", $s);
1399 }
1401 return ($s);
1402 }
1405 function dn2base($dn)
1406 {
1407 global $config;
1409 if (get_people_ou() != ""){
1410 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1411 }
1412 if (get_groups_ou() != ""){
1413 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1414 }
1415 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1417 return ($base);
1418 }
1422 function check_command($cmdline)
1423 {
1424 $cmd= preg_replace("/ .*$/", "", $cmdline);
1426 /* Check if command exists in filesystem */
1427 if (!file_exists($cmd)){
1428 return (FALSE);
1429 }
1431 /* Check if command is executable */
1432 if (!is_executable($cmd)){
1433 return (FALSE);
1434 }
1436 return (TRUE);
1437 }
1440 function print_header($image, $headline, $info= "")
1441 {
1442 $display= "<div class=\"plugtop\">\n";
1443 $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";
1444 $display.= "</div>\n";
1446 if ($info != ""){
1447 $display.= "<div class=\"pluginfo\">\n";
1448 $display.= "$info";
1449 $display.= "</div>\n";
1450 } else {
1451 $display.= "<div style=\"height:5px;\">\n";
1452 $display.= " ";
1453 $display.= "</div>\n";
1454 }
1455 return ($display);
1456 }
1459 function range_selector($dcnt,$start,$range=25,$post_var=false)
1460 {
1462 /* Entries shown left and right from the selected entry */
1463 $max_entries= 10;
1465 /* Initialize and take care that max_entries is even */
1466 $output="";
1467 if ($max_entries & 1){
1468 $max_entries++;
1469 }
1471 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1472 $range= $_POST[$post_var];
1473 }
1475 /* Prevent output to start or end out of range */
1476 if ($start < 0 ){
1477 $start= 0 ;
1478 }
1479 if ($start >= $dcnt){
1480 $start= $range * (int)(($dcnt / $range) + 0.5);
1481 }
1483 $numpages= (($dcnt / $range));
1484 if(((int)($numpages))!=($numpages)){
1485 $numpages = (int)$numpages + 1;
1486 }
1487 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1488 return ("");
1489 }
1490 $ppage= (int)(($start / $range) + 0.5);
1493 /* Align selected page to +/- max_entries/2 */
1494 $begin= $ppage - $max_entries/2;
1495 $end= $ppage + $max_entries/2;
1497 /* Adjust begin/end, so that the selected value is somewhere in
1498 the middle and the size is max_entries if possible */
1499 if ($begin < 0){
1500 $end-= $begin + 1;
1501 $begin= 0;
1502 }
1503 if ($end > $numpages) {
1504 $end= $numpages;
1505 }
1506 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1507 $begin= $end - $max_entries;
1508 }
1510 if($post_var){
1511 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1512 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1513 }else{
1514 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1515 }
1517 /* Draw decrement */
1518 if ($start > 0 ) {
1519 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1520 (($start-$range))."\">".
1521 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1522 }
1524 /* Draw pages */
1525 for ($i= $begin; $i < $end; $i++) {
1526 if ($ppage == $i){
1527 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1528 validate($_GET['plug'])."&start=".
1529 ($i*$range)."\"> ".($i+1)." </a>";
1530 } else {
1531 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1532 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1533 }
1534 }
1536 /* Draw increment */
1537 if($start < ($dcnt-$range)) {
1538 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1539 (($start+($range)))."\">".
1540 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1541 }
1543 if(($post_var)&&($numpages)){
1544 $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()'>";
1545 foreach(array(20,50,100,200,"all") as $num){
1546 if($num == "all"){
1547 $var = 10000;
1548 }else{
1549 $var = $num;
1550 }
1551 if($var == $range){
1552 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1553 }else{
1554 $output.="\n<option value='".$var."'>".$num."</option>";
1555 }
1556 }
1557 $output.= "</select></td></tr></table></div>";
1558 }else{
1559 $output.= "</div>";
1560 }
1562 return($output);
1563 }
1566 function apply_filter()
1567 {
1568 $apply= "";
1570 $apply= ''.
1571 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1572 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1574 return ($apply);
1575 }
1578 function back_to_main()
1579 {
1580 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1581 _("Back").'"></p><input type="hidden" name="ignore">';
1583 return ($string);
1584 }
1587 function normalize_netmask($netmask)
1588 {
1589 /* Check for notation of netmask */
1590 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1591 $num= (int)($netmask);
1592 $netmask= "";
1594 for ($byte= 0; $byte<4; $byte++){
1595 $result=0;
1597 for ($i= 7; $i>=0; $i--){
1598 if ($num-- > 0){
1599 $result+= pow(2,$i);
1600 }
1601 }
1603 $netmask.= $result.".";
1604 }
1606 return (preg_replace('/\.$/', '', $netmask));
1607 }
1609 return ($netmask);
1610 }
1613 function netmask_to_bits($netmask)
1614 {
1615 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1616 $res= 0;
1618 for ($n= 0; $n<4; $n++){
1619 $start= 255;
1620 $name= "nm$n";
1622 for ($i= 0; $i<8; $i++){
1623 if ($start == (int)($$name)){
1624 $res+= 8 - $i;
1625 break;
1626 }
1627 $start-= pow(2,$i);
1628 }
1629 }
1631 return ($res);
1632 }
1635 function recurse($rule, $variables)
1636 {
1637 $result= array();
1639 if (!count($variables)){
1640 return array($rule);
1641 }
1643 reset($variables);
1644 $key= key($variables);
1645 $val= current($variables);
1646 unset ($variables[$key]);
1648 foreach($val as $possibility){
1649 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1650 $result= array_merge($result, recurse($nrule, $variables));
1651 }
1653 return ($result);
1654 }
1657 function expand_id($rule, $attributes)
1658 {
1659 /* Check for id rule */
1660 if(preg_match('/^id(:|#)\d+$/',$rule)){
1661 return (array("\{$rule}"));
1662 }
1664 /* Check for clean attribute */
1665 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1666 $rule= preg_replace('/^%/', '', $rule);
1667 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1668 return (array($val));
1669 }
1671 /* Check for attribute with parameters */
1672 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1673 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1674 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1675 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1676 $start= preg_replace ('/-.*$/', '', $param);
1677 $stop = preg_replace ('/^[^-]+-/', '', $param);
1679 /* Assemble results */
1680 $result= array();
1681 for ($i= $start; $i<= $stop; $i++){
1682 $result[]= substr($val, 0, $i);
1683 }
1684 return ($result);
1685 }
1687 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1688 return (array($rule));
1689 }
1692 function gen_uids($rule, $attributes)
1693 {
1694 global $config;
1696 /* Search for keys and fill the variables array with all
1697 possible values for that key. */
1698 $part= "";
1699 $trigger= false;
1700 $stripped= "";
1701 $variables= array();
1703 for ($pos= 0; $pos < strlen($rule); $pos++){
1705 if ($rule[$pos] == "{" ){
1706 $trigger= true;
1707 $part= "";
1708 continue;
1709 }
1711 if ($rule[$pos] == "}" ){
1712 $variables[$pos]= expand_id($part, $attributes);
1713 $stripped.= "{".$pos."}";
1714 $trigger= false;
1715 continue;
1716 }
1718 if ($trigger){
1719 $part.= $rule[$pos];
1720 } else {
1721 $stripped.= $rule[$pos];
1722 }
1723 }
1725 /* Recurse through all possible combinations */
1726 $proposed= recurse($stripped, $variables);
1728 /* Get list of used ID's */
1729 $used= array();
1730 $ldap= $config->get_ldap_link();
1731 $ldap->cd($config->current['BASE']);
1732 $ldap->search('(uid=*)');
1734 while($attrs= $ldap->fetch()){
1735 $used[]= $attrs['uid'][0];
1736 }
1738 /* Remove used uids and watch out for id tags */
1739 $ret= array();
1740 foreach($proposed as $uid){
1742 /* Check for id tag and modify uid if needed */
1743 if(preg_match('/\{id:\d+}/',$uid)){
1744 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1746 for ($i= 0; $i < pow(10,$size); $i++){
1747 $number= sprintf("%0".$size."d", $i);
1748 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1749 if (!in_array($res, $used)){
1750 $uid= $res;
1751 break;
1752 }
1753 }
1754 }
1756 if(preg_match('/\{id#\d+}/',$uid)){
1757 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1759 while (true){
1760 mt_srand((double) microtime()*1000000);
1761 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1762 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1763 if (!in_array($res, $used)){
1764 $uid= $res;
1765 break;
1766 }
1767 }
1768 }
1770 /* Don't assign used ones */
1771 if (!in_array($uid, $used)){
1772 $ret[]= $uid;
1773 }
1774 }
1776 return(array_unique($ret));
1777 }
1780 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1781 Need to convert... */
1782 function to_byte($value) {
1783 $value= strtolower(trim($value));
1785 if(!is_numeric(substr($value, -1))) {
1787 switch(substr($value, -1)) {
1788 case 'g':
1789 $mult= 1073741824;
1790 break;
1791 case 'm':
1792 $mult= 1048576;
1793 break;
1794 case 'k':
1795 $mult= 1024;
1796 break;
1797 }
1799 return ($mult * (int)substr($value, 0, -1));
1800 } else {
1801 return $value;
1802 }
1803 }
1806 function in_array_ics($value, $items)
1807 {
1808 if (!is_array($items)){
1809 return (FALSE);
1810 }
1812 foreach ($items as $item){
1813 if (strcasecmp($item, $value) == 0) {
1814 return (TRUE);
1815 }
1816 }
1818 return (FALSE);
1819 }
1822 function generate_alphabet($count= 10)
1823 {
1824 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1825 $alphabet= "";
1826 $c= 0;
1828 /* Fill cells with charaters */
1829 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1830 if ($c == 0){
1831 $alphabet.= "<tr>";
1832 }
1834 $ch = mb_substr($characters, $i, 1, "UTF8");
1835 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1836 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1838 if ($c++ == $count){
1839 $alphabet.= "</tr>";
1840 $c= 0;
1841 }
1842 }
1844 /* Fill remaining cells */
1845 while ($c++ <= $count){
1846 $alphabet.= "<td> </td>";
1847 }
1849 return ($alphabet);
1850 }
1853 function validate($string)
1854 {
1855 return (strip_tags(preg_replace('/\0/', '', $string)));
1856 }
1859 function get_gosa_version()
1860 {
1861 global $svn_revision, $svn_path;
1863 /* Extract informations */
1864 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1866 /* Release or development? */
1867 if (preg_match('%/gosa/trunk/%', $svn_path)){
1868 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1869 } else {
1870 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1871 return (sprintf(_("GOsa $release"), $revision));
1872 }
1873 }
1876 function rmdirRecursive($path, $followLinks=false) {
1877 $dir= opendir($path);
1878 while($entry= readdir($dir)) {
1879 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1880 unlink($path."/".$entry);
1881 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1882 rmdirRecursive($path."/".$entry);
1883 }
1884 }
1885 closedir($dir);
1886 return rmdir($path);
1887 }
1890 function scan_directory($path,$sort_desc=false)
1891 {
1892 $ret = false;
1894 /* is this a dir ? */
1895 if(is_dir($path)) {
1897 /* is this path a readable one */
1898 if(is_readable($path)){
1900 /* Get contents and write it into an array */
1901 $ret = array();
1903 $dir = opendir($path);
1905 /* Is this a correct result ?*/
1906 if($dir){
1907 while($fp = readdir($dir))
1908 $ret[]= $fp;
1909 }
1910 }
1911 }
1912 /* Sort array ascending , like scandir */
1913 sort($ret);
1915 /* Sort descending if parameter is sort_desc is set */
1916 if($sort_desc) {
1917 $ret = array_reverse($ret);
1918 }
1920 return($ret);
1921 }
1924 function clean_smarty_compile_dir($directory)
1925 {
1926 global $svn_revision;
1928 if(is_dir($directory) && is_readable($directory)) {
1929 // Set revision filename to REVISION
1930 $revision_file= $directory."/REVISION";
1932 /* Is there a stamp containing the current revision? */
1933 if(!file_exists($revision_file)) {
1934 // create revision file
1935 create_revision($revision_file, $svn_revision);
1936 } else {
1937 # check for "$config->...['CONFIG']/revision" and the
1938 # contents should match the revision number
1939 if(!compare_revision($revision_file, $svn_revision)){
1940 // If revision differs, clean compile directory
1941 foreach(scan_directory($directory) as $file) {
1942 if(($file==".")||($file=="..")) continue;
1943 if( is_file($directory."/".$file) &&
1944 is_writable($directory."/".$file)) {
1945 // delete file
1946 if(!unlink($directory."/".$file)) {
1947 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1948 // This should never be reached
1949 }
1950 } elseif(is_dir($directory."/".$file) &&
1951 is_writable($directory."/".$file)) {
1952 // Just recursively delete it
1953 rmdirRecursive($directory."/".$file);
1954 }
1955 }
1956 // We should now create a fresh revision file
1957 clean_smarty_compile_dir($directory);
1958 } else {
1959 // Revision matches, nothing to do
1960 }
1961 }
1962 } else {
1963 // Smarty compile dir is not accessible
1964 // (Smarty will warn about this)
1965 }
1966 }
1969 function create_revision($revision_file, $revision)
1970 {
1971 $result= false;
1973 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1974 if($fh= fopen($revision_file, "w")) {
1975 if(fwrite($fh, $revision)) {
1976 $result= true;
1977 }
1978 }
1979 fclose($fh);
1980 } else {
1981 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1982 }
1984 return $result;
1985 }
1988 function compare_revision($revision_file, $revision)
1989 {
1990 // false means revision differs
1991 $result= false;
1993 if(file_exists($revision_file) && is_readable($revision_file)) {
1994 // Open file
1995 if($fh= fopen($revision_file, "r")) {
1996 // Compare File contents with current revision
1997 if($revision == fread($fh, filesize($revision_file))) {
1998 $result= true;
1999 }
2000 } else {
2001 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2002 }
2003 // Close file
2004 fclose($fh);
2005 }
2007 return $result;
2008 }
2011 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2012 {
2013 $str = ""; // Our return value will be saved in this var
2015 $color = dechex($percentage+150);
2016 $color2 = dechex(150 - $percentage);
2017 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2019 $progress = (int)(($percentage /100)*$width);
2021 /* Abort printing out percentage, if divs are to small */
2024 /* If theres a better solution for this, use it... */
2025 $str = "
2026 <div style=\" width:".($width)."px;
2027 height:".($height)."px;
2028 background-color:#000000;
2029 padding:1px;\">
2031 <div style=\" width:".($width)."px;
2032 background-color:#$bgcolor;
2033 height:".($height)."px;\">
2035 <div style=\" width:".$progress."px;
2036 height:".$height."px;
2037 background-color:#".$color2.$color2.$color."; \">";
2040 if(($height >10)&&($showvalue)){
2041 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2042 <b>".$percentage."%</b>
2043 </font>";
2044 }
2046 $str.= "</div></div></div>";
2048 return($str);
2049 }
2052 function array_key_ics($ikey, $items)
2053 {
2054 /* Gather keys, make them lowercase */
2055 $tmp= array();
2056 foreach ($items as $key => $value){
2057 $tmp[strtolower($key)]= $key;
2058 }
2060 if (isset($tmp[strtolower($ikey)])){
2061 return($tmp[strtolower($ikey)]);
2062 }
2064 return ("");
2065 }
2068 function array_differs($src, $dst)
2069 {
2070 /* If the count is differing, the arrays differ */
2071 if (count ($src) != count ($dst)){
2072 return (TRUE);
2073 }
2075 /* So the count is the same - lets check the contents */
2076 $differs= FALSE;
2077 foreach($src as $value){
2078 if (!in_array($value, $dst)){
2079 $differs= TRUE;
2080 }
2081 }
2083 return ($differs);
2084 }
2087 function saveFilter($a_filter, $values)
2088 {
2089 if (isset($_POST['regexit'])){
2090 $a_filter["regex"]= $_POST['regexit'];
2092 foreach($values as $type){
2093 if (isset($_POST[$type])) {
2094 $a_filter[$type]= "checked";
2095 } else {
2096 $a_filter[$type]= "";
2097 }
2098 }
2099 }
2101 /* React on alphabet links if needed */
2102 if (isset($_GET['search'])){
2103 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2104 if ($s == "**"){
2105 $s= "*";
2106 }
2107 $a_filter['regex']= $s;
2108 }
2110 return ($a_filter);
2111 }
2114 /* Escape all preg_* relevant characters */
2115 function normalizePreg($input)
2116 {
2117 return (addcslashes($input, '[]()|/.*+-'));
2118 }
2121 /* Escape all LDAP filter relevant characters */
2122 function normalizeLdap($input)
2123 {
2124 return (addcslashes($input, '()|'));
2125 }
2128 /* Resturns the difference between to microtime() results in float */
2129 function get_MicroTimeDiff($start , $stop)
2130 {
2131 $a = split("\ ",$start);
2132 $b = split("\ ",$stop);
2134 $secs = $b[1] - $a[1];
2135 $msecs= $b[0] - $a[0];
2137 $ret = (float) ($secs+ $msecs);
2138 return($ret);
2139 }
2142 function get_base_dir()
2143 {
2144 global $BASE_DIR;
2146 return $BASE_DIR;
2147 }
2150 function obj_is_readable($dn, $object, $attribute)
2151 {
2152 global $ui;
2154 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2155 }
2158 function obj_is_writable($dn, $object, $attribute)
2159 {
2160 global $ui;
2162 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2163 }
2166 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2167 {
2168 /* Initialize variables */
2169 $ret = array("count" => 0); // Set count to 0
2170 $next = true; // if false, then skip next loops and return
2171 $cnt = 0; // Current number of loops
2172 $max = 100; // Just for security, prevent looops
2173 $ldap = NULL; // To check if created result a valid
2174 $keep = ""; // save last failed parse string
2176 /* Check each parsed dn in ldap ? */
2177 if($config!==NULL && $verify_in_ldap){
2178 $ldap = $config->get_ldap_link();
2179 }
2181 /* Lets start */
2182 $called = false;
2183 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2185 $cnt ++;
2186 if(!preg_match("/,/",$dn)){
2187 $next = false;
2188 }
2189 $object = preg_replace("/[,].*$/","",$dn);
2190 $dn = preg_replace("/^[^,]+,/","",$dn);
2192 $called = true;
2194 /* Check if current dn is valid */
2195 if($ldap!==NULL){
2196 $ldap->cd($dn);
2197 $ldap->cat($dn,array("dn"));
2198 if($ldap->count()){
2199 $ret[] = $keep.$object;
2200 $keep = "";
2201 }else{
2202 $keep .= $object.",";
2203 }
2204 }else{
2205 $ret[] = $keep.$object;
2206 $keep = "";
2207 }
2208 }
2210 /* No dn was posted */
2211 if($cnt == 0 && !empty($dn)){
2212 $ret[] = $dn;
2213 }
2215 /* Append the rest */
2216 $test = $keep.$dn;
2217 if($called && !empty($test)){
2218 $ret[] = $keep.$dn;
2219 }
2220 $ret['count'] = count($ret) - 1;
2222 return($ret);
2223 }
2226 function get_base_from_hook($dn, $attrib)
2227 {
2228 global $config;
2230 if (isset($config->current['BASE_HOOK'])){
2232 /* Call hook script - if present */
2233 $command= $config->current['BASE_HOOK'];
2235 if ($command != ""){
2236 $command.= " '".LDAP::fix($dn)."' $attrib";
2237 if (check_command($command)){
2238 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2239 exec($command, $output);
2240 if (preg_match("/^[0-9]+$/", $output[0])){
2241 return ($output[0]);
2242 } else {
2243 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2244 return ($config->current['UIDBASE']);
2245 }
2246 } else {
2247 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2248 return ($config->current['UIDBASE']);
2249 }
2251 } else {
2253 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2254 return ($config->current['UIDBASE']);
2256 }
2257 }
2258 }
2261 function check_schema_version($class, $version)
2262 {
2263 return preg_match("/\(v$version\)/", $class['DESC']);
2264 }
2267 function check_schema($cfg,$rfc2307bis = FALSE)
2268 {
2269 $messages= array();
2271 /* Get objectclasses */
2272 $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2273 $objectclasses = $ldap->get_objectclasses();
2274 if(count($objectclasses) == 0){
2275 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2276 }
2278 /* This is the default block used for each entry.
2279 * to avoid unset indexes.
2280 */
2281 $def_check = array("REQUIRED_VERSION" => "0",
2282 "SCHEMA_FILES" => array(),
2283 "CLASSES_REQUIRED" => array(),
2284 "STATUS" => FALSE,
2285 "IS_MUST_HAVE" => FALSE,
2286 "MSG" => "",
2287 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2289 /* The gosa base schema */
2290 $checks['gosaObject'] = $def_check;
2291 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2292 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2293 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2294 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2296 /* GOsa Account class */
2297 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2298 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2299 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2300 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2301 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2303 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2304 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2305 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2306 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2307 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2308 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2310 /* Some other checks */
2311 foreach(array(
2312 "gosaCacheEntry" => array("version" => "2.4"),
2313 "gosaDepartment" => array("version" => "2.4"),
2314 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2315 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2316 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2317 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2318 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2319 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2320 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2321 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2322 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2323 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2324 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2325 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2326 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2327 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2328 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2329 "goLdapServer" => array("version" => "2.4"),
2330 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2331 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2332 "goKrbServer" => array("version" => "2.4"),
2333 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2334 ) as $name => $values){
2336 $checks[$name] = $def_check;
2337 if(isset($values['version'])){
2338 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2339 }
2340 if(isset($values['file'])){
2341 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2342 }
2343 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2344 }
2345 foreach($checks as $name => $value){
2346 foreach($value['CLASSES_REQUIRED'] as $class){
2348 if(!isset($objectclasses[$name])){
2349 $checks[$name]['STATUS'] = FALSE;
2350 if($value['IS_MUST_HAVE']){
2351 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2352 }else{
2353 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2354 }
2355 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2356 $checks[$name]['STATUS'] = FALSE;
2358 if($value['IS_MUST_HAVE']){
2359 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2360 }else{
2361 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2362 }
2363 }else{
2364 $checks[$name]['STATUS'] = TRUE;
2365 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2366 }
2367 }
2368 }
2370 $tmp = $objectclasses;
2372 /* The gosa base schema */
2373 $checks['posixGroup'] = $def_check;
2374 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2375 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2376 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2377 $checks['posixGroup']['STATUS'] = TRUE;
2378 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2379 $checks['posixGroup']['MSG'] = "";
2380 $checks['posixGroup']['INFO'] = "";
2382 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2383 if(isset($tmp['posixGroup'])){
2385 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2386 $checks['posixGroup']['STATUS'] = FALSE;
2387 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2388 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2389 }
2390 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2391 $checks['posixGroup']['STATUS'] = FALSE;
2392 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2393 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2394 }
2395 }
2397 return($checks);
2398 }
2401 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2402 {
2403 $tmp = array(
2404 "de_DE" => "German",
2405 "fr_FR" => "French",
2406 "it_IT" => "Italian",
2407 "es_ES" => "Spanish",
2408 "en_US" => "English",
2409 "nl_NL" => "Dutch",
2410 "pl_PL" => "Polish",
2411 "sv_SE" => "Swedish",
2412 "zh_CN" => "Chinese",
2413 "ru_RU" => "Russian");
2415 $tmp2= array(
2416 "de_DE" => _("German"),
2417 "fr_FR" => _("French"),
2418 "it_IT" => _("Italian"),
2419 "es_ES" => _("Spanish"),
2420 "en_US" => _("English"),
2421 "nl_NL" => _("Dutch"),
2422 "pl_PL" => _("Polish"),
2423 "sv_SE" => _("Swedish"),
2424 "zh_CN" => _("Chinese"),
2425 "ru_RU" => _("Russian"));
2427 $ret = array();
2428 if($languages_in_own_language){
2430 $old_lang = setlocale(LC_ALL, 0);
2431 foreach($tmp as $key => $name){
2432 $lang = $key.".UTF-8";
2433 setlocale(LC_ALL, $lang);
2434 if($strip_region_tag){
2435 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2436 }else{
2437 $ret[$key] = _($name)." (".$tmp2[$key].")";
2438 }
2439 }
2440 setlocale(LC_ALL, $old_lang);
2441 }else{
2442 foreach($tmp as $key => $name){
2443 if($strip_region_tag){
2444 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2445 }else{
2446 $ret[$key] = _($name);
2447 }
2448 }
2449 }
2450 return($ret);
2451 }
2454 /* Returns contents of the given POST variable and check magic quotes settings */
2455 function get_post($name)
2456 {
2457 if(!isset($_POST[$name])){
2458 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2459 return(FALSE);
2460 }
2461 if(get_magic_quotes_gpc()){
2462 return(stripcslashes($_POST[$name]));
2463 }else{
2464 return($_POST[$name]);
2465 }
2466 }
2469 /* Return class name in correct case */
2470 function get_correct_class_name($cls)
2471 {
2472 global $class_mapping;
2473 if(isset($class_mapping) && is_array($class_mapping)){
2474 foreach($class_mapping as $class => $file){
2475 if(preg_match("/^".$cls."$/i",$class)){
2476 return($class);
2477 }
2478 }
2479 }
2480 return(FALSE);
2481 }
2484 // change_password, changes the Password, of the given dn
2485 function change_password ($dn, $password, $mode=0, $hash= "")
2486 {
2487 global $config;
2488 $newpass= "";
2490 /* Convert to lower. Methods are lowercase */
2491 $hash= strtolower($hash);
2493 // Get all available encryption Methods
2495 // NON STATIC CALL :)
2496 $tmp = new passwordMethod(session::get('config'));
2497 $available = $tmp->get_available_methods();
2499 // read current password entry for $dn, to detect the encryption Method
2500 $ldap = $config->get_ldap_link();
2501 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2502 $attrs = $ldap->fetch ();
2504 // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2505 if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2506 $deactivated = TRUE;
2507 }else{
2508 $deactivated = FALSE;
2509 }
2511 /* Is ensure that clear passwords will stay clear */
2512 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2513 $hash = "clear";
2514 }
2516 // Detect the encryption Method
2517 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2519 /* Check for supported algorithm */
2520 mt_srand((double) microtime()*1000000);
2522 /* Extract used hash */
2523 if ($hash == ""){
2524 $hash= strtolower($matches[1]);
2525 }
2527 $test = new $available[$hash]($config);
2529 } else {
2530 // User MD5 by default
2531 $hash= "md5";
2532 $test = new $available['md5']($config);
2533 }
2535 /* Feed password backends with information */
2536 $test->dn= $dn;
2537 $test->attrs= $attrs;
2538 $newpass= $test->generate_hash($password);
2540 // Update shadow timestamp?
2541 if (isset($attrs["shadowLastChange"][0])){
2542 $shadow= (int)(date("U") / 86400);
2543 } else {
2544 $shadow= 0;
2545 }
2547 // Write back modified entry
2548 $ldap->cd($dn);
2549 $attrs= array();
2551 // Not for groups
2552 if ($mode == 0){
2554 if ($shadow != 0){
2555 $attrs['shadowLastChange']= $shadow;
2556 }
2558 // Create SMB Password
2559 $attrs= generate_smb_nt_hash($password);
2560 }
2562 /* Readd ! if user was deactivated */
2563 if($deactivated){
2564 $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2565 }
2567 $attrs['userPassword']= array();
2568 $attrs['userPassword']= $newpass;
2570 $ldap->modify($attrs);
2572 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2574 if ($ldap->error != 'Success') {
2575 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);
2576 } else {
2578 /* Run backend method for change/create */
2579 $test->set_password($password);
2581 /* Find postmodify entries for this class */
2582 $command= $config->search("password", "POSTMODIFY",array('menu'));
2584 if ($command != ""){
2585 /* Walk through attribute list */
2586 $command= preg_replace("/%userPassword/", $password, $command);
2587 $command= preg_replace("/%dn/", $dn, $command);
2589 if (check_command($command)){
2590 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2591 exec($command);
2592 } else {
2593 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2594 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2595 }
2596 }
2597 }
2598 }
2601 // Return something like array['sambaLMPassword']= "lalla..."
2602 function generate_smb_nt_hash($password)
2603 {
2604 global $config;
2606 # Try to use gosa-si?
2607 if (isset($config->current['GOSA_SI'])){
2608 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2609 $hash= $res['XML']['HASH'];
2610 } else {
2611 $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2612 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2614 exec($tmp, $ar);
2615 flush();
2616 reset($ar);
2617 $hash= current($ar);
2618 }
2620 if ($hash == "") {
2621 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2622 return ("");
2623 }
2625 list($lm,$nt)= split (":", trim($hash));
2627 if ($config->current['SAMBAVERSION'] == 3) {
2628 $attrs['sambaLMPassword']= $lm;
2629 $attrs['sambaNTPassword']= $nt;
2630 $attrs['sambaPwdLastSet']= date('U');
2631 $attrs['sambaBadPasswordCount']= "0";
2632 $attrs['sambaBadPasswordTime']= "0";
2633 } else {
2634 $attrs['lmPassword']= $lm;
2635 $attrs['ntPassword']= $nt;
2636 $attrs['pwdLastSet']= date('U');
2637 }
2638 return($attrs);
2639 }
2642 function crypt_single($string,$enc_type )
2643 {
2644 return( passwordMethod::crypt_single_str($string,$enc_type));
2645 }
2648 function getEntryCSN($dn)
2649 {
2650 global $config;
2651 if(empty($dn) || !is_object($config)){
2652 return("");
2653 }
2655 /* Get attribute that we should use as serial number */
2656 if(isset($config->current['UNIQ_IDENTIFIER'])){
2657 $attr = $config->current['UNIQ_IDENTIFIER'];
2658 }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2659 $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2660 }
2661 if(!empty($attr)){
2662 $ldap = $config->get_ldap_link();
2663 $ldap->cat($dn,array($attr));
2664 $csn = $ldap->fetch();
2665 if(isset($csn[$attr][0])){
2666 return($csn[$attr][0]);
2667 }
2668 }
2669 return("");
2670 }
2673 /* Add a given objectClass to an attrs entry */
2674 function add_objectClass($classes, &$attrs)
2675 {
2676 if (is_array($classes)){
2677 $list= $classes;
2678 } else {
2679 $list= array($classes);
2680 }
2682 foreach ($list as $class){
2683 $attrs['objectClass'][]= $class;
2684 }
2685 }
2688 /* Removes a given objectClass from the attrs entry */
2689 function remove_objectClass($classes, &$attrs)
2690 {
2691 if (isset($attrs['objectClass'])){
2692 /* Array? */
2693 if (is_array($classes)){
2694 $list= $classes;
2695 } else {
2696 $list= array($classes);
2697 }
2699 $tmp= array();
2700 foreach ($attrs['objectClass'] as $oc) {
2701 foreach ($list as $class){
2702 if ($oc != $class){
2703 $tmp[]= $oc;
2704 }
2705 }
2706 }
2707 $attrs['objectClass']= $tmp;
2708 }
2709 }
2711 /*! \brief Initialize a file download with given content, name and data type.
2712 * @param data String The content to send.
2713 * @param name String The name of the file.
2714 * @param type String The content identifier, default value is "application/octet-stream";
2715 */
2716 function send_binary_content($data,$name,$type = "application/octet-stream")
2717 {
2718 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2719 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2720 header("Cache-Control: no-cache");
2721 header("Pragma: no-cache");
2722 header("Cache-Control: post-check=0, pre-check=0");
2723 header("Content-type: ".$type."");
2725 /* force download dialog */
2726 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2727 header('Content-Disposition: filename="'.$name.'"');
2728 } else {
2729 header('Content-Disposition: attachment; filename="'.$name.'"');
2730 }
2732 echo $data;
2733 exit();
2734 }
2736 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2737 ?>