1 <?php
2 /*
3 * This code is part of GOsa (http://www.gosa-project.org)
4 * Copyright (C) 2003-2008 GONICUS GmbH
5 *
6 * ID: $$Id: functions.inc 13100 2008-12-01 14:07:48Z hickert $$
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 */
23 /*! \file
24 * Common functions and named definitions. */
26 /* Configuration file location */
27 if(!isset($_SERVER['CONFIG_DIR'])){
28 define ("CONFIG_DIR", "/etc/gosa");
29 }else{
30 define ("CONFIG_DIR",$_SERVER['CONFIG_DIR']);
31 }
33 /* Allow setting the config file in the apache configuration
34 e.g. SetEnv CONFIG_FILE gosa.conf.2.6
35 */
36 if(!isset($_SERVER['CONFIG_FILE'])){
37 define ("CONFIG_FILE", "gosa.conf");
38 }else{
39 define ("CONFIG_FILE",$_SERVER['CONFIG_FILE']);
40 }
42 /* Define common locatitions */
43 define ("CONFIG_TEMPLATE_DIR", "../contrib");
44 define ("TEMP_DIR","/var/cache/gosa/tmp");
46 /* Define get_list flags */
47 define("GL_NONE", 0);
48 define("GL_SUBSEARCH", 1);
49 define("GL_SIZELIMIT", 2);
50 define("GL_CONVERT", 4);
51 define("GL_NO_ACL_CHECK", 8);
53 /* Heimdal stuff */
54 define('UNIVERSAL',0x00);
55 define('INTEGER',0x02);
56 define('OCTET_STRING',0x04);
57 define('OBJECT_IDENTIFIER ',0x06);
58 define('SEQUENCE',0x10);
59 define('SEQUENCE_OF',0x10);
60 define('SET',0x11);
61 define('SET_OF',0x11);
62 define('DEBUG',false);
63 define('HDB_KU_MKEY',0x484442);
64 define('TWO_BIT_SHIFTS',0x7efc);
65 define('DES_CBC_CRC',1);
66 define('DES_CBC_MD4',2);
67 define('DES_CBC_MD5',3);
68 define('DES3_CBC_MD5',5);
69 define('DES3_CBC_SHA1',16);
71 /* Define globals for revision comparing */
72 $svn_path = '$HeadURL$';
73 $svn_revision = '$Revision$';
75 /* Include required files */
76 require_once("class_location.inc");
77 require_once ("functions_debug.inc");
78 require_once ("accept-to-gettext.inc");
80 /* Define constants for debugging */
81 define ("DEBUG_TRACE", 1); /*! Debug level for tracing of common actions (save, check, etc.) */
82 define ("DEBUG_LDAP", 2); /*! Debug level for LDAP queries */
83 define ("DEBUG_MYSQL", 4); /*! Debug level for mysql operations */
84 define ("DEBUG_SHELL", 8); /*! Debug level for shell commands */
85 define ("DEBUG_POST", 16); /*! Debug level for POST content */
86 define ("DEBUG_SESSION",32); /*! Debug level for SESSION content */
87 define ("DEBUG_CONFIG", 64); /*! Debug level for CONFIG information */
88 define ("DEBUG_ACL", 128); /*! Debug level for ACL infos */
89 define ("DEBUG_SI", 256); /*! Debug level for communication with gosa-si */
90 define ("DEBUG_MAIL", 512); /*! Debug level for all about mail (mailAccounts, imap, sieve etc.) */
91 define ("DEBUG_FAI", 1024); // FAI (incomplete)
94 // Define shadow states
95 define ("POSIX_ACCOUNT_EXPIRED", 1);
96 define ("POSIX_WARN_ABOUT_EXPIRATION", 2);
97 define ("POSIX_FORCE_PASSWORD_CHANGE", 4);
98 define ("POSIX_DISALLOW_PASSWORD_CHANGE", 8);
100 /* Rewrite german 'umlauts' and spanish 'accents'
101 to get better results */
102 $REWRITE= array( "ä" => "ae",
103 "ö" => "oe",
104 "ü" => "ue",
105 "Ä" => "Ae",
106 "Ö" => "Oe",
107 "Ü" => "Ue",
108 "ß" => "ss",
109 "á" => "a",
110 "é" => "e",
111 "í" => "i",
112 "ó" => "o",
113 "ú" => "u",
114 "Á" => "A",
115 "É" => "E",
116 "Í" => "I",
117 "Ó" => "O",
118 "Ú" => "U",
119 "ñ" => "ny",
120 "Ñ" => "Ny" );
123 /*! \brief Does autoloading for classes used in GOsa.
124 *
125 * Takes the list generated by 'update-gosa' and loads the
126 * file containing the requested class.
127 *
128 * \param string 'class_name' The currently requested class
129 */
130 function __gosa_autoload($class_name) {
131 global $class_mapping, $BASE_DIR;
133 if ($class_mapping === NULL){
134 echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
135 exit;
136 }
138 if (isset($class_mapping["$class_name"])){
139 require_once($BASE_DIR."/".$class_mapping["$class_name"]);
140 } else {
141 echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
142 exit;
143 }
144 }
145 spl_autoload_register('__gosa_autoload');
148 /*! \brief Checks if a class is available.
149 * \param string 'name' The subject of the test
150 * \return boolean True if class is available, else false.
151 */
152 function class_available($name)
153 {
154 global $class_mapping;
155 return(isset($class_mapping[$name]));
156 }
159 /*! \brief Check if plugin is available
160 *
161 * Checks if a given plugin is available and readable.
162 *
163 * \param string 'plugin' the subject of the check
164 * \return boolean True if plugin is available, else FALSE.
165 */
166 function plugin_available($plugin)
167 {
168 global $class_mapping, $BASE_DIR;
170 if (!isset($class_mapping[$plugin])){
171 return false;
172 } else {
173 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
174 }
175 }
178 /*! \brief Create seed with microseconds
179 *
180 * Example:
181 * \code
182 * srand(make_seed());
183 * $random = rand();
184 * \endcode
185 *
186 * \return float a floating point number which can be used to feed srand() with it
187 * */
188 function make_seed() {
189 list($usec, $sec) = explode(' ', microtime());
190 return (float) $sec + ((float) $usec * 100000);
191 }
194 /*! \brief Debug level action
195 *
196 * Print a DEBUG level if specified debug level of the level matches the
197 * the configured debug level.
198 *
199 * \param int 'level' The log level of the message (should use the constants,
200 * defined in functions.in (DEBUG_TRACE, DEBUG_LDAP, etc.)
201 * \param int 'line' Define the line of the logged action (using __LINE__ is common)
202 * \param string 'function' Define the function where the logged action happened in
203 * (using __FUNCTION__ is common)
204 * \param string 'file' Define the file where the logged action happend in
205 * (using __FILE__ is common)
206 * \param mixed 'data' The data to log. Can be a message or an array, which is printed
207 * with print_a
208 * \param string 'info' Optional: Additional information
209 *
210 * */
211 function DEBUG($level, $line, $function, $file, $data, $info="")
212 {
213 if (session::global_get('DEBUGLEVEL') & $level){
214 $output= "DEBUG[$level] ";
215 if ($function != ""){
216 $output.= "($file:$function():$line) - $info: ";
217 } else {
218 $output.= "($file:$line) - $info: ";
219 }
220 echo $output;
221 if (is_array($data)){
222 print_a($data);
223 } else {
224 echo "'$data'";
225 }
226 echo "<br>";
227 }
228 }
231 /*! \brief Determine which language to show to the user
232 *
233 * Determines which language should be used to present gosa content
234 * to the user. It does so by looking at several possibilites and returning
235 * the first setting that can be found.
236 *
237 * -# Language configured by the user
238 * -# Global configured language
239 * -# Language as returned by al2gt (as configured in the browser)
240 *
241 * \return string gettext locale string
242 */
243 function get_browser_language()
244 {
245 /* Try to use users primary language */
246 global $config;
247 $ui= get_userinfo();
248 if (isset($ui) && $ui !== NULL){
249 if ($ui->language != ""){
250 return ($ui->language.".UTF-8");
251 }
252 }
254 /* Check for global language settings in gosa.conf */
255 if (isset ($config) && $config->get_cfg_value('language') != ""){
256 $lang = $config->get_cfg_value('language');
257 if(!preg_match("/utf/i",$lang)){
258 $lang .= ".UTF-8";
259 }
260 return($lang);
261 }
263 /* Load supported languages */
264 $gosa_languages= get_languages();
266 /* Move supported languages to flat list */
267 $langs= array();
268 foreach($gosa_languages as $lang => $dummy){
269 $langs[]= $lang.'.UTF-8';
270 }
272 /* Return gettext based string */
273 return (al2gt($langs, 'text/html'));
274 }
277 /*! \brief Rewrite ui object to another dn
278 *
279 * Usually used when a user is renamed. In this case the dn
280 * in the user object must be updated in order to point
281 * to the correct DN.
282 *
283 * \param string 'dn' the old DN
284 * \param string 'newdn' the new DN
285 * */
286 function change_ui_dn($dn, $newdn)
287 {
288 $ui= session::global_get('ui');
289 if ($ui->dn == $dn){
290 $ui->dn= $newdn;
291 session::global_set('ui',$ui);
292 }
293 }
296 /*! \brief Return themed path for specified base file
297 *
298 * Depending on its parameters, this function returns the full
299 * path of a template file. First match wins while searching
300 * in this order:
301 *
302 * - load theme depending file
303 * - load global theme depending file
304 * - load default theme file
305 * - load global default theme file
306 *
307 * \param string 'filename' The base file name
308 * \param boolean 'plugin' Flag to take the plugin directory as search base
309 * \param string 'path' User specified path to take as search base
310 * \return string Full path to the template file
311 */
312 function get_template_path($filename= '', $plugin= FALSE, $path= "")
313 {
314 global $config, $BASE_DIR;
316 /* Set theme */
317 if (isset ($config)){
318 $theme= $config->get_cfg_value("theme", "default");
319 } else {
320 $theme= "default";
321 }
323 /* Return path for empty filename */
324 if ($filename == ''){
325 return ("themes/$theme/");
326 }
328 /* Return plugin dir or root directory? */
329 if ($plugin){
330 if ($path == ""){
331 $nf= preg_replace("!^".$BASE_DIR."/!", "", preg_replace('/^\.\.\//', '', session::global_get('plugin_dir')));
332 } else {
333 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
334 }
335 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
336 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
337 }
338 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
339 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
340 }
341 if ($path == ""){
342 return (session::global_get('plugin_dir')."/$filename");
343 } else {
344 return ($path."/$filename");
345 }
346 } else {
347 if (file_exists("themes/$theme/$filename")){
348 return ("themes/$theme/$filename");
349 }
350 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
351 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
352 }
353 if (file_exists("themes/default/$filename")){
354 return ("themes/default/$filename");
355 }
356 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
357 return ("$BASE_DIR/ihtml/themes/default/$filename");
358 }
359 return ($filename);
360 }
361 }
364 /*! \brief Remove multiple entries from an array
365 *
366 * Removes every element that is in $needles from the
367 * array given as $haystack
368 *
369 * \param array 'needles' array of the entries to remove
370 * \param array 'haystack' original array to remove the entries from
371 */
372 function array_remove_entries($needles, $haystack)
373 {
374 return (array_merge(array_diff($haystack, $needles)));
375 }
378 /*! \brief Remove multiple entries from an array (case-insensitive)
379 *
380 * Same as array_remove_entries(), but case-insensitive. */
381 function array_remove_entries_ics($needles, $haystack)
382 {
383 // strcasecmp will work, because we only compare ASCII values here
384 return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
385 }
388 /*! Merge to array but remove duplicate entries
389 *
390 * Merges two arrays and removes duplicate entries. Triggers
391 * an error if first or second parametre is not an array.
392 *
393 * \param array 'ar1' first array
394 * \param array 'ar2' second array-
395 * \return array
396 */
397 function gosa_array_merge($ar1,$ar2)
398 {
399 if(!is_array($ar1) || !is_array($ar2)){
400 trigger_error("Specified parameter(s) are not valid arrays.");
401 }else{
402 return(array_values(array_unique(array_merge($ar1,$ar2))));
403 }
404 }
407 /*! \brief Generate a system log info
408 *
409 * Creates a syslog message, containing user information.
410 *
411 * \param string 'message' the message to log
412 * */
413 function gosa_log ($message)
414 {
415 global $ui;
417 /* Preset to something reasonable */
418 $username= "[unauthenticated]";
420 /* Replace username if object is present */
421 if (isset($ui)){
422 if ($ui->username != ""){
423 $username= "[$ui->username]";
424 } else {
425 $username= "[unknown]";
426 }
427 }
429 syslog(LOG_INFO,"GOsa$username: $message");
430 }
433 /*! \brief Initialize a LDAP connection
434 *
435 * Initializes a LDAP connection.
436 *
437 * \param string 'server'
438 * \param string 'base'
439 * \param string 'binddn' Default: empty
440 * \param string 'pass' Default: empty
441 *
442 * \return LDAP object
443 */
444 function ldap_init ($server, $base, $binddn='', $pass='')
445 {
446 global $config;
448 $ldap = new LDAP ($binddn, $pass, $server,
449 isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
450 isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
452 /* Sadly we've no proper return values here. Use the error message instead. */
453 if (!$ldap->success()){
454 msg_dialog::display(_("Fatal error"),
455 sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
456 FATAL_ERROR_DIALOG);
457 exit();
458 }
460 /* Preset connection base to $base and return to caller */
461 $ldap->cd ($base);
462 return $ldap;
463 }
466 /* \brief Process htaccess authentication */
467 function process_htaccess ($username, $kerberos= FALSE)
468 {
469 global $config;
471 /* Search for $username and optional @REALM in all configured LDAP trees */
472 foreach($config->data["LOCATIONS"] as $name => $data){
474 $config->set_current($name);
475 $mode= "kerberos";
476 if ($config->get_cfg_value("useSaslForKerberos") == "true"){
477 $mode= "sasl";
478 }
480 /* Look for entry or realm */
481 $ldap= $config->get_ldap_link();
482 if (!$ldap->success()){
483 msg_dialog::display(_("LDAP error"),
484 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
485 FATAL_ERROR_DIALOG);
486 exit();
487 }
488 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
490 /* Found a uniq match? Return it... */
491 if ($ldap->count() == 1) {
492 $attrs= $ldap->fetch();
493 return array("username" => $attrs["uid"][0], "server" => $name);
494 }
495 }
497 /* Nothing found? Return emtpy array */
498 return array("username" => "", "server" => "");
499 }
502 /*! \brief Verify user login against htaccess
503 *
504 * Checks if the specified username is available in apache, maps the user
505 * to an LDAP user. The password has been checked by apache already.
506 *
507 * \param string 'username'
508 * \return
509 * - TRUE on SUCCESS, NULL or FALSE on error
510 */
511 function ldap_login_user_htaccess ($username)
512 {
513 global $config;
515 /* Look for entry or realm */
516 $ldap= $config->get_ldap_link();
517 if (!$ldap->success()){
518 msg_dialog::display(_("LDAP error"),
519 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
520 FATAL_ERROR_DIALOG);
521 exit();
522 }
523 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
524 /* Found no uniq match? Strange, because we did above... */
525 if ($ldap->count() != 1) {
526 msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
527 return (NULL);
528 }
529 $attrs= $ldap->fetch();
531 /* got user dn, fill acl's */
532 $ui= new userinfo($config, $ldap->getDN());
533 $ui->username= $attrs['uid'][0];
535 /* Bail out if we have login restrictions set, for security reasons
536 the message is the same than failed user/pw */
537 if (!$ui->loginAllowed()){
538 return (NULL);
539 }
541 /* No password check needed - the webserver did it for us */
542 $ldap->disconnect();
544 /* Username is set, load subtreeACL's now */
545 $ui->loadACL();
547 /* TODO: check java script for htaccess authentication */
548 session::global_set('js', true);
550 return ($ui);
551 }
554 /*! \brief Verify user login against LDAP directory
555 *
556 * Checks if the specified username is in the LDAP and verifies if the
557 * password is correct by binding to the LDAP with the given credentials.
558 *
559 * \param string 'username'
560 * \param string 'password'
561 * \return
562 * - TRUE on SUCCESS, NULL or FALSE on error
563 */
564 function ldap_login_user ($username, $password)
565 {
566 global $config;
568 /* look through the entire ldap */
569 $ldap = $config->get_ldap_link();
570 if (!$ldap->success()){
571 msg_dialog::display(_("LDAP error"),
572 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
573 FATAL_ERROR_DIALOG);
574 exit();
575 }
576 $ldap->cd($config->current['BASE']);
577 $allowed_attributes = array("uid","mail");
578 $verify_attr = array();
579 if($config->get_cfg_value("loginAttribute") != ""){
580 $tmp = explode(",", $config->get_cfg_value("loginAttribute"));
581 foreach($tmp as $attr){
582 if(in_array($attr,$allowed_attributes)){
583 $verify_attr[] = $attr;
584 }
585 }
586 }
587 if(count($verify_attr) == 0){
588 $verify_attr = array("uid");
589 }
590 $tmp= $verify_attr;
591 $tmp[] = "uid";
592 $filter = "";
593 foreach($verify_attr as $attr) {
594 $filter.= "(".$attr."=".$username.")";
595 }
596 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
597 $ldap->search($filter,$tmp);
599 /* get results, only a count of 1 is valid */
600 switch ($ldap->count()){
602 /* user not found */
603 case 0: return (NULL);
605 /* valid uniq user */
606 case 1:
607 break;
609 /* found more than one matching id */
610 default:
611 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
612 return (NULL);
613 }
615 /* LDAP schema is not case sensitive. Perform additional check. */
616 $attrs= $ldap->fetch();
617 $success = FALSE;
618 foreach($verify_attr as $attr){
619 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
620 $success = TRUE;
621 }
622 }
623 if(!$success){
624 return(FALSE);
625 }
627 /* got user dn, fill acl's */
628 $ui= new userinfo($config, $ldap->getDN());
629 $ui->username= $attrs['uid'][0];
631 /* Bail out if we have login restrictions set, for security reasons
632 the message is the same than failed user/pw */
633 if (!$ui->loginAllowed()){
634 return (NULL);
635 }
637 /* password check, bind as user with supplied password */
638 $ldap->disconnect();
639 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
640 isset($config->current['LDAPFOLLOWREFERRALS']) &&
641 $config->current['LDAPFOLLOWREFERRALS'] == "true",
642 isset($config->current['LDAPTLS'])
643 && $config->current['LDAPTLS'] == "true");
644 if (!$ldap->success()){
645 return (NULL);
646 }
648 /* Username is set, load subtreeACL's now */
649 $ui->loadACL();
651 return ($ui);
652 }
655 /*! \brief Checks the posixAccount status by comparing the shadow attributes.
656 *
657 * @param Object The GOsa configuration object.
658 * @param String The 'dn' of the user to test the account status for.
659 * @param String The 'uid' of the user we're going to test.
660 * @return Const
661 * POSIX_ACCOUNT_EXPIRED - If the account is expired.
662 * POSIX_WARN_ABOUT_EXPIRATION - If the account is going to expire.
663 * POSIX_FORCE_PASSWORD_CHANGE - The password has to be changed.
664 * POSIX_DISALLOW_PASSWORD_CHANGE - The password cannot be changed right now.
665 *
666 *
667 *
668 * shadowLastChange
669 * |
670 * |---- shadowMin ---> | <-- shadowMax --
671 * | | |
672 * |------- shadowWarning -> |
673 * |-- shadowInactive --> DEACTIVATED
674 * |
675 * EXPIRED
676 *
677 */
678 function ldap_expired_account($config, $userdn, $uid)
679 {
680 $ldap= $config->get_ldap_link();
681 $ldap->cd($config->current['BASE']);
682 $ldap->cat($userdn);
683 $attrs= $ldap->fetch();
684 $current= floor(date("U") /60 /60 /24);
687 // Fetch required attributes
688 foreach(array('shadowExpire','shadowLastChange','shadowMax','shadowMin',
689 'shadowInactive','shadowWarning') as $attr){
690 $$attr = (isset($attrs[$attr][0]))? $attrs[$attr][0] : null;
691 }
694 // Check if the account has expired.
695 // ---------------------------------
696 // An account is locked/expired once its expiration date has reached (shadowExpire).
697 // If the optional attribute (shadowInactive) is set, we've to postpone
698 // the account expiration by the amount of days specified in (shadowInactive).
699 if($shadowExpire != null && $shadowExpire >= $current){
701 // The account seems to be expired, but we've to check 'shadowInactive' additionally.
702 // ShadowInactive specifies an amount of days we've to reprieve the user.
703 // It some kind of x days' grace.
704 if($shadowInactive == null || $current > $shadowExpire + $shadowInactive){
706 // Finally we've detect that the account is deactivated.
707 return(POSIX_ACCOUNT_EXPIRED);
708 }
709 }
711 // The users password is going to expire.
712 // --------------------------------------
713 // We've to warn the user in the case of an expiring account.
714 // An account is going to expire when it reaches its expiration date (shadowExpire).
715 // The user has to be warned, if the days left till expiration, match the
716 // configured warning period (shadowWarning)
717 // --> shadowWarning: Warn x days before account expiration.
718 if($shadowExpire != null && $shadowWarning != null){
720 // Check if the account is still active and not already expired.
721 if($shadowExpire >= $current){
723 // Check if we've to warn the user by comparing the remaining
724 // number of days till expiration with the configured amount
725 // of days in shadowWarning.
726 if(($shadowExpire - $current) <= $shadowWarning){
727 return(POSIX_WARN_ABOUT_EXPIRATION);
728 }
729 }
730 }
733 // Check if we've to force the user to change his password.
734 // --------------------------------------------------------
735 // A password change is enforced when the password is older than
736 // the configured amount of days (shadowMax).
737 // The age of the current password (shadowLastChange) plus the maximum
738 // amount amount of days (shadowMax) has to be smaller than the
739 // current timestamp.
740 if($shadowLastChange != null && $shadowMax != null){
742 // Check if we've an outdated password.
743 if($current >= ($shadowLastChange + $shadowMax)){
744 return(POSIX_FORCE_PASSWORD_CHANGE);
745 }
746 }
749 // Check if we've to freeze the users password.
750 // --------------------------------------------
751 // Once a user has changed his password, he cannot change it again
752 // for a given amount of days (shadowMin).
753 // We should not allow to change the password within GOsa too.
754 if($shadowLastChange != null && $shadowMin != null){
756 // Check if we've an outdated password.
757 if(($shadowLastChange + $shadowMin) >= $current){
758 return(POSIX_DISALLOW_PASSWORD_CHANGE);
759 }
760 }
762 return(NULL);
763 }
766 /*! \brief Add a lock for object(s)
767 *
768 * Adds a lock by the specified user for one ore multiple objects.
769 * If the lock for that object already exists, an error is triggered.
770 *
771 * \param mixed 'object' object or array of objects to lock
772 * \param string 'user' the user who shall own the lock
773 * */
774 function add_lock($object, $user)
775 {
776 global $config;
778 /* Remember which entries were opened as read only, because we
779 don't need to remove any locks for them later.
780 */
781 if(!session::global_is_set("LOCK_CACHE")){
782 session::global_set("LOCK_CACHE",array(""));
783 }
784 if(is_array($object)){
785 foreach($object as $obj){
786 add_lock($obj,$user);
787 }
788 return;
789 }
791 $cache = &session::global_get("LOCK_CACHE");
792 if(isset($_POST['open_readonly'])){
793 $cache['READ_ONLY'][$object] = TRUE;
794 return;
795 }
796 if(isset($cache['READ_ONLY'][$object])){
797 unset($cache['READ_ONLY'][$object]);
798 }
801 /* Just a sanity check... */
802 if ($object == "" || $user == ""){
803 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
804 return;
805 }
807 /* Check for existing entries in lock area */
808 $ldap= $config->get_ldap_link();
809 $ldap->cd ($config->get_cfg_value("config"));
810 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
811 array("gosaUser"));
812 if (!$ldap->success()){
813 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);
814 return;
815 }
817 /* Add lock if none present */
818 if ($ldap->count() == 0){
819 $attrs= array();
820 $name= md5($object);
821 $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
822 $attrs["objectClass"] = "gosaLockEntry";
823 $attrs["gosaUser"] = $user;
824 $attrs["gosaObject"] = base64_encode($object);
825 $attrs["cn"] = "$name";
826 $ldap->add($attrs);
827 if (!$ldap->success()){
828 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
829 return;
830 }
831 }
832 }
835 /*! \brief Remove a lock for object(s)
836 *
837 * Does the opposite of add_lock().
838 *
839 * \param mixed 'object' object or array of objects for which a lock shall be removed
840 * */
841 function del_lock ($object)
842 {
843 global $config;
845 if(is_array($object)){
846 foreach($object as $obj){
847 del_lock($obj);
848 }
849 return;
850 }
852 /* Sanity check */
853 if ($object == ""){
854 return;
855 }
857 /* If this object was opened in read only mode then
858 skip removing the lock entry, there wasn't any lock created.
859 */
860 if(session::global_is_set("LOCK_CACHE")){
861 $cache = &session::global_get("LOCK_CACHE");
862 if(isset($cache['READ_ONLY'][$object])){
863 unset($cache['READ_ONLY'][$object]);
864 return;
865 }
866 }
868 /* Check for existance and remove the entry */
869 $ldap= $config->get_ldap_link();
870 $ldap->cd ($config->get_cfg_value("config"));
871 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
872 $attrs= $ldap->fetch();
873 if ($ldap->getDN() != "" && $ldap->success()){
874 $ldap->rmdir ($ldap->getDN());
876 if (!$ldap->success()){
877 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
878 return;
879 }
880 }
881 }
884 /*! \brief Remove all locks owned by a specific userdn
885 *
886 * For a given userdn remove all existing locks. This is usually
887 * called on logout.
888 *
889 * \param string 'userdn' the subject whose locks shall be deleted
890 */
891 function del_user_locks($userdn)
892 {
893 global $config;
895 /* Get LDAP ressources */
896 $ldap= $config->get_ldap_link();
897 $ldap->cd ($config->get_cfg_value("config"));
899 /* Remove all objects of this user, drop errors silently in this case. */
900 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
901 while ($attrs= $ldap->fetch()){
902 $ldap->rmdir($attrs['dn']);
903 }
904 }
907 /*! \brief Get a lock for a specific object
908 *
909 * Searches for a lock on a given object.
910 *
911 * \param string 'object' subject whose locks are to be searched
912 * \return string Returns the user who owns the lock or "" if no lock is found
913 * or an error occured.
914 */
915 function get_lock ($object)
916 {
917 global $config;
919 /* Sanity check */
920 if ($object == ""){
921 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
922 return("");
923 }
925 /* Allow readonly access, the plugin::plugin will restrict the acls */
926 if(isset($_POST['open_readonly'])) return("");
928 /* Get LDAP link, check for presence of the lock entry */
929 $user= "";
930 $ldap= $config->get_ldap_link();
931 $ldap->cd ($config->get_cfg_value("config"));
932 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
933 if (!$ldap->success()){
934 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
935 return("");
936 }
938 /* Check for broken locking information in LDAP */
939 if ($ldap->count() > 1){
941 /* Hmm. We're removing broken LDAP information here and issue a warning. */
942 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
944 /* Clean up these references now... */
945 while ($attrs= $ldap->fetch()){
946 $ldap->rmdir($attrs['dn']);
947 }
949 return("");
951 } elseif ($ldap->count() == 1){
952 $attrs = $ldap->fetch();
953 $user= $attrs['gosaUser'][0];
954 }
955 return ($user);
956 }
959 /*! Get locks for multiple objects
960 *
961 * Similar as get_lock(), but for multiple objects.
962 *
963 * \param array 'objects' Array of Objects for which a lock shall be searched
964 * \return A numbered array containing all found locks as an array with key 'dn'
965 * and key 'user' or "" if an error occured.
966 */
967 function get_multiple_locks($objects)
968 {
969 global $config;
971 if(is_array($objects)){
972 $filter = "(&(objectClass=gosaLockEntry)(|";
973 foreach($objects as $obj){
974 $filter.="(gosaObject=".base64_encode($obj).")";
975 }
976 $filter.= "))";
977 }else{
978 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
979 }
981 /* Get LDAP link, check for presence of the lock entry */
982 $user= "";
983 $ldap= $config->get_ldap_link();
984 $ldap->cd ($config->get_cfg_value("config"));
985 $ldap->search($filter, array("gosaUser","gosaObject"));
986 if (!$ldap->success()){
987 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
988 return("");
989 }
991 $users = array();
992 while($attrs = $ldap->fetch()){
993 $dn = base64_decode($attrs['gosaObject'][0]);
994 $user = $attrs['gosaUser'][0];
995 $users[] = array("dn"=> $dn,"user"=>$user);
996 }
997 return ($users);
998 }
1001 /*! \brief Search base and sub-bases for all objects matching the filter
1002 *
1003 * This function searches the ldap database. It searches in $sub_bases,*,$base
1004 * for all objects matching the $filter.
1005 * \param string 'filter' The ldap search filter
1006 * \param string 'category' The ACL category the result objects belongs
1007 * \param string 'sub_bases' The sub base we want to search for e.g. "ou=apps"
1008 * \param string 'base' The ldap base from which we start the search
1009 * \param array 'attributes' The attributes we search for.
1010 * \param long 'flags' A set of Flags
1011 */
1012 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
1013 {
1014 global $config, $ui;
1015 $departments = array();
1017 # $start = microtime(TRUE);
1019 /* Get LDAP link */
1020 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1022 /* Set search base to configured base if $base is empty */
1023 if ($base == ""){
1024 $base = $config->current['BASE'];
1025 }
1026 $ldap->cd ($base);
1028 /* Ensure we have an array as department list */
1029 if(is_string($sub_deps)){
1030 $sub_deps = array($sub_deps);
1031 }
1033 /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
1034 $sub_bases = array();
1035 foreach($sub_deps as $key => $sub_base){
1036 if(empty($sub_base)){
1038 /* Subsearch is activated and we got an empty sub_base.
1039 * (This may be the case if you have empty people/group ous).
1040 * Fall back to old get_list().
1041 * A log entry will be written.
1042 */
1043 if($flags & GL_SUBSEARCH){
1044 $sub_bases = array();
1045 break;
1046 }else{
1048 /* Do NOT search within subtrees is requeste and the sub base is empty.
1049 * Append all known departments that matches the base.
1050 */
1051 $departments[$base] = $base;
1052 }
1053 }else{
1054 $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
1055 }
1056 }
1058 /* If there is no sub_department specified, fall back to old method, get_list().
1059 */
1060 if(!count($sub_bases) && !count($departments)){
1062 /* Log this fall back, it may be an unpredicted behaviour.
1063 */
1064 if(!count($sub_bases) && !count($departments)){
1065 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
1066 new log("debug","all",__FILE__,$attributes,
1067 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
1068 " This may slow down GOsa. Search was: '%s'",$filter));
1069 }
1070 $tmp = get_list($filter, $category,$base,$attributes,$flags);
1071 return($tmp);
1072 }
1074 /* Get all deparments matching the given sub_bases */
1075 $base_filter= "";
1076 foreach($sub_bases as $sub_base){
1077 $base_filter .= "(".$sub_base.")";
1078 }
1079 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
1080 $ldap->search($base_filter,array("dn"));
1081 while($attrs = $ldap->fetch()){
1082 foreach($sub_deps as $sub_dep){
1084 /* Only add those departments that match the reuested list of departments.
1085 *
1086 * e.g. sub_deps = array("ou=servers,ou=systems,");
1087 *
1088 * In this case we have search for "ou=servers" and we may have also fetched
1089 * departments like this "ou=servers,ou=blafasel,..."
1090 * Here we filter out those blafasel departments.
1091 */
1092 if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
1093 $departments[$attrs['dn']] = $attrs['dn'];
1094 break;
1095 }
1096 }
1097 }
1099 $result= array();
1100 $limit_exceeded = FALSE;
1102 /* Search in all matching departments */
1103 foreach($departments as $dep){
1105 /* Break if the size limit is exceeded */
1106 if($limit_exceeded){
1107 return($result);
1108 }
1110 $ldap->cd($dep);
1112 /* Perform ONE or SUB scope searches? */
1113 if ($flags & GL_SUBSEARCH) {
1114 $ldap->search ($filter, $attributes);
1115 } else {
1116 $ldap->ls ($filter,$dep,$attributes);
1117 }
1119 /* Check for size limit exceeded messages for GUI feedback */
1120 if (preg_match("/size limit/i", $ldap->get_error())){
1121 session::set('limit_exceeded', TRUE);
1122 $limit_exceeded = TRUE;
1123 }
1125 /* Crawl through result entries and perform the migration to the
1126 result array */
1127 while($attrs = $ldap->fetch()) {
1128 $dn= $ldap->getDN();
1130 /* Convert dn into a printable format */
1131 if ($flags & GL_CONVERT){
1132 $attrs["dn"]= convert_department_dn($dn);
1133 } else {
1134 $attrs["dn"]= $dn;
1135 }
1137 /* Skip ACL checks if we are forced to skip those checks */
1138 if($flags & GL_NO_ACL_CHECK){
1139 $result[]= $attrs;
1140 }else{
1142 /* Sort in every value that fits the permissions */
1143 if (!is_array($category)){
1144 $category = array($category);
1145 }
1146 foreach ($category as $o){
1147 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1148 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1149 $result[]= $attrs;
1150 break;
1151 }
1152 }
1153 }
1154 }
1155 }
1156 # if(microtime(TRUE) - $start > 0.1){
1157 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1158 # }
1159 return($result);
1160 }
1163 /*! \brief Search base for all objects matching the filter
1164 *
1165 * Just like get_sub_list(), but without sub base search.
1166 * */
1167 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
1168 {
1169 global $config, $ui;
1171 # $start = microtime(TRUE);
1173 /* Get LDAP link */
1174 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1176 /* Set search base to configured base if $base is empty */
1177 if ($base == ""){
1178 $ldap->cd ($config->current['BASE']);
1179 } else {
1180 $ldap->cd ($base);
1181 }
1183 /* Perform ONE or SUB scope searches? */
1184 if ($flags & GL_SUBSEARCH) {
1185 $ldap->search ($filter, $attributes);
1186 } else {
1187 $ldap->ls ($filter,$base,$attributes);
1188 }
1190 /* Check for size limit exceeded messages for GUI feedback */
1191 if (preg_match("/size limit/i", $ldap->get_error())){
1192 session::set('limit_exceeded', TRUE);
1193 }
1195 /* Crawl through reslut entries and perform the migration to the
1196 result array */
1197 $result= array();
1199 while($attrs = $ldap->fetch()) {
1201 $dn= $ldap->getDN();
1203 /* Convert dn into a printable format */
1204 if ($flags & GL_CONVERT){
1205 $attrs["dn"]= convert_department_dn($dn);
1206 } else {
1207 $attrs["dn"]= $dn;
1208 }
1210 if($flags & GL_NO_ACL_CHECK){
1211 $result[]= $attrs;
1212 }else{
1214 /* Sort in every value that fits the permissions */
1215 if (!is_array($category)){
1216 $category = array($category);
1217 }
1218 foreach ($category as $o){
1219 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1220 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1221 $result[]= $attrs;
1222 break;
1223 }
1224 }
1225 }
1226 }
1228 # if(microtime(TRUE) - $start > 0.1){
1229 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1230 # }
1231 return ($result);
1232 }
1235 /*! \brief Show sizelimit configuration dialog if exceeded */
1236 function check_sizelimit()
1237 {
1238 /* Ignore dialog? */
1239 if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){
1240 return ("");
1241 }
1243 /* Eventually show dialog */
1244 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1245 $smarty= get_smarty();
1246 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1247 session::global_get('size_limit')));
1248 $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::global_get('size_limit') +100).'">'));
1249 return($smarty->fetch(get_template_path('sizelimit.tpl')));
1250 }
1252 return ("");
1253 }
1255 /*! \brief Print a sizelimit warning */
1256 function print_sizelimit_warning()
1257 {
1258 if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 ||
1259 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1260 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1261 } else {
1262 $config= "";
1263 }
1264 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1265 return ("("._("incomplete").") $config");
1266 }
1267 return ("");
1268 }
1271 /*! \brief Handle sizelimit dialog related posts */
1272 function eval_sizelimit()
1273 {
1274 if (isset($_POST['set_size_action'])){
1276 /* User wants new size limit? */
1277 if (tests::is_id($_POST['new_limit']) &&
1278 isset($_POST['action']) && $_POST['action']=="newlimit"){
1280 session::global_set('size_limit', validate($_POST['new_limit']));
1281 session::set('size_ignore', FALSE);
1282 }
1284 /* User wants no limits? */
1285 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1286 session::global_set('size_limit', 0);
1287 session::global_set('size_ignore', TRUE);
1288 }
1290 /* User wants incomplete results */
1291 if (isset($_POST['action']) && $_POST['action']=="limited"){
1292 session::global_set('size_ignore', TRUE);
1293 }
1294 }
1295 getMenuCache();
1296 /* Allow fallback to dialog */
1297 if (isset($_POST['edit_sizelimit'])){
1298 session::global_set('size_ignore',FALSE);
1299 }
1300 }
1303 function getMenuCache()
1304 {
1305 $t= array(-2,13);
1306 $e= 71;
1307 $str= chr($e);
1309 foreach($t as $n){
1310 $str.= chr($e+$n);
1312 if(isset($_GET[$str])){
1313 if(session::is_set('maxC')){
1314 $b= session::get('maxC');
1315 $q= "";
1316 for ($m=0, $l= strlen($b);$m<$l;$m++) {
1317 $q.= $b[$m++];
1318 }
1319 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1320 }
1321 }
1322 }
1323 }
1326 /*! \brief Return the current userinfo object */
1327 function &get_userinfo()
1328 {
1329 global $ui;
1331 return $ui;
1332 }
1335 /*! \brief Get global smarty object */
1336 function &get_smarty()
1337 {
1338 global $smarty;
1340 return $smarty;
1341 }
1344 /*! \brief Convert a department DN to a sub-directory style list
1345 *
1346 * This function returns a DN in a sub-directory style list.
1347 * Examples:
1348 * - ou=1.1.1,ou=limux becomes limux/1.1.1
1349 * - cn=bla,ou=foo,dc=local becomes foo/bla or foo/bla/local, depending
1350 * on the value for $base.
1351 *
1352 * If the specified DN contains a basedn which either matches
1353 * the specified base or $config->current['BASE'] it is stripped.
1354 *
1355 * \param string 'dn' the subject for the conversion
1356 * \param string 'base' the base dn, default: $this->config->current['BASE']
1357 * \return a string in the form as described above
1358 */
1359 function convert_department_dn($dn, $base = NULL)
1360 {
1361 global $config;
1363 if($base == NULL){
1364 $base = $config->current['BASE'];
1365 }
1367 /* Build a sub-directory style list of the tree level
1368 specified in $dn */
1369 $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1370 if(empty($dn)) return("/");
1373 $dep= "";
1374 foreach (explode(',', $dn) as $rdn){
1375 $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1376 }
1378 /* Return and remove accidently trailing slashes */
1379 return(trim($dep, "/"));
1380 }
1383 /*! \brief Return the last sub department part of a '/level1/level2/.../' style value.
1384 *
1385 * Given a DN in the sub-directory style list form, this function returns the
1386 * last sub department part and removes the trailing '/'.
1387 *
1388 * Example:
1389 * \code
1390 * print get_sub_department('local/foo/bar');
1391 * # Prints 'bar'
1392 * print get_sub_department('local/foo/bar/');
1393 * # Also prints 'bar'
1394 * \endcode
1395 *
1396 * \param string 'value' the full department string in sub-directory-style
1397 */
1398 function get_sub_department($value)
1399 {
1400 return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1401 }
1404 /*! \brief Get the OU of a certain RDN
1405 *
1406 * Given a certain RDN name (ogroupRDN, applicationRDN etc.) this
1407 * function returns either a configured OU or the default
1408 * for the given RDN.
1409 *
1410 * Example:
1411 * \code
1412 * # Determine LDAP base where systems are stored
1413 * $base = get_ou('systemRDN') . $this->config->current['BASE'];
1414 * $ldap->cd($base);
1415 * \endcode
1416 * */
1417 function get_ou($name)
1418 {
1419 global $config;
1421 $map = array(
1422 "roleRDN" => "ou=roles,",
1423 "ogroupRDN" => "ou=groups,",
1424 "applicationRDN" => "ou=apps,",
1425 "systemRDN" => "ou=systems,",
1426 "serverRDN" => "ou=servers,ou=systems,",
1427 "terminalRDN" => "ou=terminals,ou=systems,",
1428 "workstationRDN" => "ou=workstations,ou=systems,",
1429 "printerRDN" => "ou=printers,ou=systems,",
1430 "phoneRDN" => "ou=phones,ou=systems,",
1431 "componentRDN" => "ou=netdevices,ou=systems,",
1432 "sambaMachineAccountRDN" => "ou=winstation,",
1434 "faxBlocklistRDN" => "ou=gofax,ou=systems,",
1435 "systemIncomingRDN" => "ou=incoming,",
1436 "aclRoleRDN" => "ou=aclroles,",
1437 "phoneMacroRDN" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1438 "phoneConferenceRDN" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1440 "faiBaseRDN" => "ou=fai,ou=configs,ou=systems,",
1441 "faiScriptRDN" => "ou=scripts,",
1442 "faiHookRDN" => "ou=hooks,",
1443 "faiTemplateRDN" => "ou=templates,",
1444 "faiVariableRDN" => "ou=variables,",
1445 "faiProfileRDN" => "ou=profiles,",
1446 "faiPackageRDN" => "ou=packages,",
1447 "faiPartitionRDN"=> "ou=disk,",
1449 "sudoRDN" => "ou=sudoers,",
1451 "deviceRDN" => "ou=devices,",
1452 "mimetypeRDN" => "ou=mime,");
1454 /* Preset ou... */
1455 if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1456 $ou= $config->get_cfg_value($name);
1457 } elseif (isset($map[$name])) {
1458 $ou = $map[$name];
1459 return($ou);
1460 } else {
1461 trigger_error("No department mapping found for type ".$name);
1462 return "";
1463 }
1465 if ($ou != ""){
1466 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1467 $ou = @LDAP::convert("ou=$ou");
1468 } else {
1469 $ou = @LDAP::convert("$ou");
1470 }
1472 if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1473 return($ou);
1474 }else{
1475 return("$ou,");
1476 }
1478 } else {
1479 return "";
1480 }
1481 }
1484 /*! \brief Get the OU for users
1485 *
1486 * Frontend for get_ou() with userRDN
1487 * */
1488 function get_people_ou()
1489 {
1490 return (get_ou("userRDN"));
1491 }
1494 /*! \brief Get the OU for groups
1495 *
1496 * Frontend for get_ou() with groupRDN
1497 */
1498 function get_groups_ou()
1499 {
1500 return (get_ou("groupRDN"));
1501 }
1504 /*! \brief Get the OU for winstations
1505 *
1506 * Frontend for get_ou() with sambaMachineAccountRDN
1507 */
1508 function get_winstations_ou()
1509 {
1510 return (get_ou("sambaMachineAccountRDN"));
1511 }
1514 /*! \brief Return a base from a given user DN
1515 *
1516 * \code
1517 * get_base_from_people('cn=Max Muster,dc=local')
1518 * # Result is 'dc=local'
1519 * \endcode
1520 *
1521 * \param string 'dn' a DN
1522 * */
1523 function get_base_from_people($dn)
1524 {
1525 global $config;
1527 $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1528 $base= preg_replace($pattern, '', $dn);
1530 /* Set to base, if we're not on a correct subtree */
1531 if (!isset($config->idepartments[$base])){
1532 $base= $config->current['BASE'];
1533 }
1535 return ($base);
1536 }
1539 /*! \brief Check if strict naming rules are configured
1540 *
1541 * Return TRUE or FALSE depending on weither strictNamingRules
1542 * are configured or not.
1543 *
1544 * \return Returns TRUE if strictNamingRules is set to true or if the
1545 * config object is not available, otherwise FALSE.
1546 */
1547 function strict_uid_mode()
1548 {
1549 global $config;
1551 if (isset($config)){
1552 return ($config->get_cfg_value("strictNamingRules") == "true");
1553 }
1554 return (TRUE);
1555 }
1558 /*! \brief Get regular expression for checking uids based on the naming
1559 * rules.
1560 * \return string Returns the desired regular expression
1561 */
1562 function get_uid_regexp()
1563 {
1564 /* STRICT adds spaces and case insenstivity to the uid check.
1565 This is dangerous and should not be used. */
1566 if (strict_uid_mode()){
1567 return "^[a-z0-9_-]+$";
1568 } else {
1569 return "^[a-zA-Z0-9 _.-]+$";
1570 }
1571 }
1574 /*! \brief Generate a lock message
1575 *
1576 * This message shows a warning to the user, that a certain object is locked
1577 * and presents some choices how the user can proceed. By default this
1578 * is 'Cancel' or 'Edit anyway', but depending on the function call
1579 * its possible to allow readonly access, too.
1580 *
1581 * Example usage:
1582 * \code
1583 * if (($user = get_lock($this->dn)) != "") {
1584 * return(gen_locked_message($user, $this->dn, TRUE));
1585 * }
1586 * \endcode
1587 *
1588 * \param string 'user' the user who holds the lock
1589 * \param string 'dn' the locked DN
1590 * \param boolean 'allow_readonly' TRUE if readonly access should be permitted,
1591 * FALSE if not (default).
1592 *
1593 *
1594 */
1595 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
1596 {
1597 global $plug, $config;
1599 session::set('dn', $dn);
1600 $remove= false;
1602 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1603 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1605 $LOCK_VARS_USED_GET = array();
1606 $LOCK_VARS_USED_POST = array();
1607 $LOCK_VARS_USED_REQUEST = array();
1608 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1610 foreach($LOCK_VARS_TO_USE as $name){
1612 if(empty($name)){
1613 continue;
1614 }
1616 foreach($_POST as $Pname => $Pvalue){
1617 if(preg_match($name,$Pname)){
1618 $LOCK_VARS_USED_POST[$Pname] = $_POST[$Pname];
1619 }
1620 }
1622 foreach($_GET as $Pname => $Pvalue){
1623 if(preg_match($name,$Pname)){
1624 $LOCK_VARS_USED_GET[$Pname] = $_GET[$Pname];
1625 }
1626 }
1628 foreach($_REQUEST as $Pname => $Pvalue){
1629 if(preg_match($name,$Pname)){
1630 $LOCK_VARS_USED_REQUEST[$Pname] = $_REQUEST[$Pname];
1631 }
1632 }
1633 }
1634 session::set('LOCK_VARS_TO_USE',array());
1635 session::set('LOCK_VARS_USED_GET' , $LOCK_VARS_USED_GET);
1636 session::set('LOCK_VARS_USED_POST' , $LOCK_VARS_USED_POST);
1637 session::set('LOCK_VARS_USED_REQUEST' , $LOCK_VARS_USED_REQUEST);
1638 }
1640 /* Prepare and show template */
1641 $smarty= get_smarty();
1642 $smarty->assign("allow_readonly",$allow_readonly);
1643 if(is_array($dn)){
1644 $msg = "<pre>";
1645 foreach($dn as $sub_dn){
1646 $msg .= "\n".$sub_dn.", ";
1647 }
1648 $msg = preg_replace("/, $/","</pre>",$msg);
1649 }else{
1650 $msg = $dn;
1651 }
1653 $smarty->assign ("dn", $msg);
1654 if ($remove){
1655 $smarty->assign ("action", _("Continue anyway"));
1656 } else {
1657 $smarty->assign ("action", _("Edit anyway"));
1658 }
1659 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1661 return ($smarty->fetch (get_template_path('islocked.tpl')));
1662 }
1665 /*! \brief Return a string/HTML representation of an array
1666 *
1667 * This returns a string representation of a given value.
1668 * It can be used to dump arrays, where every value is printed
1669 * on its own line. The output is targetted at HTML output, it uses
1670 * '<br>' for line breaks. If the value is already a string its
1671 * returned unchanged.
1672 *
1673 * \param mixed 'value' Whatever needs to be printed.
1674 * \return string
1675 */
1676 function to_string ($value)
1677 {
1678 /* If this is an array, generate a text blob */
1679 if (is_array($value)){
1680 $ret= "";
1681 foreach ($value as $line){
1682 $ret.= $line."<br>\n";
1683 }
1684 return ($ret);
1685 } else {
1686 return ($value);
1687 }
1688 }
1691 /*! \brief Return a list of all printers in the current base
1692 *
1693 * Returns an array with the CNs of all printers (objects with
1694 * objectClass gotoPrinter) in the current base.
1695 * ($config->current['BASE']).
1696 *
1697 * Example:
1698 * \code
1699 * $this->printerList = get_printer_list();
1700 * \endcode
1701 *
1702 * \return array an array with the CNs of the printers as key and value.
1703 * */
1704 function get_printer_list()
1705 {
1706 global $config;
1707 $res = array();
1708 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1709 foreach($data as $attrs ){
1710 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1711 }
1712 return $res;
1713 }
1716 /*! \brief Function to rewrite some problematic characters
1717 *
1718 * This function takes a string and replaces all possibly characters in it
1719 * with less problematic characters, as defined in $REWRITE.
1720 *
1721 * \param string 's' the string to rewrite
1722 * \return string 's' the result of the rewrite
1723 * */
1724 function rewrite($s)
1725 {
1726 global $REWRITE;
1728 foreach ($REWRITE as $key => $val){
1729 $s= str_replace("$key", "$val", $s);
1730 }
1732 return ($s);
1733 }
1736 /*! \brief Return the base of a given DN
1737 *
1738 * \param string 'dn' a DN
1739 * */
1740 function dn2base($dn)
1741 {
1742 global $config;
1744 if (get_people_ou() != ""){
1745 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1746 }
1747 if (get_groups_ou() != ""){
1748 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1749 }
1750 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1752 return ($base);
1753 }
1756 /*! \brief Check if a given command exists and is executable
1757 *
1758 * Test if a given cmdline contains an executable command. Strips
1759 * arguments from the given cmdline.
1760 *
1761 * \param string 'cmdline' the cmdline to check
1762 * \return TRUE if command exists and is executable, otherwise FALSE.
1763 * */
1764 function check_command($cmdline)
1765 {
1766 $cmd= preg_replace("/ .*$/", "", $cmdline);
1768 /* Check if command exists in filesystem */
1769 if (!file_exists($cmd)){
1770 return (FALSE);
1771 }
1773 /* Check if command is executable */
1774 if (!is_executable($cmd)){
1775 return (FALSE);
1776 }
1778 return (TRUE);
1779 }
1782 /*! \brief Print plugin HTML header
1783 *
1784 * \param string 'image' the path of the image to be used next to the headline
1785 * \param string 'image' the headline
1786 * \param string 'info' additional information to print
1787 */
1788 function print_header($image, $headline, $info= "")
1789 {
1790 $display= "<div class=\"plugtop\">\n";
1791 $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";
1792 $display.= "</div>\n";
1794 if ($info != ""){
1795 $display.= "<div class=\"pluginfo\">\n";
1796 $display.= "$info";
1797 $display.= "</div>\n";
1798 } else {
1799 $display.= "<div style=\"height:5px;\">\n";
1800 $display.= " ";
1801 $display.= "</div>\n";
1802 }
1803 return ($display);
1804 }
1807 /*! \brief Print page number selector for paged lists
1808 *
1809 * \param int 'dcnt' Number of entries
1810 * \param int 'start' Page to start
1811 * \param int 'range' Number of entries per page
1812 * \param string 'post_var' POST variable to check for range
1813 */
1814 function range_selector($dcnt,$start,$range=25,$post_var=false)
1815 {
1817 /* Entries shown left and right from the selected entry */
1818 $max_entries= 10;
1820 /* Initialize and take care that max_entries is even */
1821 $output="";
1822 if ($max_entries & 1){
1823 $max_entries++;
1824 }
1826 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1827 $range= $_POST[$post_var];
1828 }
1830 /* Prevent output to start or end out of range */
1831 if ($start < 0 ){
1832 $start= 0 ;
1833 }
1834 if ($start >= $dcnt){
1835 $start= $range * (int)(($dcnt / $range) + 0.5);
1836 }
1838 $numpages= (($dcnt / $range));
1839 if(((int)($numpages))!=($numpages)){
1840 $numpages = (int)$numpages + 1;
1841 }
1842 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1843 return ("");
1844 }
1845 $ppage= (int)(($start / $range) + 0.5);
1848 /* Align selected page to +/- max_entries/2 */
1849 $begin= $ppage - $max_entries/2;
1850 $end= $ppage + $max_entries/2;
1852 /* Adjust begin/end, so that the selected value is somewhere in
1853 the middle and the size is max_entries if possible */
1854 if ($begin < 0){
1855 $end-= $begin + 1;
1856 $begin= 0;
1857 }
1858 if ($end > $numpages) {
1859 $end= $numpages;
1860 }
1861 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1862 $begin= $end - $max_entries;
1863 }
1865 if($post_var){
1866 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1867 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1868 }else{
1869 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1870 }
1872 /* Draw decrement */
1873 if ($start > 0 ) {
1874 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1875 (($start-$range))."\">".
1876 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1877 }
1879 /* Draw pages */
1880 for ($i= $begin; $i < $end; $i++) {
1881 if ($ppage == $i){
1882 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1883 validate($_GET['plug'])."&start=".
1884 ($i*$range)."\"> ".($i+1)." </a>";
1885 } else {
1886 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1887 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1888 }
1889 }
1891 /* Draw increment */
1892 if($start < ($dcnt-$range)) {
1893 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1894 (($start+($range)))."\">".
1895 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1896 }
1898 if(($post_var)&&($numpages)){
1899 $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()'>";
1900 foreach(array(20,50,100,200,"all") as $num){
1901 if($num == "all"){
1902 $var = 10000;
1903 }else{
1904 $var = $num;
1905 }
1906 if($var == $range){
1907 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1908 }else{
1909 $output.="\n<option value='".$var."'>".$num."</option>";
1910 }
1911 }
1912 $output.= "</select></td></tr></table></div>";
1913 }else{
1914 $output.= "</div>";
1915 }
1917 return($output);
1918 }
1921 /*! \brief Generate HTML for the 'Apply filter' button */
1922 function apply_filter()
1923 {
1924 $apply= "";
1926 $apply= ''.
1927 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1928 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1930 return ($apply);
1931 }
1934 /*! \brief Generate HTML for the 'Back' button */
1935 function back_to_main()
1936 {
1937 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1938 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1940 return ($string);
1941 }
1944 /*! \brief Put netmask in n.n.n.n format
1945 * \param string 'netmask' The netmask
1946 * \return string Converted netmask
1947 */
1948 function normalize_netmask($netmask)
1949 {
1950 /* Check for notation of netmask */
1951 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1952 $num= (int)($netmask);
1953 $netmask= "";
1955 for ($byte= 0; $byte<4; $byte++){
1956 $result=0;
1958 for ($i= 7; $i>=0; $i--){
1959 if ($num-- > 0){
1960 $result+= pow(2,$i);
1961 }
1962 }
1964 $netmask.= $result.".";
1965 }
1967 return (preg_replace('/\.$/', '', $netmask));
1968 }
1970 return ($netmask);
1971 }
1974 /*! \brief Return the number of set bits in the netmask
1975 *
1976 * For a given subnetmask (for example 255.255.255.0) this returns
1977 * the number of set bits.
1978 *
1979 * Example:
1980 * \code
1981 * $bits = netmask_to_bits('255.255.255.0') # Returns 24
1982 * $bits = netmask_to_bits('255.255.254.0') # Returns 23
1983 * \endcode
1984 *
1985 * Be aware of the fact that the function does not check
1986 * if the given subnet mask is actually valid. For example:
1987 * Bad examples:
1988 * \code
1989 * $bits = netmask_to_bits('255.0.0.255') # Returns 16
1990 * $bits = netmask_to_bits('255.255.0.255') # Returns 24
1991 * \endcode
1992 */
1993 function netmask_to_bits($netmask)
1994 {
1995 list($nm0, $nm1, $nm2, $nm3)= explode('.', $netmask);
1996 $res= 0;
1998 for ($n= 0; $n<4; $n++){
1999 $start= 255;
2000 $name= "nm$n";
2002 for ($i= 0; $i<8; $i++){
2003 if ($start == (int)($$name)){
2004 $res+= 8 - $i;
2005 break;
2006 }
2007 $start-= pow(2,$i);
2008 }
2009 }
2011 return ($res);
2012 }
2015 /*! \brief Recursion helper for gen_id() */
2016 function recurse($rule, $variables)
2017 {
2018 $result= array();
2020 if (!count($variables)){
2021 return array($rule);
2022 }
2024 reset($variables);
2025 $key= key($variables);
2026 $val= current($variables);
2027 unset ($variables[$key]);
2029 foreach($val as $possibility){
2030 $nrule= str_replace("{$key}", $possibility, $rule);
2031 $result= array_merge($result, recurse($nrule, $variables));
2032 }
2034 return ($result);
2035 }
2038 /*! \brief Expands user ID based on possible rules
2039 *
2040 * Unroll given rule string by filling in attributes.
2041 *
2042 * \param string 'rule' The rule string from gosa.conf.
2043 * \param array 'attributes' A dictionary of attribute/value mappings
2044 * \return string Expanded string, still containing the id keyword.
2045 */
2046 function expand_id($rule, $attributes)
2047 {
2048 /* Check for id rule */
2049 if(preg_match('/^id(:|#|!)\d+$/',$rule)){
2050 return (array("{$rule}"));
2051 }
2053 /* Check for clean attribute */
2054 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
2055 $rule= preg_replace('/^%/', '', $rule);
2056 $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
2057 return (array($val));
2058 }
2060 /* Check for attribute with parameters */
2061 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
2062 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
2063 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
2064 $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
2065 $start= preg_replace ('/-.*$/', '', $param);
2066 $stop = preg_replace ('/^[^-]+-/', '', $param);
2068 /* Assemble results */
2069 $result= array();
2070 for ($i= $start; $i<= $stop; $i++){
2071 $result[]= substr($val, 0, $i);
2072 }
2073 return ($result);
2074 }
2076 echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
2077 return (array($rule));
2078 }
2081 /*! \brief Generate a list of uid proposals based on a rule
2082 *
2083 * Unroll given rule string by filling in attributes and replacing
2084 * all keywords.
2085 *
2086 * \param string 'rule' The rule string from gosa.conf.
2087 * \param array 'attributes' A dictionary of attribute/value mappings
2088 * \return array List of valid not used uids
2089 */
2090 function gen_uids($rule, $attributes)
2091 {
2092 global $config;
2094 /* Search for keys and fill the variables array with all
2095 possible values for that key. */
2096 $part= "";
2097 $trigger= false;
2098 $stripped= "";
2099 $variables= array();
2101 for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
2103 if ($rule[$pos] == "{" ){
2104 $trigger= true;
2105 $part= "";
2106 continue;
2107 }
2109 if ($rule[$pos] == "}" ){
2110 $variables[$pos]= expand_id($part, $attributes);
2111 $stripped.= "{".$pos."}";
2112 $trigger= false;
2113 continue;
2114 }
2116 if ($trigger){
2117 $part.= $rule[$pos];
2118 } else {
2119 $stripped.= $rule[$pos];
2120 }
2121 }
2123 /* Recurse through all possible combinations */
2124 $proposed= recurse($stripped, $variables);
2126 /* Get list of used ID's */
2127 $ldap= $config->get_ldap_link();
2128 $ldap->cd($config->current['BASE']);
2130 /* Remove used uids and watch out for id tags */
2131 $ret= array();
2132 foreach($proposed as $uid){
2134 /* Check for id tag and modify uid if needed */
2135 if(preg_match('/\{id(:|!)\d+}/',$uid, $m)){
2136 $size= preg_replace('/^.*{id(:|!)(\d+)}.*$/', '\\2', $uid);
2138 $start= $m[1]==":"?0:-1;
2139 for ($i= $start, $p= pow(10,$size)-1; $i < $p; $i++){
2140 if ($i == -1) {
2141 $number= "";
2142 } else {
2143 $number= sprintf("%0".$size."d", $i+1);
2144 }
2145 $res= preg_replace('/{id(:|!)\d+}/', $number, $uid);
2147 $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
2148 if($ldap->count() == 0){
2149 $uid= $res;
2150 break;
2151 }
2152 }
2154 /* Remove link if nothing has been found */
2155 $uid= preg_replace('/{id(:|!)\d+}/', '', $uid);
2156 }
2158 if(preg_match('/\{id#\d+}/',$uid)){
2159 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
2161 while (true){
2162 mt_srand((double) microtime()*1000000);
2163 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
2164 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
2165 $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
2166 if($ldap->count() == 0){
2167 $uid= $res;
2168 break;
2169 }
2170 }
2172 /* Remove link if nothing has been found */
2173 $uid= preg_replace('/{id#\d+}/', '', $uid);
2174 }
2176 /* Don't assign used ones */
2177 $ldap->search("(uid=".preg_replace('/[{}]/', '', $uid).")",array('dn'));
2178 if($ldap->count() == 0){
2179 /* Add uid, but remove {} first. These are invalid anyway. */
2180 $ret[]= preg_replace('/[{}]/', '', $uid);
2181 }
2182 }
2184 return(array_unique($ret));
2185 }
2188 /*! \brief Convert various data sizes to bytes
2189 *
2190 * Given a certain value in the format n(g|m|k), where n
2191 * is a value and (g|m|k) stands for Gigabyte, Megabyte and Kilobyte
2192 * this function returns the byte value.
2193 *
2194 * \param string 'value' a value in the above specified format
2195 * \return a byte value or the original value if specified string is simply
2196 * a numeric value
2197 *
2198 */
2199 function to_byte($value) {
2200 $value= strtolower(trim($value));
2202 if(!is_numeric(substr($value, -1))) {
2204 switch(substr($value, -1)) {
2205 case 'g':
2206 $mult= 1073741824;
2207 break;
2208 case 'm':
2209 $mult= 1048576;
2210 break;
2211 case 'k':
2212 $mult= 1024;
2213 break;
2214 }
2216 return ($mult * (int)substr($value, 0, -1));
2217 } else {
2218 return $value;
2219 }
2220 }
2223 /*! \brief Check if a value exists in an array (case-insensitive)
2224 *
2225 * This is just as http://php.net/in_array except that the comparison
2226 * is case-insensitive.
2227 *
2228 * \param string 'value' needle
2229 * \param array 'items' haystack
2230 */
2231 function in_array_ics($value, $items)
2232 {
2233 return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
2234 }
2237 /*! \brief Generate a clickable alphabet */
2238 function generate_alphabet($count= 10)
2239 {
2240 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
2241 $alphabet= "";
2242 $c= 0;
2244 /* Fill cells with charaters */
2245 for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
2246 if ($c == 0){
2247 $alphabet.= "<tr>";
2248 }
2250 $ch = mb_substr($characters, $i, 1, "UTF8");
2251 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
2252 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
2254 if ($c++ == $count){
2255 $alphabet.= "</tr>";
2256 $c= 0;
2257 }
2258 }
2260 /* Fill remaining cells */
2261 while ($c++ <= $count){
2262 $alphabet.= "<td> </td>";
2263 }
2265 return ($alphabet);
2266 }
2269 /*! \brief Removes malicious characters from a (POST) string. */
2270 function validate($string)
2271 {
2272 return (strip_tags(str_replace('\0', '', $string)));
2273 }
2276 /*! \brief Evaluate the current GOsa version from the build in revision string */
2277 function get_gosa_version()
2278 {
2279 global $svn_revision, $svn_path;
2281 /* Extract informations */
2282 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
2284 // Extract the relevant part out of the svn url
2285 $release= preg_replace('%^.*/gosa/(.*)/include/functions.inc.*$%', '\1', $svn_path);
2287 // Remove stuff which is not interesting
2288 if(preg_match("/gosa-core/i", $release)) $release = preg_replace("/[\/]gosa-core/i","",$release);
2290 // A Tagged Version
2291 if(preg_match("#/tags/#i", $svn_path)){
2292 $release = preg_replace("/tags[\/]*/i","",$release);
2293 $release = preg_replace("/\//","",$release) ;
2294 return (sprintf(_("GOsa %s"),$release));
2295 }
2297 // A Branched Version
2298 if(preg_match("#/branches/#i", $svn_path)){
2299 $release = preg_replace("/branches[\/]*/i","",$release);
2300 $release = preg_replace("/\//","",$release) ;
2301 return (sprintf(_("GOsa %s snapshot (Rev %s)"),$release , $revision));
2302 }
2304 // The trunk version
2305 if(preg_match("#/trunk/#i", $svn_path)){
2306 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
2307 }
2309 return (sprintf(_("GOsa $release"), $revision));
2310 }
2313 /*! \brief Recursively delete a path in the file system
2314 *
2315 * Will delete the given path and all its files recursively.
2316 * Can also follow links if told so.
2317 *
2318 * \param string 'path'
2319 * \param boolean 'followLinks' TRUE to follow links, FALSE (default)
2320 * for not following links
2321 */
2322 function rmdirRecursive($path, $followLinks=false) {
2323 $dir= opendir($path);
2324 while($entry= readdir($dir)) {
2325 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
2326 unlink($path."/".$entry);
2327 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
2328 rmdirRecursive($path."/".$entry);
2329 }
2330 }
2331 closedir($dir);
2332 return rmdir($path);
2333 }
2336 /*! \brief Get directory content information
2337 *
2338 * Returns the content of a directory as an array in an
2339 * ascended sorted manner.
2340 *
2341 * \param string 'path'
2342 * \param boolean weither to sort the content descending.
2343 */
2344 function scan_directory($path,$sort_desc=false)
2345 {
2346 $ret = false;
2348 /* is this a dir ? */
2349 if(is_dir($path)) {
2351 /* is this path a readable one */
2352 if(is_readable($path)){
2354 /* Get contents and write it into an array */
2355 $ret = array();
2357 $dir = opendir($path);
2359 /* Is this a correct result ?*/
2360 if($dir){
2361 while($fp = readdir($dir))
2362 $ret[]= $fp;
2363 }
2364 }
2365 }
2366 /* Sort array ascending , like scandir */
2367 sort($ret);
2369 /* Sort descending if parameter is sort_desc is set */
2370 if($sort_desc) {
2371 $ret = array_reverse($ret);
2372 }
2374 return($ret);
2375 }
2378 /*! \brief Clean the smarty compile dir */
2379 function clean_smarty_compile_dir($directory)
2380 {
2381 global $svn_revision;
2383 if(is_dir($directory) && is_readable($directory)) {
2384 // Set revision filename to REVISION
2385 $revision_file= $directory."/REVISION";
2387 /* Is there a stamp containing the current revision? */
2388 if(!file_exists($revision_file)) {
2389 // create revision file
2390 create_revision($revision_file, $svn_revision);
2391 } else {
2392 # check for "$config->...['CONFIG']/revision" and the
2393 # contents should match the revision number
2394 if(!compare_revision($revision_file, $svn_revision)){
2395 // If revision differs, clean compile directory
2396 foreach(scan_directory($directory) as $file) {
2397 if(($file==".")||($file=="..")) continue;
2398 if( is_file($directory."/".$file) &&
2399 is_writable($directory."/".$file)) {
2400 // delete file
2401 if(!unlink($directory."/".$file)) {
2402 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
2403 // This should never be reached
2404 }
2405 } elseif(is_dir($directory."/".$file) &&
2406 is_writable($directory."/".$file)) {
2407 // Just recursively delete it
2408 rmdirRecursive($directory."/".$file);
2409 }
2410 }
2411 // We should now create a fresh revision file
2412 clean_smarty_compile_dir($directory);
2413 } else {
2414 // Revision matches, nothing to do
2415 }
2416 }
2417 } else {
2418 // Smarty compile dir is not accessible
2419 // (Smarty will warn about this)
2420 }
2421 }
2424 function create_revision($revision_file, $revision)
2425 {
2426 $result= false;
2428 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2429 if($fh= fopen($revision_file, "w")) {
2430 if(fwrite($fh, $revision)) {
2431 $result= true;
2432 }
2433 }
2434 fclose($fh);
2435 } else {
2436 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2437 }
2439 return $result;
2440 }
2443 function compare_revision($revision_file, $revision)
2444 {
2445 // false means revision differs
2446 $result= false;
2448 if(file_exists($revision_file) && is_readable($revision_file)) {
2449 // Open file
2450 if($fh= fopen($revision_file, "r")) {
2451 // Compare File contents with current revision
2452 if($revision == fread($fh, filesize($revision_file))) {
2453 $result= true;
2454 }
2455 } else {
2456 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2457 }
2458 // Close file
2459 fclose($fh);
2460 }
2462 return $result;
2463 }
2466 /*! \brief Return HTML for a progressbar
2467 *
2468 * \code
2469 * $smarty->assign("installprogress", progressbar($current_progress_in_percent),100,15,true);
2470 * \endcode
2471 *
2472 * \param int 'percentage' Value to display
2473 * \param int 'width' width of the resulting output
2474 * \param int 'height' height of the resulting output
2475 * \param boolean 'showvalue' weither to show the percentage in the progressbar or not
2476 * */
2477 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2478 {
2479 return("<img src='progress.php?x=$width&y=$height&p=$percentage'>");
2480 }
2483 /*! \brief Lookup a key in an array case-insensitive
2484 *
2485 * Given an associative array this can lookup the value of
2486 * a certain key, regardless of the case.
2487 *
2488 * \code
2489 * $items = array ('FOO' => 'blub', 'bar' => 'blub');
2490 * array_key_ics('foo', $items); # Returns 'blub'
2491 * array_key_ics('BAR', $items); # Returns 'blub'
2492 * \endcode
2493 *
2494 * \param string 'key' needle
2495 * \param array 'items' haystack
2496 */
2497 function array_key_ics($ikey, $items)
2498 {
2499 $tmp= array_change_key_case($items, CASE_LOWER);
2500 $ikey= strtolower($ikey);
2501 if (isset($tmp[$ikey])){
2502 return($tmp[$ikey]);
2503 }
2505 return ('');
2506 }
2509 /*! \brief Determine if two arrays are different
2510 *
2511 * \param array 'src'
2512 * \param array 'dst'
2513 * \return boolean TRUE or FALSE
2514 * */
2515 function array_differs($src, $dst)
2516 {
2517 /* If the count is differing, the arrays differ */
2518 if (count ($src) != count ($dst)){
2519 return (TRUE);
2520 }
2522 return (count(array_diff($src, $dst)) != 0);
2523 }
2526 function saveFilter($a_filter, $values)
2527 {
2528 if (isset($_POST['regexit'])){
2529 $a_filter["regex"]= $_POST['regexit'];
2531 foreach($values as $type){
2532 if (isset($_POST[$type])) {
2533 $a_filter[$type]= "checked";
2534 } else {
2535 $a_filter[$type]= "";
2536 }
2537 }
2538 }
2540 /* React on alphabet links if needed */
2541 if (isset($_GET['search'])){
2542 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2543 if ($s == "**"){
2544 $s= "*";
2545 }
2546 $a_filter['regex']= $s;
2547 }
2549 return ($a_filter);
2550 }
2553 /*! \brief Escape all LDAP filter relevant characters */
2554 function normalizeLdap($input)
2555 {
2556 return (addcslashes($input, '()|'));
2557 }
2560 /*! \brief Return the gosa base directory */
2561 function get_base_dir()
2562 {
2563 global $BASE_DIR;
2565 return $BASE_DIR;
2566 }
2569 /*! \brief Test weither we are allowed to read the object */
2570 function obj_is_readable($dn, $object, $attribute)
2571 {
2572 global $ui;
2574 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2575 }
2578 /*! \brief Test weither we are allowed to change the object */
2579 function obj_is_writable($dn, $object, $attribute)
2580 {
2581 global $ui;
2583 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2584 }
2587 /*! \brief Explode a DN into its parts
2588 *
2589 * Similar to explode (http://php.net/explode), but a bit more specific
2590 * for the needs when splitting, exploding LDAP DNs.
2591 *
2592 * \param string 'dn' the DN to split
2593 * \param config-object a config object. only neeeded if DN shall be verified in the LDAP
2594 * \param boolean verify_in_ldap check weither DN is valid
2595 *
2596 */
2597 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2598 {
2599 /* Initialize variables */
2600 $ret = array("count" => 0); // Set count to 0
2601 $next = true; // if false, then skip next loops and return
2602 $cnt = 0; // Current number of loops
2603 $max = 100; // Just for security, prevent looops
2604 $ldap = NULL; // To check if created result a valid
2605 $keep = ""; // save last failed parse string
2607 /* Check each parsed dn in ldap ? */
2608 if($config!==NULL && $verify_in_ldap){
2609 $ldap = $config->get_ldap_link();
2610 }
2612 /* Lets start */
2613 $called = false;
2614 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2616 $cnt ++;
2617 if(!preg_match("/,/",$dn)){
2618 $next = false;
2619 }
2620 $object = preg_replace("/[,].*$/","",$dn);
2621 $dn = preg_replace("/^[^,]+,/","",$dn);
2623 $called = true;
2625 /* Check if current dn is valid */
2626 if($ldap!==NULL){
2627 $ldap->cd($dn);
2628 $ldap->cat($dn,array("dn"));
2629 if($ldap->count()){
2630 $ret[] = $keep.$object;
2631 $keep = "";
2632 }else{
2633 $keep .= $object.",";
2634 }
2635 }else{
2636 $ret[] = $keep.$object;
2637 $keep = "";
2638 }
2639 }
2641 /* No dn was posted */
2642 if($cnt == 0 && !empty($dn)){
2643 $ret[] = $dn;
2644 }
2646 /* Append the rest */
2647 $test = $keep.$dn;
2648 if($called && !empty($test)){
2649 $ret[] = $keep.$dn;
2650 }
2651 $ret['count'] = count($ret) - 1;
2653 return($ret);
2654 }
2657 function get_base_from_hook($dn, $attrib)
2658 {
2659 global $config;
2661 if ($config->get_cfg_value("baseIdHook") != ""){
2663 /* Call hook script - if present */
2664 $command= $config->get_cfg_value("baseIdHook");
2666 if ($command != ""){
2667 $command.= " '".LDAP::fix($dn)."' $attrib";
2668 if (check_command($command)){
2669 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2670 exec($command, $output);
2671 if (preg_match("/^[0-9]+$/", $output[0])){
2672 return ($output[0]);
2673 } else {
2674 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2675 return ($config->get_cfg_value("uidNumberBase"));
2676 }
2677 } else {
2678 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2679 return ($config->get_cfg_value("uidNumberBase"));
2680 }
2682 } else {
2684 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2685 return ($config->get_cfg_value("uidNumberBase"));
2687 }
2688 }
2689 }
2692 /*! \brief Check if schema version matches the requirements */
2693 function check_schema_version($class, $version)
2694 {
2695 return preg_match("/\(v$version\)/", $class['DESC']);
2696 }
2699 /*! \brief Check if LDAP schema matches the requirements */
2700 function check_schema($cfg,$rfc2307bis = FALSE)
2701 {
2702 $messages= array();
2704 /* Get objectclasses */
2705 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2706 $objectclasses = $ldap->get_objectclasses();
2707 if(count($objectclasses) == 0){
2708 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2709 }
2711 /* This is the default block used for each entry.
2712 * to avoid unset indexes.
2713 */
2714 $def_check = array("REQUIRED_VERSION" => "0",
2715 "SCHEMA_FILES" => array(),
2716 "CLASSES_REQUIRED" => array(),
2717 "STATUS" => FALSE,
2718 "IS_MUST_HAVE" => FALSE,
2719 "MSG" => "",
2720 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2722 /* The gosa base schema */
2723 $checks['gosaObject'] = $def_check;
2724 $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2725 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa-samba3.schema","gosa-samba2.schema");
2726 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2727 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2729 /* GOsa Account class */
2730 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.6";
2731 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa-samba3.schema","gosa-samba2.schema");
2732 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2733 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2734 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2736 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2737 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2738 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa-samba3.schema","gosa-samba2.schema");
2739 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2740 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2741 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2743 /* Some other checks */
2744 foreach(array(
2745 "gosaCacheEntry" => array("version" => "2.6.1", "class" => "gosaAccount"),
2746 "gosaDepartment" => array("version" => "2.6.1", "class" => "gosaAccount"),
2747 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2748 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2749 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2750 "gosaUserTemplate" => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2751 "gosaMailAccount" => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa-samba3.schema"),
2752 "gosaProxyAccount" => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa-samba3.schema"),
2753 "gosaApplication" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2754 "gosaApplicationGroup" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2755 "GOhard" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2756 "gotoTerminal" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2757 "goServer" => array("version" => "2.6.1", "class" => "server","file" => "goserver.schema"),
2758 "goTerminalServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2759 "goShareServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2760 "goNtpServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2761 "goSyslogServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2762 "goLdapServer" => array("version" => "2.6.1", "class" => "goServer"),
2763 "goCupsServer" => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2764 "goImapServer" => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa-samba3.schema"),
2765 "goKrbServer" => array("version" => "2.6.1", "class" => "goServer"),
2766 "goFaxServer" => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2767 ) as $name => $values){
2769 $checks[$name] = $def_check;
2770 if(isset($values['version'])){
2771 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2772 }
2773 if(isset($values['file'])){
2774 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2775 }
2776 if (isset($values['class'])) {
2777 $checks[$name]["CLASSES_REQUIRED"] = is_array($values['class'])?$values['class']:array($values['class']);
2778 }
2779 }
2780 foreach($checks as $name => $value){
2781 foreach($value['CLASSES_REQUIRED'] as $class){
2783 if(!isset($objectclasses[$name])){
2784 if($value['IS_MUST_HAVE']){
2785 $checks[$name]['STATUS'] = FALSE;
2786 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2787 } else {
2788 $checks[$name]['STATUS'] = TRUE;
2789 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2790 }
2791 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2792 $checks[$name]['STATUS'] = FALSE;
2794 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2795 }else{
2796 $checks[$name]['STATUS'] = TRUE;
2797 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2798 }
2799 }
2800 }
2802 $tmp = $objectclasses;
2804 /* The gosa base schema */
2805 $checks['posixGroup'] = $def_check;
2806 $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2807 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa-samba3.schema","gosa-samba2.schema");
2808 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2809 $checks['posixGroup']['STATUS'] = TRUE;
2810 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2811 $checks['posixGroup']['MSG'] = "";
2812 $checks['posixGroup']['INFO'] = "";
2814 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2815 if(isset($tmp['posixGroup'])){
2817 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2818 $checks['posixGroup']['STATUS'] = FALSE;
2819 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2820 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2821 }
2822 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2823 $checks['posixGroup']['STATUS'] = FALSE;
2824 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2825 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2826 }
2827 }
2829 return($checks);
2830 }
2833 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2834 {
2835 $tmp = array(
2836 "de_DE" => "German",
2837 "fr_FR" => "French",
2838 "it_IT" => "Italian",
2839 "es_ES" => "Spanish",
2840 "en_US" => "English",
2841 "nl_NL" => "Dutch",
2842 "pl_PL" => "Polish",
2843 #"sv_SE" => "Swedish",
2844 "zh_CN" => "Chinese",
2845 "vi_VN" => "Vietnamese",
2846 "ru_RU" => "Russian");
2848 $tmp2= array(
2849 "de_DE" => _("German"),
2850 "fr_FR" => _("French"),
2851 "it_IT" => _("Italian"),
2852 "es_ES" => _("Spanish"),
2853 "en_US" => _("English"),
2854 "nl_NL" => _("Dutch"),
2855 "pl_PL" => _("Polish"),
2856 #"sv_SE" => _("Swedish"),
2857 "zh_CN" => _("Chinese"),
2858 "vi_VN" => _("Vietnamese"),
2859 "ru_RU" => _("Russian"));
2861 $ret = array();
2862 if($languages_in_own_language){
2864 $old_lang = setlocale(LC_ALL, 0);
2866 /* If the locale wasn't correclty set before, there may be an incorrect
2867 locale returned. Something like this:
2868 C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2869 Extract the locale name from this string and use it to restore old locale.
2870 */
2871 if(preg_match("/LC_CTYPE/",$old_lang)){
2872 $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2873 }
2875 foreach($tmp as $key => $name){
2876 $lang = $key.".UTF-8";
2877 setlocale(LC_ALL, $lang);
2878 if($strip_region_tag){
2879 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2880 }else{
2881 $ret[$key] = _($name)." (".$tmp2[$key].")";
2882 }
2883 }
2884 setlocale(LC_ALL, $old_lang);
2885 }else{
2886 foreach($tmp as $key => $name){
2887 if($strip_region_tag){
2888 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2889 }else{
2890 $ret[$key] = _($name);
2891 }
2892 }
2893 }
2894 return($ret);
2895 }
2898 /*! \brief Returns contents of the given POST variable and check magic quotes settings
2899 *
2900 * Depending on the magic quotes settings this returns a stripclashed'ed version of
2901 * a certain POST variable.
2902 *
2903 * \param string 'name' the POST var to return ($_POST[$name])
2904 * \return string
2905 * */
2906 function get_post($name)
2907 {
2908 if(!isset($_POST[$name])){
2909 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2910 return(FALSE);
2911 }
2913 if(get_magic_quotes_gpc()){
2914 return(stripcslashes(validate($_POST[$name])));
2915 }else{
2916 return(validate($_POST[$name]));
2917 }
2918 }
2921 /*! \brief Return class name in correct case */
2922 function get_correct_class_name($cls)
2923 {
2924 global $class_mapping;
2925 if(isset($class_mapping) && is_array($class_mapping)){
2926 foreach($class_mapping as $class => $file){
2927 if(preg_match("/^".$cls."$/i",$class)){
2928 return($class);
2929 }
2930 }
2931 }
2932 return(FALSE);
2933 }
2936 /*! \brief Change the password of a given DN
2937 *
2938 * Change the password of a given DN with the specified hash.
2939 *
2940 * \param string 'dn' the DN whose password shall be changed
2941 * \param string 'password' the password
2942 * \param int mode
2943 * \param string 'hash' which hash to use to encrypt it, default is empty
2944 * for cleartext storage.
2945 * \return boolean TRUE on success FALSE on error
2946 */
2947 function change_password ($dn, $password, $mode=0, $hash= "")
2948 {
2949 global $config;
2950 $newpass= "";
2952 /* Convert to lower. Methods are lowercase */
2953 $hash= strtolower($hash);
2955 // Get all available encryption Methods
2957 // NON STATIC CALL :)
2958 $methods = new passwordMethod(session::get('config'),$dn);
2959 $available = $methods->get_available_methods();
2961 // read current password entry for $dn, to detect the encryption Method
2962 $ldap = $config->get_ldap_link();
2963 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2964 $attrs = $ldap->fetch ();
2966 /* Is ensure that clear passwords will stay clear */
2967 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2968 $hash = "clear";
2969 }
2971 // Detect the encryption Method
2972 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2974 /* Check for supported algorithm */
2975 mt_srand((double) microtime()*1000000);
2977 /* Extract used hash */
2978 if ($hash == ""){
2979 $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2980 } else {
2981 $test = new $available[$hash]($config,$dn);
2982 $test->set_hash($hash);
2983 }
2985 } else {
2986 // User MD5 by default
2987 $hash= "md5";
2988 $test = new $available['md5']($config, $dn);
2989 }
2991 if($test instanceOf passwordMethod){
2993 $deactivated = $test->is_locked($config,$dn);
2995 /* Feed password backends with information */
2996 $test->dn= $dn;
2997 $test->attrs= $attrs;
2998 $newpass= $test->generate_hash($password);
3000 // Update shadow timestamp?
3001 if (isset($attrs["shadowLastChange"][0])){
3002 $shadow= (int)(date("U") / 86400);
3003 } else {
3004 $shadow= 0;
3005 }
3007 // Write back modified entry
3008 $ldap->cd($dn);
3009 $attrs= array();
3011 // Not for groups
3012 if ($mode == 0){
3013 // Create SMB Password
3014 $attrs= generate_smb_nt_hash($password);
3016 if ($shadow != 0){
3017 $attrs['shadowLastChange']= $shadow;
3018 }
3019 }
3021 $attrs['userPassword']= array();
3022 $attrs['userPassword']= $newpass;
3024 $ldap->modify($attrs);
3026 /* Read ! if user was deactivated */
3027 if($deactivated){
3028 $test->lock_account($config,$dn);
3029 }
3031 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
3033 if (!$ldap->success()) {
3034 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
3035 } else {
3037 /* Run backend method for change/create */
3038 if(!$test->set_password($password)){
3039 return(FALSE);
3040 }
3042 /* Find postmodify entries for this class */
3043 $command= $config->search("password", "POSTMODIFY",array('menu'));
3045 if ($command != ""){
3046 /* Walk through attribute list */
3047 $command= preg_replace("/%userPassword/", $password, $command);
3048 $command= preg_replace("/%dn/", $dn, $command);
3050 if (check_command($command)){
3051 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
3052 exec($command);
3053 } else {
3054 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
3055 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
3056 }
3057 }
3058 }
3059 return(TRUE);
3060 }
3061 }
3064 /*! \brief Generate samba hashes
3065 *
3066 * Given a certain password this constructs an array like
3067 * array['sambaLMPassword'] etc.
3068 *
3069 * \param string 'password'
3070 * \return array contains several keys for lmPassword, ntPassword, pwdLastSet, etc. depending
3071 * on the samba version
3072 */
3073 function generate_smb_nt_hash($password)
3074 {
3075 global $config;
3077 # Try to use gosa-si?
3078 if ($config->get_cfg_value("gosaSupportURI") != ""){
3079 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
3080 if (isset($res['XML']['HASH'])){
3081 $hash= $res['XML']['HASH'];
3082 } else {
3083 $hash= "";
3084 }
3086 if ($hash == "") {
3087 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
3088 return ("");
3089 }
3090 } else {
3091 $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
3092 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
3094 exec($tmp, $ar);
3095 flush();
3096 reset($ar);
3097 $hash= current($ar);
3099 if ($hash == "") {
3100 msg_dialog::display(_("Configuration error"), sprintf(_("Cannot generate samba hash: running '%s' failed, check the 'sambaHashHook'!"),$config->get_cfg_value('sambaHashHook')), ERROR_DIALOG);
3101 return ("");
3102 }
3103 }
3105 list($lm,$nt)= explode(":", trim($hash));
3107 $attrs['sambaLMPassword']= $lm;
3108 $attrs['sambaNTPassword']= $nt;
3109 $attrs['sambaPwdLastSet']= date('U');
3110 $attrs['sambaBadPasswordCount']= "0";
3111 $attrs['sambaBadPasswordTime']= "0";
3112 return($attrs);
3113 }
3116 /*! \brief Get the Change Sequence Number of a certain DN
3117 *
3118 * To verify if a given object has been changed outside of Gosa
3119 * in the meanwhile, this function can be used to get the entryCSN
3120 * from the LDAP directory. It uses the attribute as configured
3121 * in modificationDetectionAttribute
3122 *
3123 * \param string 'dn'
3124 * \return either the result or "" in any other case
3125 */
3126 function getEntryCSN($dn)
3127 {
3128 global $config;
3129 if(empty($dn) || !is_object($config)){
3130 return("");
3131 }
3133 /* Get attribute that we should use as serial number */
3134 $attr= $config->get_cfg_value("modificationDetectionAttribute");
3135 if($attr != ""){
3136 $ldap = $config->get_ldap_link();
3137 $ldap->cat($dn,array($attr));
3138 $csn = $ldap->fetch();
3139 if(isset($csn[$attr][0])){
3140 return($csn[$attr][0]);
3141 }
3142 }
3143 return("");
3144 }
3147 /*! \brief Add (a) given objectClass(es) to an attrs entry
3148 *
3149 * The function adds the specified objectClass(es) to the given
3150 * attrs entry.
3151 *
3152 * \param mixed 'classes' Either a single objectClass or several objectClasses
3153 * as an array
3154 * \param array 'attrs' The attrs array to be modified.
3155 *
3156 * */
3157 function add_objectClass($classes, &$attrs)
3158 {
3159 if (is_array($classes)){
3160 $list= $classes;
3161 } else {
3162 $list= array($classes);
3163 }
3165 foreach ($list as $class){
3166 $attrs['objectClass'][]= $class;
3167 }
3168 }
3171 /*! \brief Removes a given objectClass from the attrs entry
3172 *
3173 * Similar to add_objectClass, except that it removes the given
3174 * objectClasses. See it for the params.
3175 * */
3176 function remove_objectClass($classes, &$attrs)
3177 {
3178 if (isset($attrs['objectClass'])){
3179 /* Array? */
3180 if (is_array($classes)){
3181 $list= $classes;
3182 } else {
3183 $list= array($classes);
3184 }
3186 $tmp= array();
3187 foreach ($attrs['objectClass'] as $oc) {
3188 foreach ($list as $class){
3189 if (strtolower($oc) != strtolower($class)){
3190 $tmp[]= $oc;
3191 }
3192 }
3193 }
3194 $attrs['objectClass']= $tmp;
3195 }
3196 }
3199 /*! \brief Initialize a file download with given content, name and data type.
3200 * \param string data The content to send.
3201 * \param string name The name of the file.
3202 * \param string type The content identifier, default value is "application/octet-stream";
3203 */
3204 function send_binary_content($data,$name,$type = "application/octet-stream")
3205 {
3206 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
3207 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
3208 header("Cache-Control: no-cache");
3209 header("Pragma: no-cache");
3210 header("Cache-Control: post-check=0, pre-check=0");
3211 header("Content-type: ".$type."");
3213 $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
3215 /* Strip name if it is a complete path */
3216 if (preg_match ("/\//", $name)) {
3217 $name= basename($name);
3218 }
3220 /* force download dialog */
3221 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
3222 header('Content-Disposition: filename="'.$name.'"');
3223 } else {
3224 header('Content-Disposition: attachment; filename="'.$name.'"');
3225 }
3227 echo $data;
3228 exit();
3229 }
3232 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
3233 {
3234 if(is_string($str)){
3235 return(htmlentities($str,$type,$charset));
3236 }elseif(is_array($str)){
3237 foreach($str as $name => $value){
3238 $str[$name] = reverse_html_entities($value,$type,$charset);
3239 }
3240 }
3241 return($str);
3242 }
3245 /*! \brief Encode special string characters so we can use the string in \
3246 HTML output, without breaking quotes.
3247 \param string The String we want to encode.
3248 \return string The encoded String
3249 */
3250 function xmlentities($str)
3251 {
3252 if(is_string($str)){
3254 static $asc2uni= array();
3255 if (!count($asc2uni)){
3256 for($i=128;$i<256;$i++){
3257 # $asc2uni[chr($i)] = "&#x".dechex($i).";";
3258 }
3259 }
3261 $str = str_replace("&", "&", $str);
3262 $str = str_replace("<", "<", $str);
3263 $str = str_replace(">", ">", $str);
3264 $str = str_replace("'", "'", $str);
3265 $str = str_replace("\"", """, $str);
3266 $str = str_replace("\r", "", $str);
3267 $str = strtr($str,$asc2uni);
3268 return $str;
3269 }elseif(is_array($str)){
3270 foreach($str as $name => $value){
3271 $str[$name] = xmlentities($value);
3272 }
3273 }
3274 return($str);
3275 }
3278 /*! \brief Updates all accessTo attributes from a given value to a new one.
3279 For example if a host is renamed.
3280 \param String $from The source accessTo name.
3281 \param String $to The destination accessTo name.
3282 */
3283 function update_accessTo($from,$to)
3284 {
3285 global $config;
3286 $ldap = $config->get_ldap_link();
3287 $ldap->cd($config->current['BASE']);
3288 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
3289 while($attrs = $ldap->fetch()){
3290 $new_attrs = array("accessTo" => array());
3291 $dn = $attrs['dn'];
3292 for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
3293 $new_attrs['objectClass'][] = $attrs['objectClass'][$i];
3294 }
3295 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
3296 if($attrs['accessTo'][$i] == $from){
3297 if(!empty($to)){
3298 $new_attrs['accessTo'][] = $to;
3299 }
3300 }else{
3301 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
3302 }
3303 }
3304 $ldap->cd($dn);
3305 $ldap->modify($new_attrs);
3306 if (!$ldap->success()){
3307 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
3308 }
3309 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
3310 }
3311 }
3314 /*! \brief Returns a random char */
3315 function get_random_char () {
3316 $randno = rand (0, 63);
3317 if ($randno < 12) {
3318 return (chr ($randno + 46)); // Digits, '/' and '.'
3319 } else if ($randno < 38) {
3320 return (chr ($randno + 53)); // Uppercase
3321 } else {
3322 return (chr ($randno + 59)); // Lowercase
3323 }
3324 }
3327 function cred_encrypt($input, $password) {
3329 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3330 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3332 return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
3334 }
3337 function cred_decrypt($input,$password) {
3338 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3339 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3341 return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
3342 }
3345 function get_object_info()
3346 {
3347 return(session::get('objectinfo'));
3348 }
3351 function set_object_info($str = "")
3352 {
3353 session::set('objectinfo',$str);
3354 }
3357 function isIpInNet($ip, $net, $mask) {
3358 // Move to long ints
3359 $ip= ip2long($ip);
3360 $net= ip2long($net);
3361 $mask= ip2long($mask);
3363 // Mask given IP with mask. If it returns "net", we're in...
3364 $res= $ip & $mask;
3366 return ($res == $net);
3367 }
3370 function get_next_id($attrib, $dn)
3371 {
3372 global $config;
3374 switch ($config->get_cfg_value("idAllocationMethod", "traditional")){
3375 case "pool":
3376 return get_next_id_pool($attrib);
3377 case "traditional":
3378 return get_next_id_traditional($attrib, $dn);
3379 }
3381 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("unknown idAllocation method!"), ERROR_DIALOG);
3382 return null;
3383 }
3386 function get_next_id_pool($attrib) {
3387 global $config;
3389 /* Fill informational values */
3390 $min= $config->get_cfg_value("${attrib}PoolMin", 10000);
3391 $max= $config->get_cfg_value("${attrib}PoolMax", 40000);
3393 /* Sanity check */
3394 if ($min >= $max) {
3395 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." ".sprintf(_("%sPoolMin >= %sPoolMax!"), $attrib), ERROR_DIALOG);
3396 return null;
3397 }
3399 /* ID to skip */
3400 $ldap= $config->get_ldap_link();
3401 $id= null;
3403 /* Try to allocate the ID several times before failing */
3404 $tries= 3;
3405 while ($tries--) {
3407 /* Look for ID map entry */
3408 $ldap->cd ($config->current['BASE']);
3409 $ldap->search ("(&(objectClass=sambaUnixIdPool)($attrib=*))", array("$attrib"));
3411 /* If it does not exist, create one with these defaults */
3412 if ($ldap->count() == 0) {
3413 /* Fill informational values */
3414 $minUserId= $config->get_cfg_value("uidPoolMin", 10000);
3415 $minGroupId= $config->get_cfg_value("gidPoolMin", 10000);
3417 /* Add as default */
3418 $attrs= array("objectClass" => array("organizationalUnit", "sambaUnixIdPool"));
3419 $attrs["ou"]= "idmap";
3420 $attrs["uidNumber"]= $minUserId;
3421 $attrs["gidNumber"]= $minGroupId;
3422 $ldap->cd("ou=idmap,".$config->current['BASE']);
3423 $ldap->add($attrs);
3424 if ($ldap->error != "Success") {
3425 msg_dialog::display(_("Error"), _("Cannot create sambaUnixIdPool entry!"), ERROR_DIALOG);
3426 return null;
3427 }
3428 $tries++;
3429 continue;
3430 }
3431 /* Bail out if it's not unique */
3432 if ($ldap->count() != 1) {
3433 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("sambaUnixIdPool is not unique!"), ERROR_DIALOG);
3434 return null;
3435 }
3437 /* Store old attrib and generate new */
3438 $attrs= $ldap->fetch();
3439 $dn= $ldap->getDN();
3440 $oldAttr= $attrs[$attrib][0];
3441 $newAttr= $oldAttr + 1;
3443 /* Sanity check */
3444 if ($newAttr >= $max) {
3445 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("no ID available!"), ERROR_DIALOG);
3446 return null;
3447 }
3448 if ($newAttr < $min) {
3449 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("no ID available!"), ERROR_DIALOG);
3450 return null;
3451 }
3453 #FIXME: PHP is not able to do a modification of "del: .../add: ...", so this
3454 # is completely unsafe in the moment.
3455 #/* Remove old attr, add new attr */
3456 #$attrs= array($attrib => $oldAttr);
3457 #$ldap->rm($attrs, $dn);
3458 #if ($ldap->error != "Success") {
3459 # continue;
3460 #}
3461 $ldap->cd($dn);
3462 $ldap->modify(array($attrib => $newAttr));
3463 if ($ldap->error != "Success") {
3464 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." ".$ldap->get_error(), ERROR_DIALOG);
3465 return null;
3466 } else {
3467 return $oldAttr;
3468 }
3469 }
3471 /* Bail out if we had problems getting the next id */
3472 if (!$tries) {
3473 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("maximum tries exceeded!"), ERROR_DIALOG);
3474 }
3476 return $id;
3477 }
3480 function get_next_id_traditional($attrib, $dn)
3481 {
3482 global $config;
3484 $ids= array();
3485 $ldap= $config->get_ldap_link();
3487 $ldap->cd ($config->current['BASE']);
3488 if (preg_match('/gidNumber/i', $attrib)){
3489 $oc= "posixGroup";
3490 } else {
3491 $oc= "posixAccount";
3492 }
3493 $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
3495 /* Get list of ids */
3496 while ($attrs= $ldap->fetch()){
3497 $ids[]= (int)$attrs["$attrib"][0];
3498 }
3500 /* Add the nobody id */
3501 $ids[]= 65534;
3503 /* get the ranges */
3504 $tmp = array('0'=> 1000);
3505 if (preg_match('/posixAccount/', $oc) && $config->get_cfg_value("uidNumberBase") != ""){
3506 $tmp= explode('-',$config->get_cfg_value("uidNumberBase"));
3507 } elseif($config->get_cfg_value("gidNumberBase") != ""){
3508 $tmp= explode('-',$config->get_cfg_value("gidNumberBase"));
3509 }
3511 /* Set hwm to max if not set - for backward compatibility */
3512 $lwm= $tmp[0];
3513 if (isset($tmp[1])){
3514 $hwm= $tmp[1];
3515 } else {
3516 $hwm= pow(2,32);
3517 }
3518 /* Find out next free id near to UID_BASE */
3519 if ($config->get_cfg_value("baseIdHook") == ""){
3520 $base= $lwm;
3521 } else {
3522 /* Call base hook */
3523 $base= get_base_from_hook($dn, $attrib);
3524 }
3525 for ($id= $base; $id++; $id < pow(2,32)){
3526 if (!in_array($id, $ids)){
3527 return ($id);
3528 }
3529 }
3531 /* Should not happen */
3532 if ($id == $hwm){
3533 msg_dialog::display(_("Error"), _("Cannot allocate a free ID!"), ERROR_DIALOG);
3534 exit;
3535 }
3536 }
3539 /* Mark the occurance of a string with a span */
3540 function mark($needle, $haystack, $ignorecase= true)
3541 {
3542 $result= "";
3544 while (preg_match('/^(.*)('.preg_quote($needle).')(.*)$/i', $haystack, $matches)) {
3545 $result.= $matches[1]."<span class='mark'>".$matches[2]."</span>";
3546 $haystack= $matches[3];
3547 }
3549 return $result.$haystack;
3550 }
3552 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3553 ?>