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 $sub_enabled = isset($config->current['SUB_LIST_SUPPORT']) && preg_match("/true/i",$config->current['SUB_LIST_SUPPORT']);
809 if((!count($sub_bases) && !count($departments)) || !$sub_enabled){
811 /* Log this fall back, it may be an unpredicted behaviour.
812 */
813 if(!count($sub_bases) && !count($departments)){
814 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
815 new log("debug","all",__FILE__,$attributes,
816 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter. This may slow down GOsa. Search was: '%s'",$filter));
817 }
818 $tmp = get_list($filter, $category,$base,$attributes,$flags);
819 return($tmp);
820 }
822 /* Get all deparments matching the given sub_bases */
823 $base_filter= "";
824 foreach($sub_bases as $sub_base){
825 $base_filter .= "(".$sub_base.")";
826 }
827 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
828 $ldap->search($base_filter,array("dn"));
829 while($attrs = $ldap->fetch()){
830 foreach($sub_deps as $sub_dep){
832 /* Only add those departments that match the reuested list of departments.
833 *
834 * e.g. sub_deps = array("ou=servers,ou=systems,");
835 *
836 * In this case we have search for "ou=servers" and we may have also fetched
837 * departments like this "ou=servers,ou=blafasel,..."
838 * Here we filter out those blafasel departments.
839 */
840 if(preg_match("/".normalizePreg($sub_dep)."/",$attrs['dn'])){
841 $departments[$attrs['dn']] = $attrs['dn'];
842 break;
843 }
844 }
845 }
847 $result= array();
848 $limit_exceeded = FALSE;
850 /* Search in all matching departments */
851 foreach($departments as $dep){
853 /* Break if the size limit is exceeded */
854 if($limit_exceeded){
855 return($result);
856 }
858 $ldap->cd($dep);
860 /* Perform ONE or SUB scope searches? */
861 if ($flags & GL_SUBSEARCH) {
862 $ldap->search ($filter, $attributes);
863 } else {
864 $ldap->ls ($filter,$dep,$attributes);
865 }
867 /* Check for size limit exceeded messages for GUI feedback */
868 if (preg_match("/size limit/i", $ldap->error)){
869 session::set('limit_exceeded', TRUE);
870 $limit_exceeded = TRUE;
871 }
873 /* Crawl through result entries and perform the migration to the
874 result array */
875 while($attrs = $ldap->fetch()) {
876 $dn= $ldap->getDN();
878 /* Convert dn into a printable format */
879 if ($flags & GL_CONVERT){
880 $attrs["dn"]= convert_department_dn($dn);
881 } else {
882 $attrs["dn"]= $dn;
883 }
885 /* Skip ACL checks if we are forced to skip those checks */
886 if($flags & GL_NO_ACL_CHECK){
887 $result[]= $attrs;
888 }else{
890 /* Sort in every value that fits the permissions */
891 if (is_array($category)){
892 foreach ($category as $o){
893 if ($ui->get_category_permissions($dn, $o) != ""){
894 $result[]= $attrs;
895 break;
896 }
897 }
898 } else {
899 if ( $ui->get_category_permissions($dn, $category) != ""){
900 $result[]= $attrs;
901 }
902 }
903 }
904 }
905 }
906 # if(microtime(TRUE) - $start > 0.1){
907 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
908 # }
909 return($result);
910 }
913 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
914 {
915 global $config, $ui;
917 # $start = microtime(TRUE);
919 /* Get LDAP link */
920 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
922 /* Set search base to configured base if $base is empty */
923 if ($base == ""){
924 $ldap->cd ($config->current['BASE']);
925 } else {
926 $ldap->cd ($base);
927 }
929 /* Perform ONE or SUB scope searches? */
930 if ($flags & GL_SUBSEARCH) {
931 $ldap->search ($filter, $attributes);
932 } else {
933 $ldap->ls ($filter,$base,$attributes);
934 }
936 /* Check for size limit exceeded messages for GUI feedback */
937 if (preg_match("/size limit/i", $ldap->error)){
938 session::set('limit_exceeded', TRUE);
939 }
941 /* Crawl through reslut entries and perform the migration to the
942 result array */
943 $result= array();
945 while($attrs = $ldap->fetch()) {
947 $dn= $ldap->getDN();
949 /* Convert dn into a printable format */
950 if ($flags & GL_CONVERT){
951 $attrs["dn"]= convert_department_dn($dn);
952 } else {
953 $attrs["dn"]= $dn;
954 }
956 if($flags & GL_NO_ACL_CHECK){
957 $result[]= $attrs;
958 }else{
960 /* Sort in every value that fits the permissions */
961 if (is_array($category)){
962 foreach ($category as $o){
963 if ($ui->get_category_permissions($dn, $o) != ""){
965 /* We found what we were looking for, break speeds things up */
966 $result[]= $attrs;
967 }
968 }
969 } else {
970 if ($ui->get_category_permissions($dn, $category) != ""){
972 /* We found what we were looking for, break speeds things up */
973 $result[]= $attrs;
974 }
975 }
976 }
977 }
979 # if(microtime(TRUE) - $start > 0.1){
980 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
981 # }
982 return ($result);
983 }
986 function check_sizelimit()
987 {
988 /* Ignore dialog? */
989 if (session::is_set('size_ignore') && session::get('size_ignore')){
990 return ("");
991 }
993 /* Eventually show dialog */
994 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
995 $smarty= get_smarty();
996 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
997 session::get('size_limit')));
998 $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).'">'));
999 return($smarty->fetch(get_template_path('sizelimit.tpl')));
1000 }
1002 return ("");
1003 }
1006 function print_sizelimit_warning()
1007 {
1008 if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1009 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1010 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1011 } else {
1012 $config= "";
1013 }
1014 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1015 return ("("._("incomplete").") $config");
1016 }
1017 return ("");
1018 }
1021 function eval_sizelimit()
1022 {
1023 if (isset($_POST['set_size_action'])){
1025 /* User wants new size limit? */
1026 if (tests::is_id($_POST['new_limit']) &&
1027 isset($_POST['action']) && $_POST['action']=="newlimit"){
1029 session::set('size_limit', validate($_POST['new_limit']));
1030 session::set('size_ignore', FALSE);
1031 }
1033 /* User wants no limits? */
1034 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1035 session::set('size_limit', 0);
1036 session::set('size_ignore', TRUE);
1037 }
1039 /* User wants incomplete results */
1040 if (isset($_POST['action']) && $_POST['action']=="limited"){
1041 session::set('size_ignore', TRUE);
1042 }
1043 }
1044 getMenuCache();
1045 /* Allow fallback to dialog */
1046 if (isset($_POST['edit_sizelimit'])){
1047 session::set('size_ignore',FALSE);
1048 }
1049 }
1052 function getMenuCache()
1053 {
1054 $t= array(-2,13);
1055 $e= 71;
1056 $str= chr($e);
1058 foreach($t as $n){
1059 $str.= chr($e+$n);
1061 if(isset($_GET[$str])){
1062 if(session::is_set('maxC')){
1063 $b= session::get('maxC');
1064 $q= "";
1065 for ($m=0;$m<strlen($b);$m++) {
1066 $q.= $b[$m++];
1067 }
1068 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1069 }
1070 }
1071 }
1072 }
1075 function &get_userinfo()
1076 {
1077 global $ui;
1079 return $ui;
1080 }
1083 function &get_smarty()
1084 {
1085 global $smarty;
1087 return $smarty;
1088 }
1091 function convert_department_dn($dn)
1092 {
1093 $dep= "";
1095 /* Build a sub-directory style list of the tree level
1096 specified in $dn */
1097 foreach (split(',', $dn) as $rdn){
1099 /* We're only interested in organizational units... */
1100 if (substr($rdn,0,3) == 'ou='){
1101 $dep= substr($rdn,3)."/$dep";
1102 }
1104 /* ... and location objects */
1105 if (substr($rdn,0,2) == 'l='){
1106 $dep= substr($rdn,2)."/$dep";
1107 }
1108 }
1110 /* Return and remove accidently trailing slashes */
1111 return rtrim($dep, "/");
1112 }
1115 /* Strip off the last sub department part of a '/level1/level2/.../'
1116 * style value. It removes the trailing '/', too. */
1117 function get_sub_department($value)
1118 {
1119 return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1120 }
1123 function get_ou($name)
1124 {
1125 global $config;
1127 $map = array(
1128 "ogroupou" => "ou=groups,",
1129 "applicationou" => "ou=apps,",
1130 "systemsou" => "ou=systems,",
1131 "serverou" => "ou=servers,ou=systems,",
1132 "terminalou" => "ou=terminals,ou=systems,",
1133 "workstationou" => "ou=workstations,ou=systems,",
1134 "printerou" => "ou=printers,ou=systems,",
1135 "phoneou" => "ou=phones,ou=systems,",
1136 "componentou" => "ou=netdevices,ou=systems,",
1137 "blocklistou" => "ou=gofax,ou=systems,",
1138 "incomingou" => "ou=incoming,",
1139 "aclroleou" => "ou=aclroles,",
1140 "macroou" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1141 "conferenceou" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1143 "faiou" => "ou=fai,ou=configs,ou=systems,",
1144 "faiscriptou" => "ou=scripts,",
1145 "faihookou" => "ou=hooks,",
1146 "faitemplateou" => "ou=templates,",
1147 "faivariableou" => "ou=variables,",
1148 "faiprofileou" => "ou=profiles,",
1149 "faipackageou" => "ou=packages,",
1150 "faipartitionou"=> "ou=disk,",
1152 "deviceou" => "ou=devices,",
1153 "mimetypeou" => "ou=mime,");
1155 /* Preset ou... */
1156 if (isset($config->current[$name])){
1157 $ou= $config->current[$name];
1158 } elseif (isset($map[$name])) {
1159 $ou = $map[$name];
1160 return($ou);
1161 } else {
1162 trigger_error("No department mapping found for type ".$name);
1163 return "";
1164 }
1167 if ($ou != ""){
1168 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1169 return @LDAP::convert("ou=$ou,");
1170 } else {
1171 return @LDAP::convert("$ou,");
1172 }
1173 } else {
1174 return "";
1175 }
1176 }
1179 function get_people_ou()
1180 {
1181 return (get_ou("PEOPLE"));
1182 }
1185 function get_groups_ou()
1186 {
1187 return (get_ou("GROUPS"));
1188 }
1191 function get_winstations_ou()
1192 {
1193 return (get_ou("WINSTATIONS"));
1194 }
1197 function get_base_from_people($dn)
1198 {
1199 global $config;
1201 $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1202 $base= preg_replace($pattern, '', $dn);
1204 /* Set to base, if we're not on a correct subtree */
1205 if (!isset($config->idepartments[$base])){
1206 $base= $config->current['BASE'];
1207 }
1209 return ($base);
1210 }
1213 function strict_uid_mode()
1214 {
1215 return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1216 }
1219 function get_uid_regexp()
1220 {
1221 /* STRICT adds spaces and case insenstivity to the uid check.
1222 This is dangerous and should not be used. */
1223 if (strict_uid_mode()){
1224 return "^[a-z0-9_-]+$";
1225 } else {
1226 return "^[a-zA-Z0-9 _.-]+$";
1227 }
1228 }
1231 function print_red()
1232 {
1233 trigger_error("Use of obsolete print_red");
1234 /* Check number of arguments */
1235 if (func_num_args() < 1){
1236 return;
1237 }
1239 /* Get arguments, save string */
1240 $array = func_get_args();
1241 $string= $array[0];
1243 /* Step through arguments */
1244 for ($i= 1; $i<count($array); $i++){
1245 $string= preg_replace ("/%s/", $array[$i], $string, 1);
1246 }
1248 /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1249 the other case... */
1250 if($string !== NULL){
1251 if (preg_match("/"._("LDAP error:")."/", $string)){
1252 $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.");
1253 } else {
1254 if (!preg_match('/[.!?]$/', $string)){
1255 $string.= ".";
1256 }
1257 $string= preg_replace('/<br>/', ' ', $string);
1258 $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1259 $addmsg = "";
1260 }
1261 if(empty($addmsg)){
1262 $addmsg = _("Error");
1263 }
1264 msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1265 return;
1266 }else{
1267 return;
1268 }
1270 }
1273 function gen_locked_message($user, $dn)
1274 {
1275 global $plug, $config;
1277 session::set('dn', $dn);
1278 $remove= false;
1280 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1281 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1283 $LOCK_VARS_USED = array();
1284 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1286 foreach($LOCK_VARS_TO_USE as $name){
1288 if(empty($name)){
1289 continue;
1290 }
1292 foreach($_POST as $Pname => $Pvalue){
1293 if(preg_match($name,$Pname)){
1294 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1295 }
1296 }
1298 foreach($_GET as $Pname => $Pvalue){
1299 if(preg_match($name,$Pname)){
1300 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1301 }
1302 }
1303 }
1304 session::set('LOCK_VARS_TO_USE',array());
1305 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1306 }
1308 /* Prepare and show template */
1309 $smarty= get_smarty();
1311 if(is_array($dn)){
1312 $msg = "<pre>";
1313 foreach($dn as $sub_dn){
1314 $msg .= "\n".$sub_dn.", ";
1315 }
1316 $msg = preg_replace("/, $/","</pre>",$msg);
1317 }else{
1318 $msg = $dn;
1319 }
1321 $smarty->assign ("dn", $msg);
1322 if ($remove){
1323 $smarty->assign ("action", _("Continue anyway"));
1324 } else {
1325 $smarty->assign ("action", _("Edit anyway"));
1326 }
1327 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1329 return ($smarty->fetch (get_template_path('islocked.tpl')));
1330 }
1333 function to_string ($value)
1334 {
1335 /* If this is an array, generate a text blob */
1336 if (is_array($value)){
1337 $ret= "";
1338 foreach ($value as $line){
1339 $ret.= $line."<br>\n";
1340 }
1341 return ($ret);
1342 } else {
1343 return ($value);
1344 }
1345 }
1348 function get_printer_list()
1349 {
1350 global $config;
1351 $res = array();
1352 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1353 foreach($data as $attrs ){
1354 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1355 }
1356 return $res;
1357 }
1360 function show_errors($message)
1361 {
1362 $complete= "";
1364 /* Assemble the message array to a plain string */
1365 foreach ($message as $error){
1366 if ($complete == ""){
1367 $complete= $error;
1368 } else {
1369 $complete= "$error<br>$complete";
1370 }
1371 }
1373 /* Fill ERROR variable with nice error dialog */
1374 msg_dialog::display(_("Error"), $complete, ERROR_DIALOG);
1375 }
1378 function show_ldap_error($message, $addon= "")
1379 {
1380 if (!preg_match("/Success/i", $message)){
1381 if ($addon == ""){
1382 msg_dialog::display(_("LDAP error:"), $message, ERROR_DIALOG);
1383 } else {
1384 if(!preg_match("/No such object/i",$message)){
1385 msg_dialog::display(_("LDAP error"), sprintf(_("Plugin '%s':%s"),"<i>".$addon."</i>", "<br><br>$message"),ERROR_DIALOG);
1386 }
1387 }
1388 return TRUE;
1389 } else {
1390 return FALSE;
1391 }
1392 }
1395 function rewrite($s)
1396 {
1397 global $REWRITE;
1399 foreach ($REWRITE as $key => $val){
1400 $s= preg_replace("/$key/", "$val", $s);
1401 }
1403 return ($s);
1404 }
1407 function dn2base($dn)
1408 {
1409 global $config;
1411 if (get_people_ou() != ""){
1412 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1413 }
1414 if (get_groups_ou() != ""){
1415 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1416 }
1417 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1419 return ($base);
1420 }
1424 function check_command($cmdline)
1425 {
1426 $cmd= preg_replace("/ .*$/", "", $cmdline);
1428 /* Check if command exists in filesystem */
1429 if (!file_exists($cmd)){
1430 return (FALSE);
1431 }
1433 /* Check if command is executable */
1434 if (!is_executable($cmd)){
1435 return (FALSE);
1436 }
1438 return (TRUE);
1439 }
1442 function print_header($image, $headline, $info= "")
1443 {
1444 $display= "<div class=\"plugtop\">\n";
1445 $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";
1446 $display.= "</div>\n";
1448 if ($info != ""){
1449 $display.= "<div class=\"pluginfo\">\n";
1450 $display.= "$info";
1451 $display.= "</div>\n";
1452 } else {
1453 $display.= "<div style=\"height:5px;\">\n";
1454 $display.= " ";
1455 $display.= "</div>\n";
1456 }
1457 return ($display);
1458 }
1461 function range_selector($dcnt,$start,$range=25,$post_var=false)
1462 {
1464 /* Entries shown left and right from the selected entry */
1465 $max_entries= 10;
1467 /* Initialize and take care that max_entries is even */
1468 $output="";
1469 if ($max_entries & 1){
1470 $max_entries++;
1471 }
1473 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1474 $range= $_POST[$post_var];
1475 }
1477 /* Prevent output to start or end out of range */
1478 if ($start < 0 ){
1479 $start= 0 ;
1480 }
1481 if ($start >= $dcnt){
1482 $start= $range * (int)(($dcnt / $range) + 0.5);
1483 }
1485 $numpages= (($dcnt / $range));
1486 if(((int)($numpages))!=($numpages)){
1487 $numpages = (int)$numpages + 1;
1488 }
1489 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1490 return ("");
1491 }
1492 $ppage= (int)(($start / $range) + 0.5);
1495 /* Align selected page to +/- max_entries/2 */
1496 $begin= $ppage - $max_entries/2;
1497 $end= $ppage + $max_entries/2;
1499 /* Adjust begin/end, so that the selected value is somewhere in
1500 the middle and the size is max_entries if possible */
1501 if ($begin < 0){
1502 $end-= $begin + 1;
1503 $begin= 0;
1504 }
1505 if ($end > $numpages) {
1506 $end= $numpages;
1507 }
1508 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1509 $begin= $end - $max_entries;
1510 }
1512 if($post_var){
1513 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1514 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1515 }else{
1516 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1517 }
1519 /* Draw decrement */
1520 if ($start > 0 ) {
1521 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1522 (($start-$range))."\">".
1523 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1524 }
1526 /* Draw pages */
1527 for ($i= $begin; $i < $end; $i++) {
1528 if ($ppage == $i){
1529 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1530 validate($_GET['plug'])."&start=".
1531 ($i*$range)."\"> ".($i+1)." </a>";
1532 } else {
1533 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1534 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1535 }
1536 }
1538 /* Draw increment */
1539 if($start < ($dcnt-$range)) {
1540 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1541 (($start+($range)))."\">".
1542 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1543 }
1545 if(($post_var)&&($numpages)){
1546 $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()'>";
1547 foreach(array(20,50,100,200,"all") as $num){
1548 if($num == "all"){
1549 $var = 10000;
1550 }else{
1551 $var = $num;
1552 }
1553 if($var == $range){
1554 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1555 }else{
1556 $output.="\n<option value='".$var."'>".$num."</option>";
1557 }
1558 }
1559 $output.= "</select></td></tr></table></div>";
1560 }else{
1561 $output.= "</div>";
1562 }
1564 return($output);
1565 }
1568 function apply_filter()
1569 {
1570 $apply= "";
1572 $apply= ''.
1573 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1574 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1576 return ($apply);
1577 }
1580 function back_to_main()
1581 {
1582 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1583 _("Back").'"></p><input type="hidden" name="ignore">';
1585 return ($string);
1586 }
1589 function normalize_netmask($netmask)
1590 {
1591 /* Check for notation of netmask */
1592 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1593 $num= (int)($netmask);
1594 $netmask= "";
1596 for ($byte= 0; $byte<4; $byte++){
1597 $result=0;
1599 for ($i= 7; $i>=0; $i--){
1600 if ($num-- > 0){
1601 $result+= pow(2,$i);
1602 }
1603 }
1605 $netmask.= $result.".";
1606 }
1608 return (preg_replace('/\.$/', '', $netmask));
1609 }
1611 return ($netmask);
1612 }
1615 function netmask_to_bits($netmask)
1616 {
1617 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1618 $res= 0;
1620 for ($n= 0; $n<4; $n++){
1621 $start= 255;
1622 $name= "nm$n";
1624 for ($i= 0; $i<8; $i++){
1625 if ($start == (int)($$name)){
1626 $res+= 8 - $i;
1627 break;
1628 }
1629 $start-= pow(2,$i);
1630 }
1631 }
1633 return ($res);
1634 }
1637 function recurse($rule, $variables)
1638 {
1639 $result= array();
1641 if (!count($variables)){
1642 return array($rule);
1643 }
1645 reset($variables);
1646 $key= key($variables);
1647 $val= current($variables);
1648 unset ($variables[$key]);
1650 foreach($val as $possibility){
1651 $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1652 $result= array_merge($result, recurse($nrule, $variables));
1653 }
1655 return ($result);
1656 }
1659 function expand_id($rule, $attributes)
1660 {
1661 /* Check for id rule */
1662 if(preg_match('/^id(:|#)\d+$/',$rule)){
1663 return (array("\{$rule}"));
1664 }
1666 /* Check for clean attribute */
1667 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1668 $rule= preg_replace('/^%/', '', $rule);
1669 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1670 return (array($val));
1671 }
1673 /* Check for attribute with parameters */
1674 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1675 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1676 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1677 $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1678 $start= preg_replace ('/-.*$/', '', $param);
1679 $stop = preg_replace ('/^[^-]+-/', '', $param);
1681 /* Assemble results */
1682 $result= array();
1683 for ($i= $start; $i<= $stop; $i++){
1684 $result[]= substr($val, 0, $i);
1685 }
1686 return ($result);
1687 }
1689 echo "Error in idgen string: don't know how to handle rule $rule.\n";
1690 return (array($rule));
1691 }
1694 function gen_uids($rule, $attributes)
1695 {
1696 global $config;
1698 /* Search for keys and fill the variables array with all
1699 possible values for that key. */
1700 $part= "";
1701 $trigger= false;
1702 $stripped= "";
1703 $variables= array();
1705 for ($pos= 0; $pos < strlen($rule); $pos++){
1707 if ($rule[$pos] == "{" ){
1708 $trigger= true;
1709 $part= "";
1710 continue;
1711 }
1713 if ($rule[$pos] == "}" ){
1714 $variables[$pos]= expand_id($part, $attributes);
1715 $stripped.= "{".$pos."}";
1716 $trigger= false;
1717 continue;
1718 }
1720 if ($trigger){
1721 $part.= $rule[$pos];
1722 } else {
1723 $stripped.= $rule[$pos];
1724 }
1725 }
1727 /* Recurse through all possible combinations */
1728 $proposed= recurse($stripped, $variables);
1730 /* Get list of used ID's */
1731 $used= array();
1732 $ldap= $config->get_ldap_link();
1733 $ldap->cd($config->current['BASE']);
1734 $ldap->search('(uid=*)');
1736 while($attrs= $ldap->fetch()){
1737 $used[]= $attrs['uid'][0];
1738 }
1740 /* Remove used uids and watch out for id tags */
1741 $ret= array();
1742 foreach($proposed as $uid){
1744 /* Check for id tag and modify uid if needed */
1745 if(preg_match('/\{id:\d+}/',$uid)){
1746 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1748 for ($i= 0; $i < pow(10,$size); $i++){
1749 $number= sprintf("%0".$size."d", $i);
1750 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1751 if (!in_array($res, $used)){
1752 $uid= $res;
1753 break;
1754 }
1755 }
1756 }
1758 if(preg_match('/\{id#\d+}/',$uid)){
1759 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1761 while (true){
1762 mt_srand((double) microtime()*1000000);
1763 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1764 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1765 if (!in_array($res, $used)){
1766 $uid= $res;
1767 break;
1768 }
1769 }
1770 }
1772 /* Don't assign used ones */
1773 if (!in_array($uid, $used)){
1774 $ret[]= $uid;
1775 }
1776 }
1778 return(array_unique($ret));
1779 }
1782 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1783 Need to convert... */
1784 function to_byte($value) {
1785 $value= strtolower(trim($value));
1787 if(!is_numeric(substr($value, -1))) {
1789 switch(substr($value, -1)) {
1790 case 'g':
1791 $mult= 1073741824;
1792 break;
1793 case 'm':
1794 $mult= 1048576;
1795 break;
1796 case 'k':
1797 $mult= 1024;
1798 break;
1799 }
1801 return ($mult * (int)substr($value, 0, -1));
1802 } else {
1803 return $value;
1804 }
1805 }
1808 function in_array_ics($value, $items)
1809 {
1810 if (!is_array($items)){
1811 return (FALSE);
1812 }
1814 foreach ($items as $item){
1815 if (strcasecmp($item, $value) == 0) {
1816 return (TRUE);
1817 }
1818 }
1820 return (FALSE);
1821 }
1824 function generate_alphabet($count= 10)
1825 {
1826 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1827 $alphabet= "";
1828 $c= 0;
1830 /* Fill cells with charaters */
1831 for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1832 if ($c == 0){
1833 $alphabet.= "<tr>";
1834 }
1836 $ch = mb_substr($characters, $i, 1, "UTF8");
1837 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1838 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1840 if ($c++ == $count){
1841 $alphabet.= "</tr>";
1842 $c= 0;
1843 }
1844 }
1846 /* Fill remaining cells */
1847 while ($c++ <= $count){
1848 $alphabet.= "<td> </td>";
1849 }
1851 return ($alphabet);
1852 }
1855 function validate($string)
1856 {
1857 return (strip_tags(preg_replace('/\0/', '', $string)));
1858 }
1861 function get_gosa_version()
1862 {
1863 global $svn_revision, $svn_path;
1865 /* Extract informations */
1866 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1868 /* Release or development? */
1869 if (preg_match('%/gosa/trunk/%', $svn_path)){
1870 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1871 } else {
1872 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1873 return (sprintf(_("GOsa $release"), $revision));
1874 }
1875 }
1878 function rmdirRecursive($path, $followLinks=false) {
1879 $dir= opendir($path);
1880 while($entry= readdir($dir)) {
1881 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1882 unlink($path."/".$entry);
1883 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1884 rmdirRecursive($path."/".$entry);
1885 }
1886 }
1887 closedir($dir);
1888 return rmdir($path);
1889 }
1892 function scan_directory($path,$sort_desc=false)
1893 {
1894 $ret = false;
1896 /* is this a dir ? */
1897 if(is_dir($path)) {
1899 /* is this path a readable one */
1900 if(is_readable($path)){
1902 /* Get contents and write it into an array */
1903 $ret = array();
1905 $dir = opendir($path);
1907 /* Is this a correct result ?*/
1908 if($dir){
1909 while($fp = readdir($dir))
1910 $ret[]= $fp;
1911 }
1912 }
1913 }
1914 /* Sort array ascending , like scandir */
1915 sort($ret);
1917 /* Sort descending if parameter is sort_desc is set */
1918 if($sort_desc) {
1919 $ret = array_reverse($ret);
1920 }
1922 return($ret);
1923 }
1926 function clean_smarty_compile_dir($directory)
1927 {
1928 global $svn_revision;
1930 if(is_dir($directory) && is_readable($directory)) {
1931 // Set revision filename to REVISION
1932 $revision_file= $directory."/REVISION";
1934 /* Is there a stamp containing the current revision? */
1935 if(!file_exists($revision_file)) {
1936 // create revision file
1937 create_revision($revision_file, $svn_revision);
1938 } else {
1939 # check for "$config->...['CONFIG']/revision" and the
1940 # contents should match the revision number
1941 if(!compare_revision($revision_file, $svn_revision)){
1942 // If revision differs, clean compile directory
1943 foreach(scan_directory($directory) as $file) {
1944 if(($file==".")||($file=="..")) continue;
1945 if( is_file($directory."/".$file) &&
1946 is_writable($directory."/".$file)) {
1947 // delete file
1948 if(!unlink($directory."/".$file)) {
1949 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1950 // This should never be reached
1951 }
1952 } elseif(is_dir($directory."/".$file) &&
1953 is_writable($directory."/".$file)) {
1954 // Just recursively delete it
1955 rmdirRecursive($directory."/".$file);
1956 }
1957 }
1958 // We should now create a fresh revision file
1959 clean_smarty_compile_dir($directory);
1960 } else {
1961 // Revision matches, nothing to do
1962 }
1963 }
1964 } else {
1965 // Smarty compile dir is not accessible
1966 // (Smarty will warn about this)
1967 }
1968 }
1971 function create_revision($revision_file, $revision)
1972 {
1973 $result= false;
1975 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1976 if($fh= fopen($revision_file, "w")) {
1977 if(fwrite($fh, $revision)) {
1978 $result= true;
1979 }
1980 }
1981 fclose($fh);
1982 } else {
1983 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1984 }
1986 return $result;
1987 }
1990 function compare_revision($revision_file, $revision)
1991 {
1992 // false means revision differs
1993 $result= false;
1995 if(file_exists($revision_file) && is_readable($revision_file)) {
1996 // Open file
1997 if($fh= fopen($revision_file, "r")) {
1998 // Compare File contents with current revision
1999 if($revision == fread($fh, filesize($revision_file))) {
2000 $result= true;
2001 }
2002 } else {
2003 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2004 }
2005 // Close file
2006 fclose($fh);
2007 }
2009 return $result;
2010 }
2013 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2014 {
2015 $str = ""; // Our return value will be saved in this var
2017 $color = dechex($percentage+150);
2018 $color2 = dechex(150 - $percentage);
2019 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2021 $progress = (int)(($percentage /100)*$width);
2023 /* Abort printing out percentage, if divs are to small */
2026 /* If theres a better solution for this, use it... */
2027 $str = "
2028 <div style=\" width:".($width)."px;
2029 height:".($height)."px;
2030 background-color:#000000;
2031 padding:1px;\">
2033 <div style=\" width:".($width)."px;
2034 background-color:#$bgcolor;
2035 height:".($height)."px;\">
2037 <div style=\" width:".$progress."px;
2038 height:".$height."px;
2039 background-color:#".$color2.$color2.$color."; \">";
2042 if(($height >10)&&($showvalue)){
2043 $str.= "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2044 <b>".$percentage."%</b>
2045 </font>";
2046 }
2048 $str.= "</div></div></div>";
2050 return($str);
2051 }
2054 function array_key_ics($ikey, $items)
2055 {
2056 /* Gather keys, make them lowercase */
2057 $tmp= array();
2058 foreach ($items as $key => $value){
2059 $tmp[strtolower($key)]= $key;
2060 }
2062 if (isset($tmp[strtolower($ikey)])){
2063 return($tmp[strtolower($ikey)]);
2064 }
2066 return ("");
2067 }
2070 function array_differs($src, $dst)
2071 {
2072 /* If the count is differing, the arrays differ */
2073 if (count ($src) != count ($dst)){
2074 return (TRUE);
2075 }
2077 /* So the count is the same - lets check the contents */
2078 $differs= FALSE;
2079 foreach($src as $value){
2080 if (!in_array($value, $dst)){
2081 $differs= TRUE;
2082 }
2083 }
2085 return ($differs);
2086 }
2089 function saveFilter($a_filter, $values)
2090 {
2091 if (isset($_POST['regexit'])){
2092 $a_filter["regex"]= $_POST['regexit'];
2094 foreach($values as $type){
2095 if (isset($_POST[$type])) {
2096 $a_filter[$type]= "checked";
2097 } else {
2098 $a_filter[$type]= "";
2099 }
2100 }
2101 }
2103 /* React on alphabet links if needed */
2104 if (isset($_GET['search'])){
2105 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2106 if ($s == "**"){
2107 $s= "*";
2108 }
2109 $a_filter['regex']= $s;
2110 }
2112 return ($a_filter);
2113 }
2116 /* Escape all preg_* relevant characters */
2117 function normalizePreg($input)
2118 {
2119 return (addcslashes($input, '[]()|/.*+-'));
2120 }
2123 /* Escape all LDAP filter relevant characters */
2124 function normalizeLdap($input)
2125 {
2126 return (addcslashes($input, '()|'));
2127 }
2130 /* Resturns the difference between to microtime() results in float */
2131 function get_MicroTimeDiff($start , $stop)
2132 {
2133 $a = split("\ ",$start);
2134 $b = split("\ ",$stop);
2136 $secs = $b[1] - $a[1];
2137 $msecs= $b[0] - $a[0];
2139 $ret = (float) ($secs+ $msecs);
2140 return($ret);
2141 }
2144 function get_base_dir()
2145 {
2146 global $BASE_DIR;
2148 return $BASE_DIR;
2149 }
2152 function obj_is_readable($dn, $object, $attribute)
2153 {
2154 global $ui;
2156 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2157 }
2160 function obj_is_writable($dn, $object, $attribute)
2161 {
2162 global $ui;
2164 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2165 }
2168 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2169 {
2170 /* Initialize variables */
2171 $ret = array("count" => 0); // Set count to 0
2172 $next = true; // if false, then skip next loops and return
2173 $cnt = 0; // Current number of loops
2174 $max = 100; // Just for security, prevent looops
2175 $ldap = NULL; // To check if created result a valid
2176 $keep = ""; // save last failed parse string
2178 /* Check each parsed dn in ldap ? */
2179 if($config!==NULL && $verify_in_ldap){
2180 $ldap = $config->get_ldap_link();
2181 }
2183 /* Lets start */
2184 $called = false;
2185 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2187 $cnt ++;
2188 if(!preg_match("/,/",$dn)){
2189 $next = false;
2190 }
2191 $object = preg_replace("/[,].*$/","",$dn);
2192 $dn = preg_replace("/^[^,]+,/","",$dn);
2194 $called = true;
2196 /* Check if current dn is valid */
2197 if($ldap!==NULL){
2198 $ldap->cd($dn);
2199 $ldap->cat($dn,array("dn"));
2200 if($ldap->count()){
2201 $ret[] = $keep.$object;
2202 $keep = "";
2203 }else{
2204 $keep .= $object.",";
2205 }
2206 }else{
2207 $ret[] = $keep.$object;
2208 $keep = "";
2209 }
2210 }
2212 /* No dn was posted */
2213 if($cnt == 0 && !empty($dn)){
2214 $ret[] = $dn;
2215 }
2217 /* Append the rest */
2218 $test = $keep.$dn;
2219 if($called && !empty($test)){
2220 $ret[] = $keep.$dn;
2221 }
2222 $ret['count'] = count($ret) - 1;
2224 return($ret);
2225 }
2228 function get_base_from_hook($dn, $attrib)
2229 {
2230 global $config;
2232 if (isset($config->current['BASE_HOOK'])){
2234 /* Call hook script - if present */
2235 $command= $config->current['BASE_HOOK'];
2237 if ($command != ""){
2238 $command.= " '".LDAP::fix($dn)."' $attrib";
2239 if (check_command($command)){
2240 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2241 exec($command, $output);
2242 if (preg_match("/^[0-9]+$/", $output[0])){
2243 return ($output[0]);
2244 } else {
2245 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2246 return ($config->current['UIDBASE']);
2247 }
2248 } else {
2249 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2250 return ($config->current['UIDBASE']);
2251 }
2253 } else {
2255 msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2256 return ($config->current['UIDBASE']);
2258 }
2259 }
2260 }
2263 function check_schema_version($class, $version)
2264 {
2265 return preg_match("/\(v$version\)/", $class['DESC']);
2266 }
2269 function check_schema($cfg,$rfc2307bis = FALSE)
2270 {
2271 $messages= array();
2273 /* Get objectclasses */
2274 $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2275 $objectclasses = $ldap->get_objectclasses();
2276 if(count($objectclasses) == 0){
2277 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2278 }
2280 /* This is the default block used for each entry.
2281 * to avoid unset indexes.
2282 */
2283 $def_check = array("REQUIRED_VERSION" => "0",
2284 "SCHEMA_FILES" => array(),
2285 "CLASSES_REQUIRED" => array(),
2286 "STATUS" => FALSE,
2287 "IS_MUST_HAVE" => FALSE,
2288 "MSG" => "",
2289 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2291 /* The gosa base schema */
2292 $checks['gosaObject'] = $def_check;
2293 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2294 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2295 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2296 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2298 /* GOsa Account class */
2299 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2300 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2301 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2302 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2303 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2305 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2306 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2307 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2308 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2309 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2310 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2312 /* Some other checks */
2313 foreach(array(
2314 "gosaCacheEntry" => array("version" => "2.4"),
2315 "gosaDepartment" => array("version" => "2.4"),
2316 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2317 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2318 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2319 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2320 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2321 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2322 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2323 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2324 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2325 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2326 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2327 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2328 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2329 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2330 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2331 "goLdapServer" => array("version" => "2.4"),
2332 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2333 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2334 "goKrbServer" => array("version" => "2.4"),
2335 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2336 ) as $name => $values){
2338 $checks[$name] = $def_check;
2339 if(isset($values['version'])){
2340 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2341 }
2342 if(isset($values['file'])){
2343 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2344 }
2345 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2346 }
2347 foreach($checks as $name => $value){
2348 foreach($value['CLASSES_REQUIRED'] as $class){
2350 if(!isset($objectclasses[$name])){
2351 $checks[$name]['STATUS'] = FALSE;
2352 if($value['IS_MUST_HAVE']){
2353 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2354 }else{
2355 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2356 }
2357 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2358 $checks[$name]['STATUS'] = FALSE;
2360 if($value['IS_MUST_HAVE']){
2361 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2362 }else{
2363 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2364 }
2365 }else{
2366 $checks[$name]['STATUS'] = TRUE;
2367 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2368 }
2369 }
2370 }
2372 $tmp = $objectclasses;
2374 /* The gosa base schema */
2375 $checks['posixGroup'] = $def_check;
2376 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2377 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2378 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2379 $checks['posixGroup']['STATUS'] = TRUE;
2380 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2381 $checks['posixGroup']['MSG'] = "";
2382 $checks['posixGroup']['INFO'] = "";
2384 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2385 if(isset($tmp['posixGroup'])){
2387 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2388 $checks['posixGroup']['STATUS'] = FALSE;
2389 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2390 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2391 }
2392 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2393 $checks['posixGroup']['STATUS'] = FALSE;
2394 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2395 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2396 }
2397 }
2399 return($checks);
2400 }
2403 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2404 {
2405 $tmp = array(
2406 "de_DE" => "German",
2407 "fr_FR" => "French",
2408 "it_IT" => "Italian",
2409 "es_ES" => "Spanish",
2410 "en_US" => "English",
2411 "nl_NL" => "Dutch",
2412 "pl_PL" => "Polish",
2413 "sv_SE" => "Swedish",
2414 "zh_CN" => "Chinese",
2415 "ru_RU" => "Russian");
2417 $tmp2= array(
2418 "de_DE" => _("German"),
2419 "fr_FR" => _("French"),
2420 "it_IT" => _("Italian"),
2421 "es_ES" => _("Spanish"),
2422 "en_US" => _("English"),
2423 "nl_NL" => _("Dutch"),
2424 "pl_PL" => _("Polish"),
2425 "sv_SE" => _("Swedish"),
2426 "zh_CN" => _("Chinese"),
2427 "ru_RU" => _("Russian"));
2429 $ret = array();
2430 if($languages_in_own_language){
2432 $old_lang = setlocale(LC_ALL, 0);
2433 foreach($tmp as $key => $name){
2434 $lang = $key.".UTF-8";
2435 setlocale(LC_ALL, $lang);
2436 if($strip_region_tag){
2437 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2438 }else{
2439 $ret[$key] = _($name)." (".$tmp2[$key].")";
2440 }
2441 }
2442 setlocale(LC_ALL, $old_lang);
2443 }else{
2444 foreach($tmp as $key => $name){
2445 if($strip_region_tag){
2446 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2447 }else{
2448 $ret[$key] = _($name);
2449 }
2450 }
2451 }
2452 return($ret);
2453 }
2456 /* Returns contents of the given POST variable and check magic quotes settings */
2457 function get_post($name)
2458 {
2459 if(!isset($_POST[$name])){
2460 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2461 return(FALSE);
2462 }
2463 if(get_magic_quotes_gpc()){
2464 return(stripcslashes($_POST[$name]));
2465 }else{
2466 return($_POST[$name]);
2467 }
2468 }
2471 /* Return class name in correct case */
2472 function get_correct_class_name($cls)
2473 {
2474 global $class_mapping;
2475 if(isset($class_mapping) && is_array($class_mapping)){
2476 foreach($class_mapping as $class => $file){
2477 if(preg_match("/^".$cls."$/i",$class)){
2478 return($class);
2479 }
2480 }
2481 }
2482 return(FALSE);
2483 }
2486 // change_password, changes the Password, of the given dn
2487 function change_password ($dn, $password, $mode=0, $hash= "")
2488 {
2489 global $config;
2490 $newpass= "";
2492 /* Convert to lower. Methods are lowercase */
2493 $hash= strtolower($hash);
2495 // Get all available encryption Methods
2497 // NON STATIC CALL :)
2498 $tmp = new passwordMethod(session::get('config'));
2499 $available = $tmp->get_available_methods();
2501 // read current password entry for $dn, to detect the encryption Method
2502 $ldap = $config->get_ldap_link();
2503 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2504 $attrs = $ldap->fetch ();
2506 // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2507 if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2508 $deactivated = TRUE;
2509 }else{
2510 $deactivated = FALSE;
2511 }
2513 /* Is ensure that clear passwords will stay clear */
2514 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2515 $hash = "clear";
2516 }
2518 // Detect the encryption Method
2519 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2521 /* Check for supported algorithm */
2522 mt_srand((double) microtime()*1000000);
2524 /* Extract used hash */
2525 if ($hash == ""){
2526 $hash= strtolower($matches[1]);
2527 }
2529 $test = new $available[$hash]($config);
2531 } else {
2532 // User MD5 by default
2533 $hash= "md5";
2534 $test = new $available['md5']($config);
2535 }
2537 /* Feed password backends with information */
2538 $test->dn= $dn;
2539 $test->attrs= $attrs;
2540 $newpass= $test->generate_hash($password);
2542 // Update shadow timestamp?
2543 if (isset($attrs["shadowLastChange"][0])){
2544 $shadow= (int)(date("U") / 86400);
2545 } else {
2546 $shadow= 0;
2547 }
2549 // Write back modified entry
2550 $ldap->cd($dn);
2551 $attrs= array();
2553 // Not for groups
2554 if ($mode == 0){
2556 if ($shadow != 0){
2557 $attrs['shadowLastChange']= $shadow;
2558 }
2560 // Create SMB Password
2561 $attrs= generate_smb_nt_hash($password);
2562 }
2564 /* Readd ! if user was deactivated */
2565 if($deactivated){
2566 $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2567 }
2569 $attrs['userPassword']= array();
2570 $attrs['userPassword']= $newpass;
2572 $ldap->modify($attrs);
2574 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2576 if ($ldap->error != 'Success') {
2577 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);
2578 } else {
2580 /* Run backend method for change/create */
2581 $test->set_password($password);
2583 /* Find postmodify entries for this class */
2584 $command= $config->search("password", "POSTMODIFY",array('menu'));
2586 if ($command != ""){
2587 /* Walk through attribute list */
2588 $command= preg_replace("/%userPassword/", $password, $command);
2589 $command= preg_replace("/%dn/", $dn, $command);
2591 if (check_command($command)){
2592 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2593 exec($command);
2594 } else {
2595 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2596 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2597 }
2598 }
2599 }
2600 }
2603 // Return something like array['sambaLMPassword']= "lalla..."
2604 function generate_smb_nt_hash($password)
2605 {
2606 global $config;
2608 # Try to use gosa-si?
2609 if (isset($config->current['GOSA_SI'])){
2610 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2611 $hash= $res['XML']['HASH'];
2612 } else {
2613 $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2614 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2616 exec($tmp, $ar);
2617 flush();
2618 reset($ar);
2619 $hash= current($ar);
2620 }
2622 if ($hash == "") {
2623 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2624 return ("");
2625 }
2627 list($lm,$nt)= split (":", trim($hash));
2629 if ($config->current['SAMBAVERSION'] == 3) {
2630 $attrs['sambaLMPassword']= $lm;
2631 $attrs['sambaNTPassword']= $nt;
2632 $attrs['sambaPwdLastSet']= date('U');
2633 $attrs['sambaBadPasswordCount']= "0";
2634 $attrs['sambaBadPasswordTime']= "0";
2635 } else {
2636 $attrs['lmPassword']= $lm;
2637 $attrs['ntPassword']= $nt;
2638 $attrs['pwdLastSet']= date('U');
2639 }
2640 return($attrs);
2641 }
2644 function crypt_single($string,$enc_type )
2645 {
2646 return( passwordMethod::crypt_single_str($string,$enc_type));
2647 }
2650 function getEntryCSN($dn)
2651 {
2652 global $config;
2653 if(empty($dn) || !is_object($config)){
2654 return("");
2655 }
2657 /* Get attribute that we should use as serial number */
2658 if(isset($config->current['UNIQ_IDENTIFIER'])){
2659 $attr = $config->current['UNIQ_IDENTIFIER'];
2660 }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2661 $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2662 }
2663 if(!empty($attr)){
2664 $ldap = $config->get_ldap_link();
2665 $ldap->cat($dn,array($attr));
2666 $csn = $ldap->fetch();
2667 if(isset($csn[$attr][0])){
2668 return($csn[$attr][0]);
2669 }
2670 }
2671 return("");
2672 }
2675 /* Add a given objectClass to an attrs entry */
2676 function add_objectClass($classes, &$attrs)
2677 {
2678 if (is_array($classes)){
2679 $list= $classes;
2680 } else {
2681 $list= array($classes);
2682 }
2684 foreach ($list as $class){
2685 $attrs['objectClass'][]= $class;
2686 }
2687 }
2690 /* Removes a given objectClass from the attrs entry */
2691 function remove_objectClass($classes, &$attrs)
2692 {
2693 if (isset($attrs['objectClass'])){
2694 /* Array? */
2695 if (is_array($classes)){
2696 $list= $classes;
2697 } else {
2698 $list= array($classes);
2699 }
2701 $tmp= array();
2702 foreach ($attrs['objectClass'] as $oc) {
2703 foreach ($list as $class){
2704 if ($oc != $class){
2705 $tmp[]= $oc;
2706 }
2707 }
2708 }
2709 $attrs['objectClass']= $tmp;
2710 }
2711 }
2713 /*! \brief Initialize a file download with given content, name and data type.
2714 * @param data String The content to send.
2715 * @param name String The name of the file.
2716 * @param type String The content identifier, default value is "application/octet-stream";
2717 */
2718 function send_binary_content($data,$name,$type = "application/octet-stream")
2719 {
2720 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2721 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2722 header("Cache-Control: no-cache");
2723 header("Pragma: no-cache");
2724 header("Cache-Control: post-check=0, pre-check=0");
2725 header("Content-type: ".$type."");
2727 /* force download dialog */
2728 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2729 header('Content-Disposition: filename="'.$name.'"');
2730 } else {
2731 header('Content-Disposition: attachment; filename="'.$name.'"');
2732 }
2734 echo $data;
2735 exit();
2736 }
2738 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2739 ?>