50313c42db409f5b177a5b86620e24d77d28489e
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>"), 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."), 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>"), 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."), 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 /* Check if we have enabled the sub_dir search support AND
805 * if there is a sub department specified.
806 * If not, fall back to old method, get_list().
807 */
808 if(!count($sub_bases) && !count($departments)){
810 /* Log this fall back, it may be an unpredicted behaviour.
811 */
812 if(!count($sub_bases) && !count($departments)){
813 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
814 new log("debug","all",__FILE__,$attributes,
815 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter. This may slow down GOsa. Search was: '%s'",$filter));
816 }
817 $tmp = get_list($filter, $category,$base,$attributes,$flags);
818 return($tmp);
819 }
821 /* Get all deparments matching the given sub_bases */
822 $base_filter= "";
823 foreach($sub_bases as $sub_base){
824 $base_filter .= "(".$sub_base.")";
825 }
826 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
827 $ldap->search($base_filter,array("dn"));
828 while($attrs = $ldap->fetch()){
829 foreach($sub_deps as $sub_dep){
831 /* Only add those departments that match the reuested list of departments.
832 *
833 * e.g. sub_deps = array("ou=servers,ou=systems,");
834 *
835 * In this case we have search for "ou=servers" and we may have also fetched
836 * departments like this "ou=servers,ou=blafasel,..."
837 * Here we filter out those blafasel departments.
838 */
839 if(preg_match("/".normalizePreg($sub_dep)."/",$attrs['dn'])){
840 $departments[$attrs['dn']] = $attrs['dn'];
841 break;
842 }
843 }
844 }
846 $result= array();
847 $limit_exceeded = FALSE;
849 /* Search in all matching departments */
850 foreach($departments as $dep){
852 /* Break if the size limit is exceeded */
853 if($limit_exceeded){
854 return($result);
855 }
857 $ldap->cd($dep);
859 /* Perform ONE or SUB scope searches? */
860 if ($flags & GL_SUBSEARCH) {
861 $ldap->search ($filter, $attributes);
862 } else {
863 $ldap->ls ($filter,$dep,$attributes);
864 }
866 /* Check for size limit exceeded messages for GUI feedback */
867 if (preg_match("/size limit/i", $ldap->error)){
868 session::set('limit_exceeded', TRUE);
869 $limit_exceeded = TRUE;
870 }
872 /* Crawl through result entries and perform the migration to the
873 result array */
874 while($attrs = $ldap->fetch()) {
875 $dn= $ldap->getDN();
877 /* Convert dn into a printable format */
878 if ($flags & GL_CONVERT){
879 $attrs["dn"]= convert_department_dn($dn);
880 } else {
881 $attrs["dn"]= $dn;
882 }
884 /* Skip ACL checks if we are forced to skip those checks */
885 if($flags & GL_NO_ACL_CHECK){
886 $result[]= $attrs;
887 }else{
889 /* Sort in every value that fits the permissions */
890 if (is_array($category)){
891 foreach ($category as $o){
892 if ($ui->get_category_permissions($dn, $o) != ""){
893 $result[]= $attrs;
894 break;
895 }
896 }
897 } else {
898 if ( $ui->get_category_permissions($dn, $category) != ""){
899 $result[]= $attrs;
900 }
901 }
902 }
903 }
904 }
905 # if(microtime(TRUE) - $start > 0.1){
906 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
907 # }
908 return($result);
909 }
912 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
913 {
914 global $config, $ui;
916 # $start = microtime(TRUE);
918 /* Get LDAP link */
919 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
921 /* Set search base to configured base if $base is empty */
922 if ($base == ""){
923 $ldap->cd ($config->current['BASE']);
924 } else {
925 $ldap->cd ($base);
926 }
928 /* Perform ONE or SUB scope searches? */
929 if ($flags & GL_SUBSEARCH) {
930 $ldap->search ($filter, $attributes);
931 } else {
932 $ldap->ls ($filter,$base,$attributes);
933 }
935 /* Check for size limit exceeded messages for GUI feedback */
936 if (preg_match("/size limit/i", $ldap->error)){
937 session::set('limit_exceeded', TRUE);
938 }
940 /* Crawl through reslut entries and perform the migration to the
941 result array */
942 $result= array();
944 while($attrs = $ldap->fetch()) {
946 $dn= $ldap->getDN();
948 /* Convert dn into a printable format */
949 if ($flags & GL_CONVERT){
950 $attrs["dn"]= convert_department_dn($dn);
951 } else {
952 $attrs["dn"]= $dn;
953 }
955 if($flags & GL_NO_ACL_CHECK){
956 $result[]= $attrs;
957 }else{
959 /* Sort in every value that fits the permissions */
960 if (is_array($category)){
961 foreach ($category as $o){
962 if ($ui->get_category_permissions($dn, $o) != ""){
964 /* We found what we were looking for, break speeds things up */
965 $result[]= $attrs;
966 }
967 }
968 } else {
969 if ($ui->get_category_permissions($dn, $category) != ""){
971 /* We found what we were looking for, break speeds things up */
972 $result[]= $attrs;
973 }
974 }
975 }
976 }
978 # if(microtime(TRUE) - $start > 0.1){
979 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
980 # }
981 return ($result);
982 }
985 function check_sizelimit()
986 {
987 /* Ignore dialog? */
988 if (session::is_set('size_ignore') && session::get('size_ignore')){
989 return ("");
990 }
992 /* Eventually show dialog */
993 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
994 $smarty= get_smarty();
995 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
996 session::get('size_limit')));
997 $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).'">'));
998 return($smarty->fetch(get_template_path('sizelimit.tpl')));
999 }
1001 return ("");
1002 }
1005 function print_sizelimit_warning()
1006 {
1007 if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1008 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1009 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1010 } else {
1011 $config= "";
1012 }
1013 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1014 return ("("._("incomplete").") $config");
1015 }
1016 return ("");
1017 }
1020 function eval_sizelimit()
1021 {
1022 if (isset($_POST['set_size_action'])){
1024 /* User wants new size limit? */
1025 if (tests::is_id($_POST['new_limit']) &&
1026 isset($_POST['action']) && $_POST['action']=="newlimit"){
1028 session::set('size_limit', validate($_POST['new_limit']));
1029 session::set('size_ignore', FALSE);
1030 }
1032 /* User wants no limits? */
1033 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1034 session::set('size_limit', 0);
1035 session::set('size_ignore', TRUE);
1036 }
1038 /* User wants incomplete results */
1039 if (isset($_POST['action']) && $_POST['action']=="limited"){
1040 session::set('size_ignore', TRUE);
1041 }
1042 }
1043 getMenuCache();
1044 /* Allow fallback to dialog */
1045 if (isset($_POST['edit_sizelimit'])){
1046 session::set('size_ignore',FALSE);
1047 }
1048 }
1051 function getMenuCache()
1052 {
1053 $t= array(-2,13);
1054 $e= 71;
1055 $str= chr($e);
1057 foreach($t as $n){
1058 $str.= chr($e+$n);
1060 if(isset($_GET[$str])){
1061 if(session::is_set('maxC')){
1062 $b= session::get('maxC');
1063 $q= "";
1064 for ($m=0;$m<strlen($b);$m++) {
1065 $q.= $b[$m++];
1066 }
1067 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1068 }
1069 }
1070 }
1071 }
1074 function &get_userinfo()
1075 {
1076 global $ui;
1078 return $ui;
1079 }
1082 function &get_smarty()
1083 {
1084 global $smarty;
1086 return $smarty;
1087 }
1090 function convert_department_dn($dn)
1091 {
1092 $dep= "";
1094 /* Build a sub-directory style list of the tree level
1095 specified in $dn */
1096 foreach (split(',', $dn) as $rdn){
1098 /* We're only interested in organizational units... */
1099 if (substr($rdn,0,3) == 'ou='){
1100 $dep= substr($rdn,3)."/$dep";
1101 }
1103 /* ... and location objects */
1104 if (substr($rdn,0,2) == 'l='){
1105 $dep= substr($rdn,2)."/$dep";
1106 }
1107 }
1109 /* Return and remove accidently trailing slashes */
1110 return rtrim($dep, "/");
1111 }
1114 /* Strip off the last sub department part of a '/level1/level2/.../'
1115 * style value. It removes the trailing '/', too. */
1116 function get_sub_department($value)
1117 {
1118 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1119 }
1122 function get_ou($name)
1123 {
1124 global $config;
1126 $map = array(
1127 "ogroupou" => "ou=groups,",
1128 "applicationou" => "ou=apps,",
1129 "systemsou" => "ou=systems,",
1130 "serverou" => "ou=servers,ou=systems,",
1131 "terminalou" => "ou=terminals,ou=systems,",
1132 "workstationou" => "ou=workstations,ou=systems,",
1133 "printerou" => "ou=printers,ou=systems,",
1134 "phoneou" => "ou=phones,ou=systems,",
1135 "componentou" => "ou=netdevices,ou=systems,",
1136 "blocklistou" => "ou=gofax,ou=systems,",
1137 "incomingou" => "ou=incoming,",
1138 "aclroleou" => "ou=aclroles,",
1139 "macroou" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1140 "conferenceou" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1142 "faiou" => "ou=fai,ou=configs,ou=systems,",
1143 "faiscriptou" => "ou=scripts,",
1144 "faihookou" => "ou=hooks,",
1145 "faitemplateou" => "ou=templates,",
1146 "faivariableou" => "ou=variables,",
1147 "faiprofileou" => "ou=profiles,",
1148 "faipackageou" => "ou=packages,",
1149 "faipartitionou"=> "ou=disk,",
1151 "deviceou" => "ou=devices,",
1152 "mimetypeou" => "ou=mime,");
1154 /* Preset ou... */
1155 if (isset($config->current[$name])){
1156 $ou= $config->current[$name];
1157 } elseif (isset($map[$name])) {
1158 $ou = $map[$name];
1159 return($ou);
1160 } else {
1161 trigger_error("No department mapping found for type ".$name);
1162 return "";
1163 }
1166 if ($ou != ""){
1167 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1168 return @LDAP::convert("ou=$ou,");
1169 } else {
1170 return @LDAP::convert("$ou,");
1171 }
1172 } else {
1173 return "";
1174 }
1175 }
1178 function get_people_ou()
1179 {
1180 return (get_ou("PEOPLE"));
1181 }
1184 function get_groups_ou()
1185 {
1186 return (get_ou("GROUPS"));
1187 }
1190 function get_winstations_ou()
1191 {
1192 return (get_ou("WINSTATIONS"));
1193 }
1196 function get_base_from_people($dn)
1197 {
1198 global $config;
1200 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1201 $base= preg_replace($pattern, '', $dn);
1203 /* Set to base, if we're not on a correct subtree */
1204 if (!isset($config->idepartments[$base])){
1205 $base= $config->current['BASE'];
1206 }
1208 return ($base);
1209 }
1212 function strict_uid_mode()
1213 {
1214 return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1215 }
1218 function get_uid_regexp()
1219 {
1220 /* STRICT adds spaces and case insenstivity to the uid check.
1221 This is dangerous and should not be used. */
1222 if (strict_uid_mode()){
1223 return "^[a-z0-9_-]+$";
1224 } else {
1225 return "^[a-zA-Z0-9 _.-]+$";
1226 }
1227 }
1230 function print_red()
1231 {
1232 trigger_error("Use of obsolete print_red");
1233 /* Check number of arguments */
1234 if (func_num_args() < 1){
1235 return;
1236 }
1238 /* Get arguments, save string */
1239 $array = func_get_args();
1240 $string= $array[0];
1242 /* Step through arguments */
1243 for ($i= 1; $i<count($array); $i++){
1244 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1245 }
1247 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1248 the other case... */
1249 if($string !== NULL){
1250 if (preg_match("/"._("LDAP error:")."/", $string)){
1251 $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.");
1252 } else {
1253 if (!preg_match('/[.!?]$/', $string)){
1254 $string.= ".";
1255 }
1256 $string= preg_replace('/<br>/', ' ', $string);
1257 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1258 $addmsg = "";
1259 }
1260 if(empty($addmsg)){
1261 $addmsg = _("Error");
1262 }
1263 msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1264 return;
1265 }else{
1266 return;
1267 }
1269 }
1272 function gen_locked_message($user, $dn)
1273 {
1274 global $plug, $config;
1276 session::set('dn', $dn);
1277 $remove= false;
1279 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1280 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1282 $LOCK_VARS_USED = array();
1283 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1285 foreach($LOCK_VARS_TO_USE as $name){
1287 if(empty($name)){
1288 continue;
1289 }
1291 foreach($_POST as $Pname => $Pvalue){
1292 if(preg_match($name,$Pname)){
1293 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1294 }
1295 }
1297 foreach($_GET as $Pname => $Pvalue){
1298 if(preg_match($name,$Pname)){
1299 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1300 }
1301 }
1302 }
1303 session::set('LOCK_VARS_TO_USE',array());
1304 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1305 }
1307 /* Prepare and show template */
1308 $smarty= get_smarty();
1310 if(is_array($dn)){
1311 $msg = "<pre>";
1312 foreach($dn as $sub_dn){
1313 $msg .= "\n".$sub_dn.", ";
1314 }
1315 $msg = preg_replace("/, $/","</pre>",$msg);
1316 }else{
1317 $msg = $dn;
1318 }
1320 $smarty->assign ("dn", $msg);
1321 if ($remove){
1322 $smarty->assign ("action", _("Continue anyway"));
1323 } else {
1324 $smarty->assign ("action", _("Edit anyway"));
1325 }
1326 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1328 return ($smarty->fetch (get_template_path('islocked.tpl')));
1329 }
1332 function to_string ($value)
1333 {
1334 /* If this is an array, generate a text blob */
1335 if (is_array($value)){
1336 $ret= "";
1337 foreach ($value as $line){
1338 $ret.= $line."<br>\n";
1339 }
1340 return ($ret);
1341 } else {
1342 return ($value);
1343 }
1344 }
1347 function get_printer_list()
1348 {
1349 global $config;
1350 $res = array();
1351 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1352 foreach($data as $attrs ){
1353 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1354 }
1355 return $res;
1356 }
1359 function show_errors($message)
1360 {
1361 $complete= "";
1363 /* Assemble the message array to a plain string */
1364 foreach ($message as $error){
1365 if ($complete == ""){
1366 $complete= $error;
1367 } else {
1368 $complete= "$error<br>$complete";
1369 }
1370 }
1372 /* Fill ERROR variable with nice error dialog */
1373 msg_dialog::display(_("Error"), $complete, ERROR_DIALOG);
1374 }
1377 function show_ldap_error($message, $addon= "")
1378 {
1379 if (!preg_match("/Success/i", $message)){
1380 if ($addon == ""){
1381 msg_dialog::display(_("LDAP error:"), $message, ERROR_DIALOG);
1382 } else {
1383 if(!preg_match("/No such object/i",$message)){
1384 msg_dialog::display(_("LDAP error"), sprintf(_("Plugin '%s':%s"),"<i>".$addon."</i>", "<br><br>$message"),ERROR_DIALOG);
1385 }
1386 }
1387 return TRUE;
1388 } else {
1389 return FALSE;
1390 }
1391 }
1394 function rewrite($s)
1395 {
1396 global $REWRITE;
1398 foreach ($REWRITE as $key => $val){
1399 $s= preg_replace("/$key/", "$val", $s);
1400 }
1402 return ($s);
1403 }
1406 function dn2base($dn)
1407 {
1408 global $config;
1410 if (get_people_ou() != ""){
1411 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1412 }
1413 if (get_groups_ou() != ""){
1414 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1415 }
1416 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1418 return ($base);
1419 }
1423 function check_command($cmdline)
1424 {
1425 $cmd= preg_replace("/ .*$/", "", $cmdline);
1427 /* Check if command exists in filesystem */
1428 if (!file_exists($cmd)){
1429 return (FALSE);
1430 }
1432 /* Check if command is executable */
1433 if (!is_executable($cmd)){
1434 return (FALSE);
1435 }
1437 return (TRUE);
1438 }
1441 function print_header($image, $headline, $info= "")
1442 {
1443 $display= "<div class=\"plugtop\">\n";
1444 $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";
1445 $display.= "</div>\n";
1447 if ($info != ""){
1448 $display.= "<div class=\"pluginfo\">\n";
1449 $display.= "$info";
1450 $display.= "</div>\n";
1451 } else {
1452 $display.= "<div style=\"height:5px;\">\n";
1453 $display.= " ";
1454 $display.= "</div>\n";
1455 }
1456 return ($display);
1457 }
1460 function range_selector($dcnt,$start,$range=25,$post_var=false)
1461 {
1463 /* Entries shown left and right from the selected entry */
1464 $max_entries= 10;
1466 /* Initialize and take care that max_entries is even */
1467 $output="";
1468 if ($max_entries & 1){
1469 $max_entries++;
1470 }
1472 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1473 $range= $_POST[$post_var];
1474 }
1476 /* Prevent output to start or end out of range */
1477 if ($start < 0 ){
1478 $start= 0 ;
1479 }
1480 if ($start >= $dcnt){
1481 $start= $range * (int)(($dcnt / $range) + 0.5);
1482 }
1484 $numpages= (($dcnt / $range));
1485 if(((int)($numpages))!=($numpages)){
1486 $numpages = (int)$numpages + 1;
1487 }
1488 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1489 return ("");
1490 }
1491 $ppage= (int)(($start / $range) + 0.5);
1494 /* Align selected page to +/- max_entries/2 */
1495 $begin= $ppage - $max_entries/2;
1496 $end= $ppage + $max_entries/2;
1498 /* Adjust begin/end, so that the selected value is somewhere in
1499 the middle and the size is max_entries if possible */
1500 if ($begin < 0){
1501 $end-= $begin + 1;
1502 $begin= 0;
1503 }
1504 if ($end > $numpages) {
1505 $end= $numpages;
1506 }
1507 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1508 $begin= $end - $max_entries;
1509 }
1511 if($post_var){
1512 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1513 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1514 }else{
1515 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1516 }
1518 /* Draw decrement */
1519 if ($start > 0 ) {
1520 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1521 (($start-$range))."\">".
1522 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1523 }
1525 /* Draw pages */
1526 for ($i= $begin; $i < $end; $i++) {
1527 if ($ppage == $i){
1528 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1529 validate($_GET['plug'])."&start=".
1530 ($i*$range)."\"> ".($i+1)." </a>";
1531 } else {
1532 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1533 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1534 }
1535 }
1537 /* Draw increment */
1538 if($start < ($dcnt-$range)) {
1539 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1540 (($start+($range)))."\">".
1541 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1542 }
1544 if(($post_var)&&($numpages)){
1545 $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()'>";
1546 foreach(array(20,50,100,200,"all") as $num){
1547 if($num == "all"){
1548 $var = 10000;
1549 }else{
1550 $var = $num;
1551 }
1552 if($var == $range){
1553 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1554 }else{
1555 $output.="\n<option value='".$var."'>".$num."</option>";
1556 }
1557 }
1558 $output.= "</select></td></tr></table></div>";
1559 }else{
1560 $output.= "</div>";
1561 }
1563 return($output);
1564 }
1567 function apply_filter()
1568 {
1569 $apply= "";
1571 $apply= ''.
1572 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1573 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1575 return ($apply);
1576 }
1579 function back_to_main()
1580 {
1581 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1582 _("Back").'"></p><input type="hidden" name="ignore">';
1584 return ($string);
1585 }
1588 function normalize_netmask($netmask)
1589 {
1590 /* Check for notation of netmask */
1591 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1592 $num= (int)($netmask);
1593 $netmask= "";
1595 for ($byte= 0; $byte<4; $byte++){
1596 $result=0;
1598 for ($i= 7; $i>=0; $i--){
1599 if ($num-- > 0){
1600 $result+= pow(2,$i);
1601 }
1602 }
1604 $netmask.= $result.".";
1605 }
1607 return (preg_replace('/\.$/', '', $netmask));
1608 }
1610 return ($netmask);
1611 }
1614 function netmask_to_bits($netmask)
1615 {
1616 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1617 $res= 0;
1619 for ($n= 0; $n<4; $n++){
1620 $start= 255;
1621 $name= "nm$n";
1623 for ($i= 0; $i<8; $i++){
1624 if ($start == (int)($$name)){
1625 $res+= 8 - $i;
1626 break;
1627 }
1628 $start-= pow(2,$i);
1629 }
1630 }
1632 return ($res);
1633 }
1636 function recurse($rule, $variables)
1637 {
1638 $result= array();
1640 if (!count($variables)){
1641 return array($rule);
1642 }
1644 reset($variables);
1645 $key= key($variables);
1646 $val= current($variables);
1647 unset ($variables[$key]);
1649 foreach($val as $possibility){
1650 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1651 $result= array_merge($result, recurse($nrule, $variables));
1652 }
1654 return ($result);
1655 }
1658 function expand_id($rule, $attributes)
1659 {
1660 /* Check for id rule */
1661 if(preg_match('/^id(:|#)\d+$/',$rule)){
1662 return (array("\{$rule}"));
1663 }
1665 /* Check for clean attribute */
1666 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1667 $rule= preg_replace('/^%/', '', $rule);
1668 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1669 return (array($val));
1670 }
1672 /* Check for attribute with parameters */
1673 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1674 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1675 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1676 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1677 $start= preg_replace ('/-.*$/', '', $param);
1678 $stop = preg_replace ('/^[^-]+-/', '', $param);
1680 /* Assemble results */
1681 $result= array();
1682 for ($i= $start; $i<= $stop; $i++){
1683 $result[]= substr($val, 0, $i);
1684 }
1685 return ($result);
1686 }
1688 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1689 return (array($rule));
1690 }
1693 function gen_uids($rule, $attributes)
1694 {
1695 global $config;
1697 /* Search for keys and fill the variables array with all
1698 possible values for that key. */
1699 $part= "";
1700 $trigger= false;
1701 $stripped= "";
1702 $variables= array();
1704 for ($pos= 0; $pos < strlen($rule); $pos++){
1706 if ($rule[$pos] == "{" ){
1707 $trigger= true;
1708 $part= "";
1709 continue;
1710 }
1712 if ($rule[$pos] == "}" ){
1713 $variables[$pos]= expand_id($part, $attributes);
1714 $stripped.= "{".$pos."}";
1715 $trigger= false;
1716 continue;
1717 }
1719 if ($trigger){
1720 $part.= $rule[$pos];
1721 } else {
1722 $stripped.= $rule[$pos];
1723 }
1724 }
1726 /* Recurse through all possible combinations */
1727 $proposed= recurse($stripped, $variables);
1729 /* Get list of used ID's */
1730 $used= array();
1731 $ldap= $config->get_ldap_link();
1732 $ldap->cd($config->current['BASE']);
1733 $ldap->search('(uid=*)');
1735 while($attrs= $ldap->fetch()){
1736 $used[]= $attrs['uid'][0];
1737 }
1739 /* Remove used uids and watch out for id tags */
1740 $ret= array();
1741 foreach($proposed as $uid){
1743 /* Check for id tag and modify uid if needed */
1744 if(preg_match('/\{id:\d+}/',$uid)){
1745 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1747 for ($i= 0; $i < pow(10,$size); $i++){
1748 $number= sprintf("%0".$size."d", $i);
1749 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1750 if (!in_array($res, $used)){
1751 $uid= $res;
1752 break;
1753 }
1754 }
1755 }
1757 if(preg_match('/\{id#\d+}/',$uid)){
1758 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1760 while (true){
1761 mt_srand((double) microtime()*1000000);
1762 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1763 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1764 if (!in_array($res, $used)){
1765 $uid= $res;
1766 break;
1767 }
1768 }
1769 }
1771 /* Don't assign used ones */
1772 if (!in_array($uid, $used)){
1773 $ret[]= $uid;
1774 }
1775 }
1777 return(array_unique($ret));
1778 }
1781 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1782 Need to convert... */
1783 function to_byte($value) {
1784 $value= strtolower(trim($value));
1786 if(!is_numeric(substr($value, -1))) {
1788 switch(substr($value, -1)) {
1789 case 'g':
1790 $mult= 1073741824;
1791 break;
1792 case 'm':
1793 $mult= 1048576;
1794 break;
1795 case 'k':
1796 $mult= 1024;
1797 break;
1798 }
1800 return ($mult * (int)substr($value, 0, -1));
1801 } else {
1802 return $value;
1803 }
1804 }
1807 function in_array_ics($value, $items)
1808 {
1809 if (!is_array($items)){
1810 return (FALSE);
1811 }
1813 foreach ($items as $item){
1814 if (strcasecmp($item, $value) == 0) {
1815 return (TRUE);
1816 }
1817 }
1819 return (FALSE);
1820 }
1823 function generate_alphabet($count= 10)
1824 {
1825 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1826 $alphabet= "";
1827 $c= 0;
1829 /* Fill cells with charaters */
1830 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1831 if ($c == 0){
1832 $alphabet.= "<tr>";
1833 }
1835 $ch = mb_substr($characters, $i, 1, "UTF8");
1836 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1837 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1839 if ($c++ == $count){
1840 $alphabet.= "</tr>";
1841 $c= 0;
1842 }
1843 }
1845 /* Fill remaining cells */
1846 while ($c++ <= $count){
1847 $alphabet.= "<td> </td>";
1848 }
1850 return ($alphabet);
1851 }
1854 function validate($string)
1855 {
1856 return (strip_tags(preg_replace('/\0/', '', $string)));
1857 }
1860 function get_gosa_version()
1861 {
1862 global $svn_revision, $svn_path;
1864 /* Extract informations */
1865 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1867 /* Release or development? */
1868 if (preg_match('%/gosa/trunk/%', $svn_path)){
1869 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1870 } else {
1871 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1872 return (sprintf(_("GOsa $release"), $revision));
1873 }
1874 }
1877 function rmdirRecursive($path, $followLinks=false) {
1878 $dir= opendir($path);
1879 while($entry= readdir($dir)) {
1880 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1881 unlink($path."/".$entry);
1882 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1883 rmdirRecursive($path."/".$entry);
1884 }
1885 }
1886 closedir($dir);
1887 return rmdir($path);
1888 }
1891 function scan_directory($path,$sort_desc=false)
1892 {
1893 $ret = false;
1895 /* is this a dir ? */
1896 if(is_dir($path)) {
1898 /* is this path a readable one */
1899 if(is_readable($path)){
1901 /* Get contents and write it into an array */
1902 $ret = array();
1904 $dir = opendir($path);
1906 /* Is this a correct result ?*/
1907 if($dir){
1908 while($fp = readdir($dir))
1909 $ret[]= $fp;
1910 }
1911 }
1912 }
1913 /* Sort array ascending , like scandir */
1914 sort($ret);
1916 /* Sort descending if parameter is sort_desc is set */
1917 if($sort_desc) {
1918 $ret = array_reverse($ret);
1919 }
1921 return($ret);
1922 }
1925 function clean_smarty_compile_dir($directory)
1926 {
1927 global $svn_revision;
1929 if(is_dir($directory) && is_readable($directory)) {
1930 // Set revision filename to REVISION
1931 $revision_file= $directory."/REVISION";
1933 /* Is there a stamp containing the current revision? */
1934 if(!file_exists($revision_file)) {
1935 // create revision file
1936 create_revision($revision_file, $svn_revision);
1937 } else {
1938 # check for "$config->...['CONFIG']/revision" and the
1939 # contents should match the revision number
1940 if(!compare_revision($revision_file, $svn_revision)){
1941 // If revision differs, clean compile directory
1942 foreach(scan_directory($directory) as $file) {
1943 if(($file==".")||($file=="..")) continue;
1944 if( is_file($directory."/".$file) &&
1945 is_writable($directory."/".$file)) {
1946 // delete file
1947 if(!unlink($directory."/".$file)) {
1948 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1949 // This should never be reached
1950 }
1951 } elseif(is_dir($directory."/".$file) &&
1952 is_writable($directory."/".$file)) {
1953 // Just recursively delete it
1954 rmdirRecursive($directory."/".$file);
1955 }
1956 }
1957 // We should now create a fresh revision file
1958 clean_smarty_compile_dir($directory);
1959 } else {
1960 // Revision matches, nothing to do
1961 }
1962 }
1963 } else {
1964 // Smarty compile dir is not accessible
1965 // (Smarty will warn about this)
1966 }
1967 }
1970 function create_revision($revision_file, $revision)
1971 {
1972 $result= false;
1974 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1975 if($fh= fopen($revision_file, "w")) {
1976 if(fwrite($fh, $revision)) {
1977 $result= true;
1978 }
1979 }
1980 fclose($fh);
1981 } else {
1982 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1983 }
1985 return $result;
1986 }
1989 function compare_revision($revision_file, $revision)
1990 {
1991 // false means revision differs
1992 $result= false;
1994 if(file_exists($revision_file) && is_readable($revision_file)) {
1995 // Open file
1996 if($fh= fopen($revision_file, "r")) {
1997 // Compare File contents with current revision
1998 if($revision == fread($fh, filesize($revision_file))) {
1999 $result= true;
2000 }
2001 } else {
2002 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2003 }
2004 // Close file
2005 fclose($fh);
2006 }
2008 return $result;
2009 }
2012 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2013 {
2014 $str = ""; // Our return value will be saved in this var
2016 $color = dechex($percentage+150);
2017 $color2 = dechex(150 - $percentage);
2018 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2020 $progress = (int)(($percentage /100)*$width);
2022 /* Abort printing out percentage, if divs are to small */
2025 /* If theres a better solution for this, use it... */
2026 $str = "
2027 <div style=\" width:".($width)."px;
2028 height:".($height)."px;
2029 background-color:#000000;
2030 padding:1px;\">
2032 <div style=\" width:".($width)."px;
2033 background-color:#$bgcolor;
2034 height:".($height)."px;\">
2036 <div style=\" width:".$progress."px;
2037 height:".$height."px;
2038 background-color:#".$color2.$color2.$color."; \">";
2041 if(($height >10)&&($showvalue)){
2042 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2043 <b>".$percentage."%</b>
2044 </font>";
2045 }
2047 $str.= "</div></div></div>";
2049 return($str);
2050 }
2053 function array_key_ics($ikey, $items)
2054 {
2055 /* Gather keys, make them lowercase */
2056 $tmp= array();
2057 foreach ($items as $key => $value){
2058 $tmp[strtolower($key)]= $key;
2059 }
2061 if (isset($tmp[strtolower($ikey)])){
2062 return($tmp[strtolower($ikey)]);
2063 }
2065 return ("");
2066 }
2069 function array_differs($src, $dst)
2070 {
2071 /* If the count is differing, the arrays differ */
2072 if (count ($src) != count ($dst)){
2073 return (TRUE);
2074 }
2076 /* So the count is the same - lets check the contents */
2077 $differs= FALSE;
2078 foreach($src as $value){
2079 if (!in_array($value, $dst)){
2080 $differs= TRUE;
2081 }
2082 }
2084 return ($differs);
2085 }
2088 function saveFilter($a_filter, $values)
2089 {
2090 if (isset($_POST['regexit'])){
2091 $a_filter["regex"]= $_POST['regexit'];
2093 foreach($values as $type){
2094 if (isset($_POST[$type])) {
2095 $a_filter[$type]= "checked";
2096 } else {
2097 $a_filter[$type]= "";
2098 }
2099 }
2100 }
2102 /* React on alphabet links if needed */
2103 if (isset($_GET['search'])){
2104 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2105 if ($s == "**"){
2106 $s= "*";
2107 }
2108 $a_filter['regex']= $s;
2109 }
2111 return ($a_filter);
2112 }
2115 /* Escape all preg_* relevant characters */
2116 function normalizePreg($input)
2117 {
2118 return (addcslashes($input, '[]()|/.*+-'));
2119 }
2122 /* Escape all LDAP filter relevant characters */
2123 function normalizeLdap($input)
2124 {
2125 return (addcslashes($input, '()|'));
2126 }
2129 /* Resturns the difference between to microtime() results in float */
2130 function get_MicroTimeDiff($start , $stop)
2131 {
2132 $a = split("\ ",$start);
2133 $b = split("\ ",$stop);
2135 $secs = $b[1] - $a[1];
2136 $msecs= $b[0] - $a[0];
2138 $ret = (float) ($secs+ $msecs);
2139 return($ret);
2140 }
2143 function get_base_dir()
2144 {
2145 global $BASE_DIR;
2147 return $BASE_DIR;
2148 }
2151 function obj_is_readable($dn, $object, $attribute)
2152 {
2153 global $ui;
2155 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2156 }
2159 function obj_is_writable($dn, $object, $attribute)
2160 {
2161 global $ui;
2163 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2164 }
2167 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2168 {
2169 /* Initialize variables */
2170 $ret = array("count" => 0); // Set count to 0
2171 $next = true; // if false, then skip next loops and return
2172 $cnt = 0; // Current number of loops
2173 $max = 100; // Just for security, prevent looops
2174 $ldap = NULL; // To check if created result a valid
2175 $keep = ""; // save last failed parse string
2177 /* Check each parsed dn in ldap ? */
2178 if($config!==NULL && $verify_in_ldap){
2179 $ldap = $config->get_ldap_link();
2180 }
2182 /* Lets start */
2183 $called = false;
2184 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2186 $cnt ++;
2187 if(!preg_match("/,/",$dn)){
2188 $next = false;
2189 }
2190 $object = preg_replace("/[,].*$/","",$dn);
2191 $dn = preg_replace("/^[^,]+,/","",$dn);
2193 $called = true;
2195 /* Check if current dn is valid */
2196 if($ldap!==NULL){
2197 $ldap->cd($dn);
2198 $ldap->cat($dn,array("dn"));
2199 if($ldap->count()){
2200 $ret[] = $keep.$object;
2201 $keep = "";
2202 }else{
2203 $keep .= $object.",";
2204 }
2205 }else{
2206 $ret[] = $keep.$object;
2207 $keep = "";
2208 }
2209 }
2211 /* No dn was posted */
2212 if($cnt == 0 && !empty($dn)){
2213 $ret[] = $dn;
2214 }
2216 /* Append the rest */
2217 $test = $keep.$dn;
2218 if($called && !empty($test)){
2219 $ret[] = $keep.$dn;
2220 }
2221 $ret['count'] = count($ret) - 1;
2223 return($ret);
2224 }
2227 function get_base_from_hook($dn, $attrib)
2228 {
2229 global $config;
2231 if (isset($config->current['BASE_HOOK'])){
2233 /* Call hook script - if present */
2234 $command= $config->current['BASE_HOOK'];
2236 if ($command != ""){
2237 $command.= " '".LDAP::fix($dn)."' $attrib";
2238 if (check_command($command)){
2239 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2240 exec($command, $output);
2241 if (preg_match("/^[0-9]+$/", $output[0])){
2242 return ($output[0]);
2243 } else {
2244 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2245 return ($config->current['UIDBASE']);
2246 }
2247 } else {
2248 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2249 return ($config->current['UIDBASE']);
2250 }
2252 } else {
2254 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2255 return ($config->current['UIDBASE']);
2257 }
2258 }
2259 }
2262 function check_schema_version($class, $version)
2263 {
2264 return preg_match("/\(v$version\)/", $class['DESC']);
2265 }
2268 function check_schema($cfg,$rfc2307bis = FALSE)
2269 {
2270 $messages= array();
2272 /* Get objectclasses */
2273 $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2274 $objectclasses = $ldap->get_objectclasses();
2275 if(count($objectclasses) == 0){
2276 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2277 }
2279 /* This is the default block used for each entry.
2280 * to avoid unset indexes.
2281 */
2282 $def_check = array("REQUIRED_VERSION" => "0",
2283 "SCHEMA_FILES" => array(),
2284 "CLASSES_REQUIRED" => array(),
2285 "STATUS" => FALSE,
2286 "IS_MUST_HAVE" => FALSE,
2287 "MSG" => "",
2288 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2290 /* The gosa base schema */
2291 $checks['gosaObject'] = $def_check;
2292 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2293 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2294 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2295 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2297 /* GOsa Account class */
2298 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2299 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2300 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2301 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2302 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2304 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2305 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2306 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2307 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2308 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2309 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2311 /* Some other checks */
2312 foreach(array(
2313 "gosaCacheEntry" => array("version" => "2.4"),
2314 "gosaDepartment" => array("version" => "2.4"),
2315 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2316 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2317 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2318 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2319 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2320 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2321 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2322 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2323 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2324 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2325 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2326 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2327 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2328 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2329 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2330 "goLdapServer" => array("version" => "2.4"),
2331 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2332 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2333 "goKrbServer" => array("version" => "2.4"),
2334 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2335 ) as $name => $values){
2337 $checks[$name] = $def_check;
2338 if(isset($values['version'])){
2339 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2340 }
2341 if(isset($values['file'])){
2342 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2343 }
2344 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2345 }
2346 foreach($checks as $name => $value){
2347 foreach($value['CLASSES_REQUIRED'] as $class){
2349 if(!isset($objectclasses[$name])){
2350 $checks[$name]['STATUS'] = FALSE;
2351 if($value['IS_MUST_HAVE']){
2352 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2353 }else{
2354 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2355 }
2356 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2357 $checks[$name]['STATUS'] = FALSE;
2359 if($value['IS_MUST_HAVE']){
2360 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2361 }else{
2362 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2363 }
2364 }else{
2365 $checks[$name]['STATUS'] = TRUE;
2366 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2367 }
2368 }
2369 }
2371 $tmp = $objectclasses;
2373 /* The gosa base schema */
2374 $checks['posixGroup'] = $def_check;
2375 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2376 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2377 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2378 $checks['posixGroup']['STATUS'] = TRUE;
2379 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2380 $checks['posixGroup']['MSG'] = "";
2381 $checks['posixGroup']['INFO'] = "";
2383 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2384 if(isset($tmp['posixGroup'])){
2386 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2387 $checks['posixGroup']['STATUS'] = FALSE;
2388 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2389 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2390 }
2391 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2392 $checks['posixGroup']['STATUS'] = FALSE;
2393 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2394 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2395 }
2396 }
2398 return($checks);
2399 }
2402 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2403 {
2404 $tmp = array(
2405 "de_DE" => "German",
2406 "fr_FR" => "French",
2407 "it_IT" => "Italian",
2408 "es_ES" => "Spanish",
2409 "en_US" => "English",
2410 "nl_NL" => "Dutch",
2411 "pl_PL" => "Polish",
2412 "sv_SE" => "Swedish",
2413 "zh_CN" => "Chinese",
2414 "ru_RU" => "Russian");
2416 $tmp2= array(
2417 "de_DE" => _("German"),
2418 "fr_FR" => _("French"),
2419 "it_IT" => _("Italian"),
2420 "es_ES" => _("Spanish"),
2421 "en_US" => _("English"),
2422 "nl_NL" => _("Dutch"),
2423 "pl_PL" => _("Polish"),
2424 "sv_SE" => _("Swedish"),
2425 "zh_CN" => _("Chinese"),
2426 "ru_RU" => _("Russian"));
2428 $ret = array();
2429 if($languages_in_own_language){
2431 $old_lang = setlocale(LC_ALL, 0);
2432 foreach($tmp as $key => $name){
2433 $lang = $key.".UTF-8";
2434 setlocale(LC_ALL, $lang);
2435 if($strip_region_tag){
2436 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2437 }else{
2438 $ret[$key] = _($name)." (".$tmp2[$key].")";
2439 }
2440 }
2441 setlocale(LC_ALL, $old_lang);
2442 }else{
2443 foreach($tmp as $key => $name){
2444 if($strip_region_tag){
2445 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2446 }else{
2447 $ret[$key] = _($name);
2448 }
2449 }
2450 }
2451 return($ret);
2452 }
2455 /* Returns contents of the given POST variable and check magic quotes settings */
2456 function get_post($name)
2457 {
2458 if(!isset($_POST[$name])){
2459 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2460 return(FALSE);
2461 }
2462 if(get_magic_quotes_gpc()){
2463 return(stripcslashes($_POST[$name]));
2464 }else{
2465 return($_POST[$name]);
2466 }
2467 }
2470 /* Return class name in correct case */
2471 function get_correct_class_name($cls)
2472 {
2473 global $class_mapping;
2474 if(isset($class_mapping) && is_array($class_mapping)){
2475 foreach($class_mapping as $class => $file){
2476 if(preg_match("/^".$cls."$/i",$class)){
2477 return($class);
2478 }
2479 }
2480 }
2481 return(FALSE);
2482 }
2485 // change_password, changes the Password, of the given dn
2486 function change_password ($dn, $password, $mode=0, $hash= "")
2487 {
2488 global $config;
2489 $newpass= "";
2491 /* Convert to lower. Methods are lowercase */
2492 $hash= strtolower($hash);
2494 // Get all available encryption Methods
2496 // NON STATIC CALL :)
2497 $tmp = new passwordMethod(session::get('config'));
2498 $available = $tmp->get_available_methods();
2500 // read current password entry for $dn, to detect the encryption Method
2501 $ldap = $config->get_ldap_link();
2502 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2503 $attrs = $ldap->fetch ();
2505 // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2506 if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2507 $deactivated = TRUE;
2508 }else{
2509 $deactivated = FALSE;
2510 }
2512 /* Is ensure that clear passwords will stay clear */
2513 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2514 $hash = "clear";
2515 }
2517 // Detect the encryption Method
2518 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2520 /* Check for supported algorithm */
2521 mt_srand((double) microtime()*1000000);
2523 /* Extract used hash */
2524 if ($hash == ""){
2525 $hash= strtolower($matches[1]);
2526 }
2528 $test = new $available[$hash]($config);
2530 } else {
2531 // User MD5 by default
2532 $hash= "md5";
2533 $test = new $available['md5']($config);
2534 }
2536 /* Feed password backends with information */
2537 $test->dn= $dn;
2538 $test->attrs= $attrs;
2539 $newpass= $test->generate_hash($password);
2541 // Update shadow timestamp?
2542 if (isset($attrs["shadowLastChange"][0])){
2543 $shadow= (int)(date("U") / 86400);
2544 } else {
2545 $shadow= 0;
2546 }
2548 // Write back modified entry
2549 $ldap->cd($dn);
2550 $attrs= array();
2552 // Not for groups
2553 if ($mode == 0){
2555 if ($shadow != 0){
2556 $attrs['shadowLastChange']= $shadow;
2557 }
2559 // Create SMB Password
2560 $attrs= generate_smb_nt_hash($password);
2561 }
2563 /* Readd ! if user was deactivated */
2564 if($deactivated){
2565 $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2566 }
2568 $attrs['userPassword']= array();
2569 $attrs['userPassword']= $newpass;
2571 $ldap->modify($attrs);
2573 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2575 if ($ldap->error != 'Success') {
2576 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);
2577 } else {
2579 /* Run backend method for change/create */
2580 $test->set_password($password);
2582 /* Find postmodify entries for this class */
2583 $command= $config->search("password", "POSTMODIFY",array('menu'));
2585 if ($command != ""){
2586 /* Walk through attribute list */
2587 $command= preg_replace("/%userPassword/", $password, $command);
2588 $command= preg_replace("/%dn/", $dn, $command);
2590 if (check_command($command)){
2591 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2592 exec($command);
2593 } else {
2594 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2595 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2596 }
2597 }
2598 }
2599 }
2602 // Return something like array['sambaLMPassword']= "lalla..."
2603 function generate_smb_nt_hash($password)
2604 {
2605 global $config;
2607 # Try to use gosa-si?
2608 if (isset($config->current['GOSA_SI'])){
2609 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2610 $hash= $res['XML']['HASH'];
2611 } else {
2612 $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2613 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2615 exec($tmp, $ar);
2616 flush();
2617 reset($ar);
2618 $hash= current($ar);
2619 }
2621 if ($hash == "") {
2622 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2623 return ("");
2624 }
2626 list($lm,$nt)= split (":", trim($hash));
2628 if ($config->current['SAMBAVERSION'] == 3) {
2629 $attrs['sambaLMPassword']= $lm;
2630 $attrs['sambaNTPassword']= $nt;
2631 $attrs['sambaPwdLastSet']= date('U');
2632 $attrs['sambaBadPasswordCount']= "0";
2633 $attrs['sambaBadPasswordTime']= "0";
2634 } else {
2635 $attrs['lmPassword']= $lm;
2636 $attrs['ntPassword']= $nt;
2637 $attrs['pwdLastSet']= date('U');
2638 }
2639 return($attrs);
2640 }
2643 function crypt_single($string,$enc_type )
2644 {
2645 return( passwordMethod::crypt_single_str($string,$enc_type));
2646 }
2649 function getEntryCSN($dn)
2650 {
2651 global $config;
2652 if(empty($dn) || !is_object($config)){
2653 return("");
2654 }
2656 /* Get attribute that we should use as serial number */
2657 if(isset($config->current['UNIQ_IDENTIFIER'])){
2658 $attr = $config->current['UNIQ_IDENTIFIER'];
2659 }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2660 $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2661 }
2662 if(!empty($attr)){
2663 $ldap = $config->get_ldap_link();
2664 $ldap->cat($dn,array($attr));
2665 $csn = $ldap->fetch();
2666 if(isset($csn[$attr][0])){
2667 return($csn[$attr][0]);
2668 }
2669 }
2670 return("");
2671 }
2674 /* Add a given objectClass to an attrs entry */
2675 function add_objectClass($classes, &$attrs)
2676 {
2677 if (is_array($classes)){
2678 $list= $classes;
2679 } else {
2680 $list= array($classes);
2681 }
2683 foreach ($list as $class){
2684 $attrs['objectClass'][]= $class;
2685 }
2686 }
2689 /* Removes a given objectClass from the attrs entry */
2690 function remove_objectClass($classes, &$attrs)
2691 {
2692 if (isset($attrs['objectClass'])){
2693 /* Array? */
2694 if (is_array($classes)){
2695 $list= $classes;
2696 } else {
2697 $list= array($classes);
2698 }
2700 $tmp= array();
2701 foreach ($attrs['objectClass'] as $oc) {
2702 foreach ($list as $class){
2703 if ($oc != $class){
2704 $tmp[]= $oc;
2705 }
2706 }
2707 }
2708 $attrs['objectClass']= $tmp;
2709 }
2710 }
2712 /*! \brief Initialize a file download with given content, name and data type.
2713 * @param data String The content to send.
2714 * @param name String The name of the file.
2715 * @param type String The content identifier, default value is "application/octet-stream";
2716 */
2717 function send_binary_content($data,$name,$type = "application/octet-stream")
2718 {
2719 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2720 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2721 header("Cache-Control: no-cache");
2722 header("Pragma: no-cache");
2723 header("Cache-Control: post-check=0, pre-check=0");
2724 header("Content-type: ".$type."");
2726 /* force download dialog */
2727 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2728 header('Content-Disposition: filename="'.$name.'"');
2729 } else {
2730 header('Content-Disposition: attachment; filename="'.$name.'"');
2731 }
2733 echo $data;
2734 exit();
2735 }
2737 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2738 ?>