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)
92 define ("DEBUG_RPC", 2048); /*! Debug level for communication with remote procedures */
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"), bold("update-gosa"));
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"), bold($class_name), bold("update-gosa"));
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, $config;
156 $disabled = array();
157 if($config instanceOf config && $config->configRegistry instanceOf configRegistry){
158 $disabled = $config->configRegistry->getDisabledPlugins();
159 }
161 return(isset($class_mapping[$name]) && !isset($disabled[$name]));
162 }
165 /*! \brief Check if plugin is available
166 *
167 * Checks if a given plugin is available and readable.
168 *
169 * \param string 'plugin' the subject of the check
170 * \return boolean True if plugin is available, else FALSE.
171 */
172 function plugin_available($plugin)
173 {
174 global $class_mapping, $BASE_DIR;
176 if (!isset($class_mapping[$plugin])){
177 return false;
178 } else {
179 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
180 }
181 }
184 /*! \brief Create seed with microseconds
185 *
186 * Example:
187 * \code
188 * srand(make_seed());
189 * $random = rand();
190 * \endcode
191 *
192 * \return float a floating point number which can be used to feed srand() with it
193 * */
194 function make_seed() {
195 list($usec, $sec) = explode(' ', microtime());
196 return (float) $sec + ((float) $usec * 100000);
197 }
200 /*! \brief Debug level action
201 *
202 * Print a DEBUG level if specified debug level of the level matches the
203 * the configured debug level.
204 *
205 * \param int 'level' The log level of the message (should use the constants,
206 * defined in functions.in (DEBUG_TRACE, DEBUG_LDAP, etc.)
207 * \param int 'line' Define the line of the logged action (using __LINE__ is common)
208 * \param string 'function' Define the function where the logged action happened in
209 * (using __FUNCTION__ is common)
210 * \param string 'file' Define the file where the logged action happend in
211 * (using __FILE__ is common)
212 * \param mixed 'data' The data to log. Can be a message or an array, which is printed
213 * with print_a
214 * \param string 'info' Optional: Additional information
215 *
216 * */
217 function DEBUG($level, $line, $function, $file, $data, $info="")
218 {
219 global $config;
220 $debugLevel = 0;
221 if($config instanceOf config){
222 $debugLevel = $config->get_cfg_value('core', 'debugLevel');
223 }
224 if ($debugLevel & $level){
225 $output= "DEBUG[$level] ";
226 if ($function != ""){
227 $output.= "($file:$function():$line) - $info: ";
228 } else {
229 $output.= "($file:$line) - $info: ";
230 }
231 echo $output;
232 if (is_array($data)){
233 print_a($data);
234 } else {
235 echo "'$data'";
236 }
237 echo "<br>";
238 }
239 }
242 /*! \brief Determine which language to show to the user
243 *
244 * Determines which language should be used to present gosa content
245 * to the user. It does so by looking at several possibilites and returning
246 * the first setting that can be found.
247 *
248 * -# Language configured by the user
249 * -# Global configured language
250 * -# Language as returned by al2gt (as configured in the browser)
251 *
252 * \return string gettext locale string
253 */
254 function get_browser_language()
255 {
256 /* Try to use users primary language */
257 global $config;
258 $ui= get_userinfo();
259 if (isset($ui) && $ui !== NULL){
260 if ($ui->language != ""){
261 return ($ui->language.".UTF-8");
262 }
263 }
265 /* Check for global language settings in gosa.conf */
266 if (isset ($config) && $config->get_cfg_value("core",'language') != ""){
267 $lang = $config->get_cfg_value("core",'language');
268 if(!preg_match("/utf/i",$lang)){
269 $lang .= ".UTF-8";
270 }
271 return($lang);
272 }
274 /* Load supported languages */
275 $gosa_languages= get_languages();
277 /* Move supported languages to flat list */
278 $langs= array();
279 foreach($gosa_languages as $lang => $dummy){
280 $langs[]= $lang.'.UTF-8';
281 }
283 /* Return gettext based string */
284 return (al2gt($langs, 'text/html'));
285 }
288 /*! \brief Rewrite ui object to another dn
289 *
290 * Usually used when a user is renamed. In this case the dn
291 * in the user object must be updated in order to point
292 * to the correct DN.
293 *
294 * \param string 'dn' the old DN
295 * \param string 'newdn' the new DN
296 * */
297 function change_ui_dn($dn, $newdn)
298 {
299 $ui= session::global_get('ui');
300 if ($ui->dn == $dn){
301 $ui->dn= $newdn;
302 session::global_set('ui',$ui);
303 }
304 }
307 /*! \brief Return themed path for specified base file
308 *
309 * Depending on its parameters, this function returns the full
310 * path of a template file. First match wins while searching
311 * in this order:
312 *
313 * - load theme depending file
314 * - load global theme depending file
315 * - load default theme file
316 * - load global default theme file
317 *
318 * \param string 'filename' The base file name
319 * \param boolean 'plugin' Flag to take the plugin directory as search base
320 * \param string 'path' User specified path to take as search base
321 * \return string Full path to the template file
322 */
323 function get_template_path($filename= '', $plugin= FALSE, $path= "")
324 {
325 global $config, $BASE_DIR;
327 /* Set theme */
328 if (isset ($config)){
329 $theme= $config->get_cfg_value("core","theme");
330 } else {
331 $theme= "default";
332 }
334 /* Return path for empty filename */
335 if ($filename == ''){
336 return ("themes/$theme/");
337 }
339 /* Return plugin dir or root directory? */
340 if ($plugin){
341 if ($path == ""){
342 $nf= preg_replace("!^".$BASE_DIR."/!", "", preg_replace('/^\.\.\//', '', session::global_get('plugin_dir')));
343 } else {
344 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
345 }
346 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
347 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
348 }
349 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
350 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
351 }
352 if ($path == ""){
353 return (session::global_get('plugin_dir')."/$filename");
354 } else {
355 return ($path."/$filename");
356 }
357 } else {
358 if (file_exists("themes/$theme/$filename")){
359 return ("themes/$theme/$filename");
360 }
361 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
362 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
363 }
364 if (file_exists("themes/default/$filename")){
365 return ("themes/default/$filename");
366 }
367 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
368 return ("$BASE_DIR/ihtml/themes/default/$filename");
369 }
370 return ($filename);
371 }
372 }
375 /*! \brief Remove multiple entries from an array
376 *
377 * Removes every element that is in $needles from the
378 * array given as $haystack
379 *
380 * \param array 'needles' array of the entries to remove
381 * \param array 'haystack' original array to remove the entries from
382 */
383 function array_remove_entries($needles, $haystack)
384 {
385 return (array_merge(array_diff($haystack, $needles)));
386 }
389 /*! \brief Remove multiple entries from an array (case-insensitive)
390 *
391 * Same as array_remove_entries(), but case-insensitive. */
392 function array_remove_entries_ics($needles, $haystack)
393 {
394 // strcasecmp will work, because we only compare ASCII values here
395 return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
396 }
399 /*! Merge to array but remove duplicate entries
400 *
401 * Merges two arrays and removes duplicate entries. Triggers
402 * an error if first or second parametre is not an array.
403 *
404 * \param array 'ar1' first array
405 * \param array 'ar2' second array-
406 * \return array
407 */
408 function gosa_array_merge($ar1,$ar2)
409 {
410 if(!is_array($ar1) || !is_array($ar2)){
411 trigger_error("Specified parameter(s) are not valid arrays.");
412 }else{
413 return(array_values(array_unique(array_merge($ar1,$ar2))));
414 }
415 }
418 /*! \brief Generate a system log info
419 *
420 * Creates a syslog message, containing user information.
421 *
422 * \param string 'message' the message to log
423 * */
424 function gosa_log ($message)
425 {
426 global $ui;
428 /* Preset to something reasonable */
429 $username= "[unauthenticated]";
431 /* Replace username if object is present */
432 if (isset($ui)){
433 if ($ui->username != ""){
434 $username= "[$ui->username]";
435 } else {
436 $username= "[unknown]";
437 }
438 }
440 syslog(LOG_INFO,"GOsa$username: $message");
441 }
444 /*! \brief Initialize a LDAP connection
445 *
446 * Initializes a LDAP connection.
447 *
448 * \param string 'server'
449 * \param string 'base'
450 * \param string 'binddn' Default: empty
451 * \param string 'pass' Default: empty
452 *
453 * \return LDAP object
454 */
455 function ldap_init ($server, $base, $binddn='', $pass='')
456 {
457 global $config;
459 $ldap = new LDAP ($binddn, $pass, $server,
460 isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
461 isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
463 /* Sadly we've no proper return values here. Use the error message instead. */
464 if (!$ldap->success()){
465 msg_dialog::display(_("Fatal error"),
466 sprintf(_("Error while connecting to LDAP: %s"), $ldap->get_error()),
467 FATAL_ERROR_DIALOG);
468 exit();
469 }
471 /* Preset connection base to $base and return to caller */
472 $ldap->cd ($base);
473 return $ldap;
474 }
477 /* \brief Process htaccess authentication */
478 function process_htaccess ($username, $kerberos= FALSE)
479 {
480 global $config;
482 /* Search for $username and optional @REALM in all configured LDAP trees */
483 foreach($config->data["LOCATIONS"] as $name => $data){
485 $config->set_current($name);
486 $mode= "kerberos";
487 if ($config->get_cfg_value("core","useSaslForKerberos") == "true"){
488 $mode= "sasl";
489 }
491 /* Look for entry or realm */
492 $ldap= $config->get_ldap_link();
493 if (!$ldap->success()){
494 msg_dialog::display(_("LDAP error"),
495 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
496 FATAL_ERROR_DIALOG);
497 exit();
498 }
499 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
501 /* Found a uniq match? Return it... */
502 if ($ldap->count() == 1) {
503 $attrs= $ldap->fetch();
504 return array("username" => $attrs["uid"][0], "server" => $name);
505 }
506 }
508 /* Nothing found? Return emtpy array */
509 return array("username" => "", "server" => "");
510 }
513 /*! \brief Verify user login against htaccess
514 *
515 * Checks if the specified username is available in apache, maps the user
516 * to an LDAP user. The password has been checked by apache already.
517 *
518 * \param string 'username'
519 * \return
520 * - TRUE on SUCCESS, NULL or FALSE on error
521 */
522 function ldap_login_user_htaccess ($username)
523 {
524 global $config;
526 /* Look for entry or realm */
527 $ldap= $config->get_ldap_link();
528 if (!$ldap->success()){
529 msg_dialog::display(_("LDAP error"),
530 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
531 FATAL_ERROR_DIALOG);
532 exit();
533 }
534 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
535 /* Found no uniq match? Strange, because we did above... */
536 if ($ldap->count() != 1) {
537 msg_dialog::display(_("LDAP error"), _("User ID is not unique!"), FATAL_ERROR_DIALOG);
538 return (NULL);
539 }
540 $attrs= $ldap->fetch();
542 /* got user dn, fill acl's */
543 $ui= new userinfo($config, $ldap->getDN());
544 $ui->username= $attrs['uid'][0];
546 /* Bail out if we have login restrictions set, for security reasons
547 the message is the same than failed user/pw */
548 if (!$ui->loginAllowed()){
549 new log("security","login","",array(),"Login restriction for user \"$username\", login not permitted");
550 return (NULL);
551 }
553 /* No password check needed - the webserver did it for us */
554 $ldap->disconnect();
556 /* Username is set, load subtreeACL's now */
557 $ui->loadACL();
559 /* TODO: check java script for htaccess authentication */
560 session::global_set('js', true);
562 return ($ui);
563 }
566 /*! \brief Verify user login against LDAP directory
567 *
568 * Checks if the specified username is in the LDAP and verifies if the
569 * password is correct by binding to the LDAP with the given credentials.
570 *
571 * \param string 'username'
572 * \param string 'password'
573 * \return
574 * - TRUE on SUCCESS, NULL or FALSE on error
575 */
576 function ldap_login_user ($username, $password)
577 {
578 global $config;
580 /* look through the entire ldap */
581 $ldap = $config->get_ldap_link();
582 if (!$ldap->success()){
583 msg_dialog::display(_("LDAP error"),
584 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
585 FATAL_ERROR_DIALOG);
586 exit();
587 }
588 $ldap->cd($config->current['BASE']);
589 $allowed_attributes = array("uid","mail");
590 $verify_attr = array();
591 if($config->get_cfg_value("core","loginAttribute") != ""){
592 $tmp = explode(",", $config->get_cfg_value("core","loginAttribute"));
593 foreach($tmp as $attr){
594 if(in_array($attr,$allowed_attributes)){
595 $verify_attr[] = $attr;
596 }
597 }
598 }
599 if(count($verify_attr) == 0){
600 $verify_attr = array("uid");
601 }
602 $tmp= $verify_attr;
603 $tmp[] = "uid";
604 $filter = "";
605 foreach($verify_attr as $attr) {
606 $filter.= "(".$attr."=".$username.")";
607 }
608 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
609 $ldap->search($filter,$tmp);
611 /* get results, only a count of 1 is valid */
612 switch ($ldap->count()){
614 /* user not found */
615 case 0: return (NULL);
617 /* valid uniq user */
618 case 1:
619 break;
621 /* found more than one matching id */
622 default:
623 msg_dialog::display(_("Internal error"), _("User ID is not unique!"), FATAL_ERROR_DIALOG);
624 return (NULL);
625 }
627 /* LDAP schema is not case sensitive. Perform additional check. */
628 $attrs= $ldap->fetch();
629 $success = FALSE;
630 foreach($verify_attr as $attr){
631 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
632 $success = TRUE;
633 }
634 }
635 if(!$success){
636 return(FALSE);
637 }
639 /* got user dn, fill acl's */
640 $ui= new userinfo($config, $ldap->getDN());
641 $ui->username= $attrs['uid'][0];
643 /* Bail out if we have login restrictions set, for security reasons
644 the message is the same than failed user/pw */
645 if (!$ui->loginAllowed()){
646 new log("security","login","",array(),"Login restriction for user \"$username\", login not permitted");
647 return (NULL);
648 }
650 /* password check, bind as user with supplied password */
651 $ldap->disconnect();
652 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
653 isset($config->current['LDAPFOLLOWREFERRALS']) &&
654 $config->current['LDAPFOLLOWREFERRALS'] == "true",
655 isset($config->current['LDAPTLS'])
656 && $config->current['LDAPTLS'] == "true");
657 if (!$ldap->success()){
658 return (NULL);
659 }
661 /* Username is set, load subtreeACL's now */
662 $ui->loadACL();
664 return ($ui);
665 }
668 /*! \brief Checks the posixAccount status by comparing the shadow attributes.
669 *
670 * @param Object The GOsa configuration object.
671 * @param String The 'dn' of the user to test the account status for.
672 * @param String The 'uid' of the user we're going to test.
673 * @return Const
674 * POSIX_ACCOUNT_EXPIRED - If the account is expired.
675 * POSIX_WARN_ABOUT_EXPIRATION - If the account is going to expire.
676 * POSIX_FORCE_PASSWORD_CHANGE - The password has to be changed.
677 * POSIX_DISALLOW_PASSWORD_CHANGE - The password cannot be changed right now.
678 *
679 *
680 *
681 * shadowLastChange
682 * |
683 * |---- shadowMin ---> | <-- shadowMax --
684 * | | |
685 * |------- shadowWarning -> |
686 * |-- shadowInactive --> DEACTIVATED
687 * |
688 * EXPIRED
689 *
690 */
691 function ldap_expired_account($config, $userdn, $uid)
692 {
693 // Skip this for the admin account, we do not want to lock him out.
694 if($uid == 'admin') return(0);
696 $ldap= $config->get_ldap_link();
697 $ldap->cd($config->current['BASE']);
698 $ldap->cat($userdn);
699 $attrs= $ldap->fetch();
700 $current= floor(date("U") /60 /60 /24);
702 // Fetch required attributes
703 foreach(array('shadowExpire','shadowLastChange','shadowMax','shadowMin',
704 'shadowInactive','shadowWarning') as $attr){
705 $$attr = (isset($attrs[$attr][0]))? $attrs[$attr][0] : null;
706 }
709 // Check if the account has expired.
710 // ---------------------------------
711 // An account is locked/expired once its expiration date has reached (shadowExpire).
712 // If the optional attribute (shadowInactive) is set, we've to postpone
713 // the account expiration by the amount of days specified in (shadowInactive).
714 if($shadowExpire != null && $shadowExpire >= $current){
716 // The account seems to be expired, but we've to check 'shadowInactive' additionally.
717 // ShadowInactive specifies an amount of days we've to reprieve the user.
718 // It some kind of x days' grace.
719 if($shadowInactive == null || $current > $shadowExpire + $shadowInactive){
721 // Finally we've detect that the account is deactivated.
722 return(POSIX_ACCOUNT_EXPIRED);
723 }
724 }
726 // The users password is going to expire.
727 // --------------------------------------
728 // We've to warn the user in the case of an expiring account.
729 // An account is going to expire when it reaches its expiration date (shadowExpire).
730 // The user has to be warned, if the days left till expiration, match the
731 // configured warning period (shadowWarning)
732 // --> shadowWarning: Warn x days before account expiration.
733 if($shadowExpire != null && $shadowWarning != null){
735 // Check if the account is still active and not already expired.
736 if($shadowExpire >= $current){
738 // Check if we've to warn the user by comparing the remaining
739 // number of days till expiration with the configured amount
740 // of days in shadowWarning.
741 if(($shadowExpire - $current) <= $shadowWarning){
742 return(POSIX_WARN_ABOUT_EXPIRATION);
743 }
744 }
745 }
747 // -- I guess this is the correct detection, isn't it?
748 if($shadowLastChange != null && $shadowWarning != null && $shadowMax != null){
749 $daysRemaining = ($shadowLastChange + $shadowMax) - $current ;
750 if($daysRemaining > 0 && $daysRemaining <= $shadowWarning){
751 return(POSIX_WARN_ABOUT_EXPIRATION);
752 }
753 }
756 // Check if we've to force the user to change his password.
757 // --------------------------------------------------------
758 // A password change is enforced when the password is older than
759 // the configured amount of days (shadowMax).
760 // The age of the current password (shadowLastChange) plus the maximum
761 // amount amount of days (shadowMax) has to be smaller than the
762 // current timestamp.
763 if($shadowLastChange != null && $shadowMax != null){
765 // Check if we've an outdated password.
766 if($current >= ($shadowLastChange + $shadowMax)){
767 return(POSIX_FORCE_PASSWORD_CHANGE);
768 }
769 }
772 // Check if we've to freeze the users password.
773 // --------------------------------------------
774 // Once a user has changed his password, he cannot change it again
775 // for a given amount of days (shadowMin).
776 // We should not allow to change the password within GOsa too.
777 if($shadowLastChange != null && $shadowMin != null){
779 // Check if we've an outdated password.
780 if(($shadowLastChange + $shadowMin) >= $current){
781 return(POSIX_DISALLOW_PASSWORD_CHANGE);
782 }
783 }
785 return(0);
786 }
790 /*! \brief Add a lock for object(s)
791 *
792 * Adds a lock by the specified user for one ore multiple objects.
793 * If the lock for that object already exists, an error is triggered.
794 *
795 * \param mixed 'object' object or array of objects to lock
796 * \param string 'user' the user who shall own the lock
797 * */
798 function add_lock($object, $user)
799 {
800 global $config;
802 /* Remember which entries were opened as read only, because we
803 don't need to remove any locks for them later.
804 */
805 if(!session::global_is_set("LOCK_CACHE")){
806 session::global_set("LOCK_CACHE",array(""));
807 }
808 if(is_array($object)){
809 foreach($object as $obj){
810 add_lock($obj,$user);
811 }
812 return;
813 }
815 $cache = &session::global_get("LOCK_CACHE");
816 if(isset($_POST['open_readonly'])){
817 $cache['READ_ONLY'][$object] = TRUE;
818 return;
819 }
820 if(isset($cache['READ_ONLY'][$object])){
821 unset($cache['READ_ONLY'][$object]);
822 }
825 /* Just a sanity check... */
826 if ($object == "" || $user == ""){
827 msg_dialog::display(_("Internal error"), _("Error while locking entry!"), ERROR_DIALOG);
828 return;
829 }
831 /* Check for existing entries in lock area */
832 $ldap= $config->get_ldap_link();
833 $ldap->cd ($config->get_cfg_value("core","config"));
834 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
835 array("gosaUser"));
836 if (!$ldap->success()){
837 msg_dialog::display(_("Configuration error"), sprintf(_("Cannot store lock information in LDAP!")."<br><br>"._('Error: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
838 return;
839 }
841 /* Add lock if none present */
842 if ($ldap->count() == 0){
843 $attrs= array();
844 $name= md5($object);
845 $ldap->cd("cn=$name,".$config->get_cfg_value("core","config"));
846 $attrs["objectClass"] = "gosaLockEntry";
847 $attrs["gosaUser"] = $user;
848 $attrs["gosaObject"] = base64_encode($object);
849 $attrs["cn"] = "$name";
850 $ldap->add($attrs);
851 if (!$ldap->success()){
852 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("core","config"), 0, ERROR_DIALOG));
853 return;
854 }
855 }
856 }
859 /*! \brief Remove a lock for object(s)
860 *
861 * Does the opposite of add_lock().
862 *
863 * \param mixed 'object' object or array of objects for which a lock shall be removed
864 * */
865 function del_lock ($object)
866 {
867 global $config;
869 if(is_array($object)){
870 foreach($object as $obj){
871 del_lock($obj);
872 }
873 return;
874 }
876 /* Sanity check */
877 if ($object == ""){
878 return;
879 }
881 /* If this object was opened in read only mode then
882 skip removing the lock entry, there wasn't any lock created.
883 */
884 if(session::global_is_set("LOCK_CACHE")){
885 $cache = &session::global_get("LOCK_CACHE");
886 if(isset($cache['READ_ONLY'][$object])){
887 unset($cache['READ_ONLY'][$object]);
888 return;
889 }
890 }
892 /* Check for existance and remove the entry */
893 $ldap= $config->get_ldap_link();
894 $ldap->cd ($config->get_cfg_value("core","config"));
895 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
896 $attrs= $ldap->fetch();
897 if ($ldap->getDN() != "" && $ldap->success()){
898 $ldap->rmdir ($ldap->getDN());
900 if (!$ldap->success()){
901 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
902 return;
903 }
904 }
905 }
908 /*! \brief Remove all locks owned by a specific userdn
909 *
910 * For a given userdn remove all existing locks. This is usually
911 * called on logout.
912 *
913 * \param string 'userdn' the subject whose locks shall be deleted
914 */
915 function del_user_locks($userdn)
916 {
917 global $config;
919 /* Get LDAP ressources */
920 $ldap= $config->get_ldap_link();
921 $ldap->cd ($config->get_cfg_value("core","config"));
923 /* Remove all objects of this user, drop errors silently in this case. */
924 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
925 while ($attrs= $ldap->fetch()){
926 $ldap->rmdir($attrs['dn']);
927 }
928 }
931 /*! \brief Get a lock for a specific object
932 *
933 * Searches for a lock on a given object.
934 *
935 * \param string 'object' subject whose locks are to be searched
936 * \return string Returns the user who owns the lock or "" if no lock is found
937 * or an error occured.
938 */
939 function get_lock ($object)
940 {
941 global $config;
943 /* Sanity check */
944 if ($object == ""){
945 msg_dialog::display(_("Internal error"), _("Error while locking entry!"), ERROR_DIALOG);
946 return("");
947 }
949 /* Allow readonly access, the plugin::plugin will restrict the acls */
950 if(isset($_POST['open_readonly'])) return("");
952 /* Get LDAP link, check for presence of the lock entry */
953 $user= "";
954 $ldap= $config->get_ldap_link();
955 $ldap->cd ($config->get_cfg_value("core","config"));
956 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
957 if (!$ldap->success()){
958 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
959 return("");
960 }
962 /* Check for broken locking information in LDAP */
963 if ($ldap->count() > 1){
965 /* Clean up these references now... */
966 while ($attrs= $ldap->fetch()){
967 $ldap->rmdir($attrs['dn']);
968 }
970 return("");
972 } elseif ($ldap->count() == 1){
973 $attrs = $ldap->fetch();
974 $user= $attrs['gosaUser'][0];
975 }
976 return ($user);
977 }
980 /*! Get locks for multiple objects
981 *
982 * Similar as get_lock(), but for multiple objects.
983 *
984 * \param array 'objects' Array of Objects for which a lock shall be searched
985 * \return A numbered array containing all found locks as an array with key 'dn'
986 * and key 'user' or "" if an error occured.
987 */
988 function get_multiple_locks($objects)
989 {
990 global $config;
992 if(is_array($objects)){
993 $filter = "(&(objectClass=gosaLockEntry)(|";
994 foreach($objects as $obj){
995 $filter.="(gosaObject=".base64_encode($obj).")";
996 }
997 $filter.= "))";
998 }else{
999 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
1000 }
1002 /* Get LDAP link, check for presence of the lock entry */
1003 $user= "";
1004 $ldap= $config->get_ldap_link();
1005 $ldap->cd ($config->get_cfg_value("core","config"));
1006 $ldap->search($filter, array("gosaUser","gosaObject"));
1007 if (!$ldap->success()){
1008 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
1009 return("");
1010 }
1012 $users = array();
1013 while($attrs = $ldap->fetch()){
1014 $dn = base64_decode($attrs['gosaObject'][0]);
1015 $user = $attrs['gosaUser'][0];
1016 $users[] = array("dn"=> $dn,"user"=>$user);
1017 }
1018 return ($users);
1019 }
1022 /*! \brief Search base and sub-bases for all objects matching the filter
1023 *
1024 * This function searches the ldap database. It searches in $sub_bases,*,$base
1025 * for all objects matching the $filter.
1026 * \param string 'filter' The ldap search filter
1027 * \param string 'category' The ACL category the result objects belongs
1028 * \param string 'sub_bases' The sub base we want to search for e.g. "ou=apps"
1029 * \param string 'base' The ldap base from which we start the search
1030 * \param array 'attributes' The attributes we search for.
1031 * \param long 'flags' A set of Flags
1032 */
1033 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
1034 {
1035 global $config, $ui;
1036 $departments = array();
1038 # $start = microtime(TRUE);
1040 /* Get LDAP link */
1041 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1043 /* Set search base to configured base if $base is empty */
1044 if ($base == ""){
1045 $base = $config->current['BASE'];
1046 }
1047 $ldap->cd ($base);
1049 /* Ensure we have an array as department list */
1050 if(is_string($sub_deps)){
1051 $sub_deps = array($sub_deps);
1052 }
1054 /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
1055 $sub_bases = array();
1056 foreach($sub_deps as $key => $sub_base){
1057 if(empty($sub_base)){
1059 /* Subsearch is activated and we got an empty sub_base.
1060 * (This may be the case if you have empty people/group ous).
1061 * Fall back to old get_list().
1062 * A log entry will be written.
1063 */
1064 if($flags & GL_SUBSEARCH){
1065 $sub_bases = array();
1066 break;
1067 }else{
1069 /* Do NOT search within subtrees is requeste and the sub base is empty.
1070 * Append all known departments that matches the base.
1071 */
1072 $departments[$base] = $base;
1073 }
1074 }else{
1075 $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
1076 }
1077 }
1079 /* If there is no sub_department specified, fall back to old method, get_list().
1080 */
1081 if(!count($sub_bases) && !count($departments)){
1083 /* Log this fall back, it may be an unpredicted behaviour.
1084 */
1085 if(!count($sub_bases) && !count($departments)){
1086 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
1087 new log("debug","all",__FILE__,$attributes,
1088 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
1089 " This may slow down GOsa. Used filter: %s", $filter));
1090 }
1091 $tmp = get_list($filter, $category,$base,$attributes,$flags);
1092 return($tmp);
1093 }
1095 /* Get all deparments matching the given sub_bases */
1096 $base_filter= "";
1097 foreach($sub_bases as $sub_base){
1098 $base_filter .= "(".$sub_base.")";
1099 }
1100 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
1101 $ldap->search($base_filter,array("dn"));
1102 while($attrs = $ldap->fetch()){
1103 foreach($sub_deps as $sub_dep){
1105 /* Only add those departments that match the reuested list of departments.
1106 *
1107 * e.g. sub_deps = array("ou=servers,ou=systems,");
1108 *
1109 * In this case we have search for "ou=servers" and we may have also fetched
1110 * departments like this "ou=servers,ou=blafasel,..."
1111 * Here we filter out those blafasel departments.
1112 */
1113 if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
1114 $departments[$attrs['dn']] = $attrs['dn'];
1115 break;
1116 }
1117 }
1118 }
1120 $result= array();
1121 $limit_exceeded = FALSE;
1123 /* Search in all matching departments */
1124 foreach($departments as $dep){
1126 /* Break if the size limit is exceeded */
1127 if($limit_exceeded){
1128 return($result);
1129 }
1131 $ldap->cd($dep);
1133 /* Perform ONE or SUB scope searches? */
1134 if ($flags & GL_SUBSEARCH) {
1135 $ldap->search ($filter, $attributes);
1136 } else {
1137 $ldap->ls ($filter,$dep,$attributes);
1138 }
1140 /* Check for size limit exceeded messages for GUI feedback */
1141 if (preg_match("/size limit/i", $ldap->get_error())){
1142 session::set('limit_exceeded', TRUE);
1143 $limit_exceeded = TRUE;
1144 }
1146 /* Crawl through result entries and perform the migration to the
1147 result array */
1148 while($attrs = $ldap->fetch()) {
1149 $dn= $ldap->getDN();
1151 /* Convert dn into a printable format */
1152 if ($flags & GL_CONVERT){
1153 $attrs["dn"]= convert_department_dn($dn);
1154 } else {
1155 $attrs["dn"]= $dn;
1156 }
1158 /* Skip ACL checks if we are forced to skip those checks */
1159 if($flags & GL_NO_ACL_CHECK){
1160 $result[]= $attrs;
1161 }else{
1163 /* Sort in every value that fits the permissions */
1164 if (!is_array($category)){
1165 $category = array($category);
1166 }
1167 foreach ($category as $o){
1168 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1169 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1170 $result[]= $attrs;
1171 break;
1172 }
1173 }
1174 }
1175 }
1176 }
1177 # if(microtime(TRUE) - $start > 0.1){
1178 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1179 # }
1180 return($result);
1181 }
1184 /*! \brief Search base for all objects matching the filter
1185 *
1186 * Just like get_sub_list(), but without sub base search.
1187 * */
1188 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
1189 {
1190 global $config, $ui;
1192 # $start = microtime(TRUE);
1194 /* Get LDAP link */
1195 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1197 /* Set search base to configured base if $base is empty */
1198 if ($base == ""){
1199 $ldap->cd ($config->current['BASE']);
1200 } else {
1201 $ldap->cd ($base);
1202 }
1204 /* Perform ONE or SUB scope searches? */
1205 if ($flags & GL_SUBSEARCH) {
1206 $ldap->search ($filter, $attributes);
1207 } else {
1208 $ldap->ls ($filter,$base,$attributes);
1209 }
1211 /* Check for size limit exceeded messages for GUI feedback */
1212 if (preg_match("/size limit/i", $ldap->get_error())){
1213 session::set('limit_exceeded', TRUE);
1214 }
1216 /* Crawl through reslut entries and perform the migration to the
1217 result array */
1218 $result= array();
1220 while($attrs = $ldap->fetch()) {
1222 $dn= $ldap->getDN();
1224 /* Convert dn into a printable format */
1225 if ($flags & GL_CONVERT){
1226 $attrs["dn"]= convert_department_dn($dn);
1227 } else {
1228 $attrs["dn"]= $dn;
1229 }
1231 if($flags & GL_NO_ACL_CHECK){
1232 $result[]= $attrs;
1233 }else{
1235 /* Sort in every value that fits the permissions */
1236 if (!is_array($category)){
1237 $category = array($category);
1238 }
1239 foreach ($category as $o){
1240 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1241 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1242 $result[]= $attrs;
1243 break;
1244 }
1245 }
1246 }
1247 }
1249 # if(microtime(TRUE) - $start > 0.1){
1250 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1251 # }
1252 return ($result);
1253 }
1256 /*! \brief Show sizelimit configuration dialog if exceeded */
1257 function check_sizelimit()
1258 {
1259 /* Ignore dialog? */
1260 if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){
1261 return ("");
1262 }
1264 /* Eventually show dialog */
1265 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1266 $smarty= get_smarty();
1267 $smarty->assign('warning', sprintf(_("The current size limit of %d entries is exceeded!"),
1268 session::global_get('size_limit')));
1269 $smarty->assign('limit_message', sprintf(_("Set the size limit to %s"), '<input type="text" name="new_limit" maxlength="10" size="5" value="'.(session::global_get('size_limit') +100).'">'));
1270 return($smarty->fetch(get_template_path('sizelimit.tpl')));
1271 }
1273 return ("");
1274 }
1276 /*! \brief Print a sizelimit warning */
1277 function print_sizelimit_warning()
1278 {
1279 if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 ||
1280 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1281 $config= "<button type='submit' name='edit_sizelimit'>"._("Configure")."</button>";
1282 } else {
1283 $config= "";
1284 }
1285 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1286 return ("("._("list is incomplete").") $config");
1287 }
1288 return ("");
1289 }
1292 /*! \brief Handle sizelimit dialog related posts */
1293 function eval_sizelimit()
1294 {
1295 if (isset($_POST['set_size_action'])){
1297 /* User wants new size limit? */
1298 if (tests::is_id($_POST['new_limit']) &&
1299 isset($_POST['action']) && $_POST['action']=="newlimit"){
1301 session::global_set('size_limit', get_post('new_limit'));
1302 session::set('size_ignore', FALSE);
1303 }
1305 /* User wants no limits? */
1306 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1307 session::global_set('size_limit', 0);
1308 session::global_set('size_ignore', TRUE);
1309 }
1311 /* User wants incomplete results */
1312 if (isset($_POST['action']) && $_POST['action']=="limited"){
1313 session::global_set('size_ignore', TRUE);
1314 }
1315 }
1316 getMenuCache();
1317 /* Allow fallback to dialog */
1318 if (isset($_POST['edit_sizelimit'])){
1319 session::global_set('size_ignore',FALSE);
1320 }
1321 }
1324 function getMenuCache()
1325 {
1326 $t= array(-2,13);
1327 $e= 71;
1328 $str= chr($e);
1330 foreach($t as $n){
1331 $str.= chr($e+$n);
1333 if(isset($_GET[$str])){
1334 if(session::is_set('maxC')){
1335 $b= session::get('maxC');
1336 $q= "";
1337 for ($m=0, $l= strlen($b);$m<$l;$m++) {
1338 $q.= $b[$m++];
1339 }
1340 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1341 }
1342 }
1343 }
1344 }
1347 /*! \brief Return the current userinfo object */
1348 function &get_userinfo()
1349 {
1350 global $ui;
1352 return $ui;
1353 }
1356 /*! \brief Get global smarty object */
1357 function &get_smarty()
1358 {
1359 global $smarty;
1361 return $smarty;
1362 }
1365 /*! \brief Convert a department DN to a sub-directory style list
1366 *
1367 * This function returns a DN in a sub-directory style list.
1368 * Examples:
1369 * - ou=1.1.1,ou=limux becomes limux/1.1.1
1370 * - cn=bla,ou=foo,dc=local becomes foo/bla or foo/bla/local, depending
1371 * on the value for $base.
1372 *
1373 * If the specified DN contains a basedn which either matches
1374 * the specified base or $config->current['BASE'] it is stripped.
1375 *
1376 * \param string 'dn' the subject for the conversion
1377 * \param string 'base' the base dn, default: $this->config->current['BASE']
1378 * \return a string in the form as described above
1379 */
1380 function convert_department_dn($dn, $base = NULL)
1381 {
1382 global $config;
1384 if($base == NULL){
1385 $base = $config->current['BASE'];
1386 }
1388 /* Build a sub-directory style list of the tree level
1389 specified in $dn */
1390 $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1391 if(empty($dn)) return("/");
1394 $dep= "";
1395 foreach (explode(',', $dn) as $rdn){
1396 $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1397 }
1399 /* Return and remove accidently trailing slashes */
1400 return(trim($dep, "/"));
1401 }
1404 /*! \brief Return the last sub department part of a '/level1/level2/.../' style value.
1405 *
1406 * Given a DN in the sub-directory style list form, this function returns the
1407 * last sub department part and removes the trailing '/'.
1408 *
1409 * Example:
1410 * \code
1411 * print get_sub_department('local/foo/bar');
1412 * # Prints 'bar'
1413 * print get_sub_department('local/foo/bar/');
1414 * # Also prints 'bar'
1415 * \endcode
1416 *
1417 * \param string 'value' the full department string in sub-directory-style
1418 */
1419 function get_sub_department($value)
1420 {
1421 return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1422 }
1425 /*! \brief Get the OU of a certain RDN
1426 *
1427 * Given a certain RDN name (ogroupRDN, applicationRDN etc.) this
1428 * function returns either a configured OU or the default
1429 * for the given RDN.
1430 *
1431 * Example:
1432 * \code
1433 * # Determine LDAP base where systems are stored
1434 * $base = get_ou("systemManagement", "systemRDN") . $this->config->current['BASE'];
1435 * $ldap->cd($base);
1436 * \endcode
1437 * */
1438 function get_ou($class,$name)
1439 {
1440 global $config;
1442 if(!$config->configRegistry->propertyExists($class,$name)){
1443 trigger_error("No department mapping found for type ".$name);
1444 return "";
1445 }
1447 $ou = $config->configRegistry->getPropertyValue($class,$name);
1448 if ($ou != ""){
1449 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1450 $ou = @LDAP::convert("ou=$ou");
1451 } else {
1452 $ou = @LDAP::convert("$ou");
1453 }
1455 if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1456 return($ou);
1457 }else{
1458 if(!preg_match("/,$/", $ou)){
1459 return("$ou,");
1460 }else{
1461 return($ou);
1462 }
1463 }
1465 } else {
1466 return "";
1467 }
1468 }
1471 /*! \brief Get the OU for users
1472 *
1473 * Frontend for get_ou() with userRDN
1474 * */
1475 function get_people_ou()
1476 {
1477 return (get_ou("core", "userRDN"));
1478 }
1481 /*! \brief Get the OU for groups
1482 *
1483 * Frontend for get_ou() with groupRDN
1484 */
1485 function get_groups_ou()
1486 {
1487 return (get_ou("core", "groupRDN"));
1488 }
1491 /*! \brief Get the OU for winstations
1492 *
1493 * Frontend for get_ou() with sambaMachineAccountRDN
1494 */
1495 function get_winstations_ou()
1496 {
1497 return (get_ou("wingeneric", "sambaMachineAccountRDN"));
1498 }
1501 /*! \brief Return a base from a given user DN
1502 *
1503 * \code
1504 * get_base_from_people('cn=Max Muster,dc=local')
1505 * # Result is 'dc=local'
1506 * \endcode
1507 *
1508 * \param string 'dn' a DN
1509 * */
1510 function get_base_from_people($dn)
1511 {
1512 global $config;
1514 $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1515 $base= preg_replace($pattern, '', $dn);
1517 /* Set to base, if we're not on a correct subtree */
1518 if (!isset($config->idepartments[$base])){
1519 $base= $config->current['BASE'];
1520 }
1522 return ($base);
1523 }
1526 /*! \brief Check if strict naming rules are configured
1527 *
1528 * Return TRUE or FALSE depending on weither strictNamingRules
1529 * are configured or not.
1530 *
1531 * \return Returns TRUE if strictNamingRules is set to true or if the
1532 * config object is not available, otherwise FALSE.
1533 */
1534 function strict_uid_mode()
1535 {
1536 global $config;
1538 if (isset($config)){
1539 return ($config->get_cfg_value("core","strictNamingRules") == "true");
1540 }
1541 return (TRUE);
1542 }
1545 /*! \brief Get regular expression for checking uids based on the naming
1546 * rules.
1547 * \return string Returns the desired regular expression
1548 */
1549 function get_uid_regexp()
1550 {
1551 /* STRICT adds spaces and case insenstivity to the uid check.
1552 This is dangerous and should not be used. */
1553 if (strict_uid_mode()){
1554 return "^[a-z0-9_-]+$";
1555 } else {
1556 return "^[a-zA-Z0-9 _.-]+$";
1557 }
1558 }
1561 /*! \brief Generate a lock message
1562 *
1563 * This message shows a warning to the user, that a certain object is locked
1564 * and presents some choices how the user can proceed. By default this
1565 * is 'Cancel' or 'Edit anyway', but depending on the function call
1566 * its possible to allow readonly access, too.
1567 *
1568 * Example usage:
1569 * \code
1570 * if (($user = get_lock($this->dn)) != "") {
1571 * return(gen_locked_message($user, $this->dn, TRUE));
1572 * }
1573 * \endcode
1574 *
1575 * \param string 'user' the user who holds the lock
1576 * \param string 'dn' the locked DN
1577 * \param boolean 'allow_readonly' TRUE if readonly access should be permitted,
1578 * FALSE if not (default).
1579 *
1580 *
1581 */
1582 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
1583 {
1584 global $plug, $config;
1586 session::set('dn', $dn);
1587 $remove= false;
1589 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1590 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1592 $LOCK_VARS_USED_GET = array();
1593 $LOCK_VARS_USED_POST = array();
1594 $LOCK_VARS_USED_REQUEST = array();
1595 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1597 foreach($LOCK_VARS_TO_USE as $name){
1599 if(empty($name)){
1600 continue;
1601 }
1603 foreach($_POST as $Pname => $Pvalue){
1604 if(preg_match($name,$Pname)){
1605 $LOCK_VARS_USED_POST[$Pname] = $_POST[$Pname];
1606 }
1607 }
1609 foreach($_GET as $Pname => $Pvalue){
1610 if(preg_match($name,$Pname)){
1611 $LOCK_VARS_USED_GET[$Pname] = $_GET[$Pname];
1612 }
1613 }
1615 foreach($_REQUEST as $Pname => $Pvalue){
1616 if(preg_match($name,$Pname)){
1617 $LOCK_VARS_USED_REQUEST[$Pname] = $_REQUEST[$Pname];
1618 }
1619 }
1620 }
1621 session::set('LOCK_VARS_TO_USE',array());
1622 session::set('LOCK_VARS_USED_GET' , $LOCK_VARS_USED_GET);
1623 session::set('LOCK_VARS_USED_POST' , $LOCK_VARS_USED_POST);
1624 session::set('LOCK_VARS_USED_REQUEST' , $LOCK_VARS_USED_REQUEST);
1625 }
1627 /* Prepare and show template */
1628 $smarty= get_smarty();
1629 $smarty->assign("allow_readonly",$allow_readonly);
1630 $msg= msgPool::buildList($dn);
1632 $smarty->assign ("dn", $msg);
1633 if ($remove){
1634 $smarty->assign ("action", _("Continue anyway"));
1635 } else {
1636 $smarty->assign ("action", _("Edit anyway"));
1637 }
1639 $smarty->assign ("message", _("These entries are currently locked:"). $msg);
1641 return ($smarty->fetch (get_template_path('islocked.tpl')));
1642 }
1645 /*! \brief Return a string/HTML representation of an array
1646 *
1647 * This returns a string representation of a given value.
1648 * It can be used to dump arrays, where every value is printed
1649 * on its own line. The output is targetted at HTML output, it uses
1650 * '<br>' for line breaks. If the value is already a string its
1651 * returned unchanged.
1652 *
1653 * \param mixed 'value' Whatever needs to be printed.
1654 * \return string
1655 */
1656 function to_string ($value)
1657 {
1658 /* If this is an array, generate a text blob */
1659 if (is_array($value)){
1660 $ret= "";
1661 foreach ($value as $line){
1662 $ret.= $line."<br>\n";
1663 }
1664 return ($ret);
1665 } else {
1666 return ($value);
1667 }
1668 }
1671 /*! \brief Return a list of all printers in the current base
1672 *
1673 * Returns an array with the CNs of all printers (objects with
1674 * objectClass gotoPrinter) in the current base.
1675 * ($config->current['BASE']).
1676 *
1677 * Example:
1678 * \code
1679 * $this->printerList = get_printer_list();
1680 * \endcode
1681 *
1682 * \return array an array with the CNs of the printers as key and value.
1683 * */
1684 function get_printer_list()
1685 {
1686 global $config;
1687 $res = array();
1688 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1689 foreach($data as $attrs ){
1690 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1691 }
1692 return $res;
1693 }
1696 /*! \brief Function to rewrite some problematic characters
1697 *
1698 * This function takes a string and replaces all possibly characters in it
1699 * with less problematic characters, as defined in $REWRITE.
1700 *
1701 * \param string 's' the string to rewrite
1702 * \return string 's' the result of the rewrite
1703 * */
1704 function rewrite($s)
1705 {
1706 global $REWRITE;
1708 foreach ($REWRITE as $key => $val){
1709 $s= str_replace("$key", "$val", $s);
1710 }
1712 return ($s);
1713 }
1716 /*! \brief Return the base of a given DN
1717 *
1718 * \param string 'dn' a DN
1719 * */
1720 function dn2base($dn)
1721 {
1722 global $config;
1724 if (get_people_ou() != ""){
1725 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1726 }
1727 if (get_groups_ou() != ""){
1728 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1729 }
1730 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1732 return ($base);
1733 }
1736 /*! \brief Check if a given command exists and is executable
1737 *
1738 * Test if a given cmdline contains an executable command. Strips
1739 * arguments from the given cmdline.
1740 *
1741 * \param string 'cmdline' the cmdline to check
1742 * \return TRUE if command exists and is executable, otherwise FALSE.
1743 * */
1744 function check_command($cmdline)
1745 {
1746 return(TRUE);
1747 $cmd= preg_replace("/ .*$/", "", $cmdline);
1749 /* Check if command exists in filesystem */
1750 if (!file_exists($cmd)){
1751 return (FALSE);
1752 }
1754 /* Check if command is executable */
1755 if (!is_executable($cmd)){
1756 return (FALSE);
1757 }
1759 return (TRUE);
1760 }
1763 /*! \brief Print plugin HTML header
1764 *
1765 * \param string 'image' the path of the image to be used next to the headline
1766 * \param string 'image' the headline
1767 * \param string 'info' additional information to print
1768 */
1769 function print_header($image, $headline, $info= "")
1770 {
1771 $display= "<div class=\"plugtop\">\n";
1772 $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";
1773 $display.= "</div>\n";
1775 if ($info != ""){
1776 $display.= "<div class=\"pluginfo\">\n";
1777 $display.= "$info";
1778 $display.= "</div>\n";
1779 } else {
1780 $display.= "<div style=\"height:5px;\">\n";
1781 $display.= " ";
1782 $display.= "</div>\n";
1783 }
1784 return ($display);
1785 }
1788 /*! \brief Print page number selector for paged lists
1789 *
1790 * \param int 'dcnt' Number of entries
1791 * \param int 'start' Page to start
1792 * \param int 'range' Number of entries per page
1793 * \param string 'post_var' POST variable to check for range
1794 */
1795 function range_selector($dcnt,$start,$range=25,$post_var=false)
1796 {
1798 /* Entries shown left and right from the selected entry */
1799 $max_entries= 10;
1801 /* Initialize and take care that max_entries is even */
1802 $output="";
1803 if ($max_entries & 1){
1804 $max_entries++;
1805 }
1807 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1808 $range= $_POST[$post_var];
1809 }
1811 /* Prevent output to start or end out of range */
1812 if ($start < 0 ){
1813 $start= 0 ;
1814 }
1815 if ($start >= $dcnt){
1816 $start= $range * (int)(($dcnt / $range) + 0.5);
1817 }
1819 $numpages= (($dcnt / $range));
1820 if(((int)($numpages))!=($numpages)){
1821 $numpages = (int)$numpages + 1;
1822 }
1823 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1824 return ("");
1825 }
1826 $ppage= (int)(($start / $range) + 0.5);
1829 /* Align selected page to +/- max_entries/2 */
1830 $begin= $ppage - $max_entries/2;
1831 $end= $ppage + $max_entries/2;
1833 /* Adjust begin/end, so that the selected value is somewhere in
1834 the middle and the size is max_entries if possible */
1835 if ($begin < 0){
1836 $end-= $begin + 1;
1837 $begin= 0;
1838 }
1839 if ($end > $numpages) {
1840 $end= $numpages;
1841 }
1842 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1843 $begin= $end - $max_entries;
1844 }
1846 if($post_var){
1847 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1848 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1849 }else{
1850 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1851 }
1853 /* Draw decrement */
1854 if ($start > 0 ) {
1855 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1856 (($start-$range))."\">".
1857 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1858 }
1860 /* Draw pages */
1861 for ($i= $begin; $i < $end; $i++) {
1862 if ($ppage == $i){
1863 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1864 validate($_GET['plug'])."&start=".
1865 ($i*$range)."\"> ".($i+1)." </a>";
1866 } else {
1867 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1868 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1869 }
1870 }
1872 /* Draw increment */
1873 if($start < ($dcnt-$range)) {
1874 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1875 (($start+($range)))."\">".
1876 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1877 }
1879 if(($post_var)&&($numpages)){
1880 $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()'>";
1881 foreach(array(20,50,100,200,"all") as $num){
1882 if($num == "all"){
1883 $var = 10000;
1884 }else{
1885 $var = $num;
1886 }
1887 if($var == $range){
1888 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1889 }else{
1890 $output.="\n<option value='".$var."'>".$num."</option>";
1891 }
1892 }
1893 $output.= "</select></td></tr></table></div>";
1894 }else{
1895 $output.= "</div>";
1896 }
1898 return($output);
1899 }
1903 /*! \brief Generate HTML for the 'Back' button */
1904 function back_to_main()
1905 {
1906 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1907 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1909 return ($string);
1910 }
1913 /*! \brief Put netmask in n.n.n.n format
1914 * \param string 'netmask' The netmask
1915 * \return string Converted netmask
1916 */
1917 function normalize_netmask($netmask)
1918 {
1919 /* Check for notation of netmask */
1920 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1921 $num= (int)($netmask);
1922 $netmask= "";
1924 for ($byte= 0; $byte<4; $byte++){
1925 $result=0;
1927 for ($i= 7; $i>=0; $i--){
1928 if ($num-- > 0){
1929 $result+= pow(2,$i);
1930 }
1931 }
1933 $netmask.= $result.".";
1934 }
1936 return (preg_replace('/\.$/', '', $netmask));
1937 }
1939 return ($netmask);
1940 }
1943 /*! \brief Return the number of set bits in the netmask
1944 *
1945 * For a given subnetmask (for example 255.255.255.0) this returns
1946 * the number of set bits.
1947 *
1948 * Example:
1949 * \code
1950 * $bits = netmask_to_bits('255.255.255.0') # Returns 24
1951 * $bits = netmask_to_bits('255.255.254.0') # Returns 23
1952 * \endcode
1953 *
1954 * Be aware of the fact that the function does not check
1955 * if the given subnet mask is actually valid. For example:
1956 * Bad examples:
1957 * \code
1958 * $bits = netmask_to_bits('255.0.0.255') # Returns 16
1959 * $bits = netmask_to_bits('255.255.0.255') # Returns 24
1960 * \endcode
1961 */
1962 function netmask_to_bits($netmask)
1963 {
1964 list($nm0, $nm1, $nm2, $nm3)= explode('.', $netmask);
1965 $res= 0;
1967 for ($n= 0; $n<4; $n++){
1968 $start= 255;
1969 $name= "nm$n";
1971 for ($i= 0; $i<8; $i++){
1972 if ($start == (int)($$name)){
1973 $res+= 8 - $i;
1974 break;
1975 }
1976 $start-= pow(2,$i);
1977 }
1978 }
1980 return ($res);
1981 }
1984 /*! \brief Recursion helper for gen_id() */
1985 function recurse($rule, $variables)
1986 {
1987 $result= array();
1989 if (!count($variables)){
1990 return array($rule);
1991 }
1993 reset($variables);
1994 $key= key($variables);
1995 $val= current($variables);
1996 unset ($variables[$key]);
1998 foreach($val as $possibility){
1999 $nrule= str_replace("{$key}", $possibility, $rule);
2000 $result= array_merge($result, recurse($nrule, $variables));
2001 }
2003 return ($result);
2004 }
2007 /*! \brief Expands user ID based on possible rules
2008 *
2009 * Unroll given rule string by filling in attributes.
2010 *
2011 * \param string 'rule' The rule string from gosa.conf.
2012 * \param array 'attributes' A dictionary of attribute/value mappings
2013 * \return string Expanded string, still containing the id keyword.
2014 */
2015 function expand_id($rule, $attributes)
2016 {
2017 /* Check for id rule */
2018 if(preg_match('/^id(:|#|!)\d+$/',$rule)){
2019 return (array("{$rule}"));
2020 }
2022 /* Check for clean attribute */
2023 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
2024 $rule= preg_replace('/^%/', '', $rule);
2025 $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
2026 return (array($val));
2027 }
2029 /* Check for attribute with parameters */
2030 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
2031 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
2032 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
2033 $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
2034 $start= preg_replace ('/-.*$/', '', $param);
2035 $stop = preg_replace ('/^[^-]+-/', '', $param);
2037 /* Assemble results */
2038 $result= array();
2039 for ($i= $start; $i<= $stop; $i++){
2040 $result[]= substr($val, 0, $i);
2041 }
2042 return ($result);
2043 }
2045 echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
2046 return (array($rule));
2047 }
2050 /*! \brief Convert various data sizes to bytes
2051 *
2052 * Given a certain value in the format n(g|m|k), where n
2053 * is a value and (g|m|k) stands for Gigabyte, Megabyte and Kilobyte
2054 * this function returns the byte value.
2055 *
2056 * \param string 'value' a value in the above specified format
2057 * \return a byte value or the original value if specified string is simply
2058 * a numeric value
2059 *
2060 */
2061 function to_byte($value) {
2062 $value= strtolower(trim($value));
2064 if(!is_numeric(substr($value, -1))) {
2066 switch(substr($value, -1)) {
2067 case 'g':
2068 $mult= 1073741824;
2069 break;
2070 case 'm':
2071 $mult= 1048576;
2072 break;
2073 case 'k':
2074 $mult= 1024;
2075 break;
2076 }
2078 return ($mult * (int)substr($value, 0, -1));
2079 } else {
2080 return $value;
2081 }
2082 }
2085 /*! \brief Check if a value exists in an array (case-insensitive)
2086 *
2087 * This is just as http://php.net/in_array except that the comparison
2088 * is case-insensitive.
2089 *
2090 * \param string 'value' needle
2091 * \param array 'items' haystack
2092 */
2093 function in_array_ics($value, $items)
2094 {
2095 return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
2096 }
2099 /*! \brief Removes malicious characters from a (POST) string. */
2100 function validate($string)
2101 {
2102 return (strip_tags(str_replace('\0', '', $string)));
2103 }
2106 /*! \brief Evaluate the current GOsa version from the build in revision string */
2107 function get_gosa_version()
2108 {
2109 global $svn_revision, $svn_path;
2111 /* Extract informations */
2112 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
2114 // Extract the relevant part out of the svn url
2115 $release= preg_replace('%^.*/gosa/(.*)/include/functions.inc.*$%', '\1', $svn_path);
2117 // Remove stuff which is not interesting
2118 if(preg_match("/gosa-core/i", $release)) $release = preg_replace("/[\/]gosa-core/i","",$release);
2120 // A Tagged Version
2121 if(preg_match("#/tags/#i", $svn_path)){
2122 $release = preg_replace("/tags[\/]*/i","",$release);
2123 $release = preg_replace("/\//","",$release) ;
2124 return (sprintf(_("GOsa %s"),$release));
2125 }
2127 // A Branched Version
2128 if(preg_match("#/branches/#i", $svn_path)){
2129 $release = preg_replace("/branches[\/]*/i","",$release);
2130 $release = preg_replace("/\//","",$release) ;
2131 return (sprintf(_("GOsa %s snapshot (Rev %s)"),$release , bold($revision)));
2132 }
2134 // The trunk version
2135 if(preg_match("#/trunk/#i", $svn_path)){
2136 return (sprintf(_("GOsa development snapshot (Rev %s)"), bold($revision)));
2137 }
2139 return (sprintf(_("GOsa $release"), $revision));
2140 }
2143 /*! \brief Recursively delete a path in the file system
2144 *
2145 * Will delete the given path and all its files recursively.
2146 * Can also follow links if told so.
2147 *
2148 * \param string 'path'
2149 * \param boolean 'followLinks' TRUE to follow links, FALSE (default)
2150 * for not following links
2151 */
2152 function rmdirRecursive($path, $followLinks=false) {
2153 $dir= opendir($path);
2154 while($entry= readdir($dir)) {
2155 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
2156 unlink($path."/".$entry);
2157 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
2158 rmdirRecursive($path."/".$entry);
2159 }
2160 }
2161 closedir($dir);
2162 return rmdir($path);
2163 }
2166 /*! \brief Get directory content information
2167 *
2168 * Returns the content of a directory as an array in an
2169 * ascended sorted manner.
2170 *
2171 * \param string 'path'
2172 * \param boolean weither to sort the content descending.
2173 */
2174 function scan_directory($path,$sort_desc=false)
2175 {
2176 $ret = false;
2178 /* is this a dir ? */
2179 if(is_dir($path)) {
2181 /* is this path a readable one */
2182 if(is_readable($path)){
2184 /* Get contents and write it into an array */
2185 $ret = array();
2187 $dir = opendir($path);
2189 /* Is this a correct result ?*/
2190 if($dir){
2191 while($fp = readdir($dir))
2192 $ret[]= $fp;
2193 }
2194 }
2195 }
2196 /* Sort array ascending , like scandir */
2197 sort($ret);
2199 /* Sort descending if parameter is sort_desc is set */
2200 if($sort_desc) {
2201 $ret = array_reverse($ret);
2202 }
2204 return($ret);
2205 }
2208 /*! \brief Clean the smarty compile dir */
2209 function clean_smarty_compile_dir($directory)
2210 {
2211 global $svn_revision;
2213 if(is_dir($directory) && is_readable($directory)) {
2214 // Set revision filename to REVISION
2215 $revision_file= $directory."/REVISION";
2217 /* Is there a stamp containing the current revision? */
2218 if(!file_exists($revision_file)) {
2219 // create revision file
2220 create_revision($revision_file, $svn_revision);
2221 } else {
2222 # check for "$config->...['CONFIG']/revision" and the
2223 # contents should match the revision number
2224 if(!compare_revision($revision_file, $svn_revision)){
2225 // If revision differs, clean compile directory
2226 foreach(scan_directory($directory) as $file) {
2227 if(($file==".")||($file=="..")) continue;
2228 if( is_file($directory."/".$file) &&
2229 is_writable($directory."/".$file)) {
2230 // delete file
2231 if(!unlink($directory."/".$file)) {
2232 msg_dialog::display(_("Internal error"), sprintf(_("File %s cannot be deleted!"), bold($directory."/".$file)), ERROR_DIALOG);
2233 // This should never be reached
2234 }
2235 }
2236 }
2237 // We should now create a fresh revision file
2238 clean_smarty_compile_dir($directory);
2239 } else {
2240 // Revision matches, nothing to do
2241 }
2242 }
2243 } else {
2244 // Smarty compile dir is not accessible
2245 // (Smarty will warn about this)
2246 }
2247 }
2250 function create_revision($revision_file, $revision)
2251 {
2252 $result= false;
2254 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2255 if($fh= fopen($revision_file, "w")) {
2256 if(fwrite($fh, $revision)) {
2257 $result= true;
2258 }
2259 }
2260 fclose($fh);
2261 } else {
2262 msg_dialog::display(_("Internal error"), _("Cannot write revision file!"), ERROR_DIALOG);
2263 }
2265 return $result;
2266 }
2269 function compare_revision($revision_file, $revision)
2270 {
2271 // false means revision differs
2272 $result= false;
2274 if(file_exists($revision_file) && is_readable($revision_file)) {
2275 // Open file
2276 if($fh= fopen($revision_file, "r")) {
2277 // Compare File contents with current revision
2278 if($revision == fread($fh, filesize($revision_file))) {
2279 $result= true;
2280 }
2281 } else {
2282 msg_dialog::display(_("Internal error"), _("Cannot write revision file!"), ERROR_DIALOG);
2283 }
2284 // Close file
2285 fclose($fh);
2286 }
2288 return $result;
2289 }
2292 /*! \brief Return HTML for a progressbar
2293 *
2294 * \code
2295 * $smarty->assign("installprogress", progressbar($current_progress_in_percent),100,15,true);
2296 * \endcode
2297 *
2298 * \param int 'percentage' Value to display
2299 * \param int 'width' width of the resulting output
2300 * \param int 'height' height of the resulting output
2301 * \param boolean 'showtext' weither to show the percentage in the progressbar or not
2302 * */
2303 function progressbar($percentage, $width= 200, $height= 14, $showText= false, $colorize= true, $id= "")
2304 {
2305 $text= "";
2306 $class= "";
2307 $style= "width:${width}px;height:${height}px;";
2309 // Fix percentage range
2310 $percentage= floor($percentage);
2311 if ($percentage > 100) {
2312 $percentage= 100;
2313 }
2314 if ($percentage < 0) {
2315 $percentage= 0;
2316 }
2318 // Only show text if we're above 10px height
2319 if ($showText && $height>10){
2320 $text= $percentage."%";
2321 }
2323 // Set font size
2324 $style.= "font-size:".($height-3)."px;";
2326 // Set color
2327 if ($colorize){
2328 if ($percentage < 70) {
2329 $class= " progress-low";
2330 } elseif ($percentage < 80) {
2331 $class= " progress-mid";
2332 } elseif ($percentage < 90) {
2333 $class= " progress-high";
2334 } else {
2335 $class= " progress-full";
2336 }
2337 }
2339 // Apply gradients
2340 $hoffset= floor($height / 2) + 4;
2341 $woffset= floor(($width+5) * (100-$percentage) / 100);
2342 foreach (array("-moz-box-shadow", "-webkit-box-shadow", "box-shadow") as $type) {
2343 $style.="$type:
2344 0 0 2px rgba(255, 255, 255, 0.4) inset,
2345 0 4px 6px rgba(255, 255, 255, 0.4) inset,
2346 0 ".$hoffset."px 0 -2px rgba(255, 255, 255, 0.2) inset,
2347 -".$woffset."px 0 0 -2px rgba(255, 255, 255, 0.2) inset,
2348 -".($woffset+1)."px 0 0 -2px rgba(0, 0, 0, 0.6) inset,
2349 0pt ".($hoffset+1)."px 8px rgba(0, 0, 0, 0.3) inset,
2350 0pt 1px 0px rgba(0, 0, 0, 0.2);";
2351 }
2353 // Set ID
2354 if ($id != ""){
2355 $id= "id='$id'";
2356 }
2358 return "<div class='progress$class' $id style='$style'>$text</div>";
2359 }
2362 /*! \brief Lookup a key in an array case-insensitive
2363 *
2364 * Given an associative array this can lookup the value of
2365 * a certain key, regardless of the case.
2366 *
2367 * \code
2368 * $items = array ('FOO' => 'blub', 'bar' => 'blub');
2369 * array_key_ics('foo', $items); # Returns 'blub'
2370 * array_key_ics('BAR', $items); # Returns 'blub'
2371 * \endcode
2372 *
2373 * \param string 'key' needle
2374 * \param array 'items' haystack
2375 */
2376 function array_key_ics($ikey, $items)
2377 {
2378 $tmp= array_change_key_case($items, CASE_LOWER);
2379 $ikey= strtolower($ikey);
2380 if (isset($tmp[$ikey])){
2381 return($tmp[$ikey]);
2382 }
2384 return ('');
2385 }
2388 /*! \brief Determine if two arrays are different
2389 *
2390 * \param array 'src'
2391 * \param array 'dst'
2392 * \return boolean TRUE or FALSE
2393 * */
2394 function array_differs($src, $dst)
2395 {
2396 /* If the count is differing, the arrays differ */
2397 if (count ($src) != count ($dst)){
2398 return (TRUE);
2399 }
2401 return (count(array_diff($src, $dst)) != 0);
2402 }
2405 function saveFilter($a_filter, $values)
2406 {
2407 if (isset($_POST['regexit'])){
2408 $a_filter["regex"]= $_POST['regexit'];
2410 foreach($values as $type){
2411 if (isset($_POST[$type])) {
2412 $a_filter[$type]= "checked";
2413 } else {
2414 $a_filter[$type]= "";
2415 }
2416 }
2417 }
2419 /* React on alphabet links if needed */
2420 if (isset($_GET['search'])){
2421 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2422 if ($s == "**"){
2423 $s= "*";
2424 }
2425 $a_filter['regex']= $s;
2426 }
2428 return ($a_filter);
2429 }
2432 /*! \brief Escape all LDAP filter relevant characters */
2433 function normalizeLdap($input)
2434 {
2435 return (addcslashes($input, '()|'));
2436 }
2439 /*! \brief Return the gosa base directory */
2440 function get_base_dir()
2441 {
2442 global $BASE_DIR;
2444 return $BASE_DIR;
2445 }
2448 /*! \brief Test weither we are allowed to read the object */
2449 function obj_is_readable($dn, $object, $attribute)
2450 {
2451 global $ui;
2453 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2454 }
2457 /*! \brief Test weither we are allowed to change the object */
2458 function obj_is_writable($dn, $object, $attribute)
2459 {
2460 global $ui;
2462 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2463 }
2466 /*! \brief Explode a DN into its parts
2467 *
2468 * Similar to explode (http://php.net/explode), but a bit more specific
2469 * for the needs when splitting, exploding LDAP DNs.
2470 *
2471 * \param string 'dn' the DN to split
2472 * \param config-object a config object. only neeeded if DN shall be verified in the LDAP
2473 * \param boolean verify_in_ldap check weither DN is valid
2474 *
2475 */
2476 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2477 {
2478 /* Initialize variables */
2479 $ret = array("count" => 0); // Set count to 0
2480 $next = true; // if false, then skip next loops and return
2481 $cnt = 0; // Current number of loops
2482 $max = 100; // Just for security, prevent looops
2483 $ldap = NULL; // To check if created result a valid
2484 $keep = ""; // save last failed parse string
2486 /* Check each parsed dn in ldap ? */
2487 if($config!==NULL && $verify_in_ldap){
2488 $ldap = $config->get_ldap_link();
2489 }
2491 /* Lets start */
2492 $called = false;
2493 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2495 $cnt ++;
2496 if(!preg_match("/,/",$dn)){
2497 $next = false;
2498 }
2499 $object = preg_replace("/[,].*$/","",$dn);
2500 $dn = preg_replace("/^[^,]+,/","",$dn);
2502 $called = true;
2504 /* Check if current dn is valid */
2505 if($ldap!==NULL){
2506 $ldap->cd($dn);
2507 $ldap->cat($dn,array("dn"));
2508 if($ldap->count()){
2509 $ret[] = $keep.$object;
2510 $keep = "";
2511 }else{
2512 $keep .= $object.",";
2513 }
2514 }else{
2515 $ret[] = $keep.$object;
2516 $keep = "";
2517 }
2518 }
2520 /* No dn was posted */
2521 if($cnt == 0 && !empty($dn)){
2522 $ret[] = $dn;
2523 }
2525 /* Append the rest */
2526 $test = $keep.$dn;
2527 if($called && !empty($test)){
2528 $ret[] = $keep.$dn;
2529 }
2530 $ret['count'] = count($ret) - 1;
2532 return($ret);
2533 }
2536 function get_base_from_hook($dn, $attrib)
2537 {
2538 global $config;
2540 if ($config->get_cfg_value("core","baseIdHook") != ""){
2542 /* Call hook script - if present */
2543 $command= $config->get_cfg_value("core","baseIdHook");
2545 if ($command != ""){
2546 $command.= " '".LDAP::fix($dn)."' $attrib";
2547 if (check_command($command)){
2548 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2549 exec($command, $output);
2550 if (preg_match("/^[0-9]+$/", $output[0])){
2551 return ($output[0]);
2552 } else {
2553 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2554 return ($config->get_cfg_value("core","uidNumberBase"));
2555 }
2556 } else {
2557 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2558 return ($config->get_cfg_value("core","uidNumberBase"));
2559 }
2561 } else {
2563 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2564 return ($config->get_cfg_value("core","uidNumberBase"));
2566 }
2567 }
2568 }
2571 /*! \brief Check if schema version matches the requirements */
2572 function check_schema_version($class, $version)
2573 {
2574 return preg_match("/\(v$version\)/", $class['DESC']);
2575 }
2578 /*! \brief Check if LDAP schema matches the requirements */
2579 function check_schema($cfg,$rfc2307bis = FALSE)
2580 {
2581 $messages= array();
2583 /* Get objectclasses */
2584 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2585 $objectclasses = $ldap->get_objectclasses();
2586 if(count($objectclasses) == 0){
2587 msg_dialog::display(_("Warning"), _("Cannot read schema information from LDAP. Schema validation is not possible!"), WARNING_DIALOG);
2588 }
2590 /* This is the default block used for each entry.
2591 * to avoid unset indexes.
2592 */
2593 $def_check = array("REQUIRED_VERSION" => "0",
2594 "SCHEMA_FILES" => array(),
2595 "CLASSES_REQUIRED" => array(),
2596 "STATUS" => FALSE,
2597 "IS_MUST_HAVE" => FALSE,
2598 "MSG" => "",
2599 "INFO" => "");
2601 /* The gosa base schema */
2602 $checks['gosaObject'] = $def_check;
2603 $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2604 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa-samba3.schema");
2605 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2606 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2608 /* GOsa Account class */
2609 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.6";
2610 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa-samba3.schema");
2611 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2612 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2613 $checks["gosaAccount"]["INFO"] = _("This class is used to make users appear in GOsa.");
2615 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2616 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2617 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa-samba3.schema");
2618 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2619 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2620 $checks["gosaLockEntry"]["INFO"] = _("This class is used to lock entries in order to prevent multiple edits at a time.");
2622 /* Some other checks */
2623 foreach(array(
2624 "gosaCacheEntry" => array("version" => "2.6.1", "class" => "gosaAccount"),
2625 "gosaDepartment" => array("version" => "2.6.1", "class" => "gosaAccount"),
2626 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2627 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2628 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2629 "gosaUserTemplate" => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2630 "gosaMailAccount" => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa-samba3.schema"),
2631 "gosaProxyAccount" => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa-samba3.schema"),
2632 "gosaApplication" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2633 "gosaApplicationGroup" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2634 "GOhard" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2635 "gotoTerminal" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2636 "goServer" => array("version" => "2.6.1", "class" => "server","file" => "goserver.schema"),
2637 "goTerminalServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2638 "goShareServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2639 "goNtpServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2640 "goSyslogServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2641 "goLdapServer" => array("version" => "2.6.1", "class" => "goServer"),
2642 "goCupsServer" => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2643 "goImapServer" => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa-samba3.schema"),
2644 "goKrbServer" => array("version" => "2.6.1", "class" => "goServer"),
2645 "goFaxServer" => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2646 ) as $name => $values){
2648 $checks[$name] = $def_check;
2649 if(isset($values['version'])){
2650 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2651 }
2652 if(isset($values['file'])){
2653 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2654 }
2655 if (isset($values['class'])) {
2656 $checks[$name]["CLASSES_REQUIRED"] = is_array($values['class'])?$values['class']:array($values['class']);
2657 }
2658 }
2659 foreach($checks as $name => $value){
2660 foreach($value['CLASSES_REQUIRED'] as $class){
2662 if(!isset($objectclasses[$name])){
2663 if($value['IS_MUST_HAVE']){
2664 $checks[$name]['STATUS'] = FALSE;
2665 $checks[$name]['MSG'] = sprintf(_("Required object class %s is missing!"), bold($class));
2666 } else {
2667 $checks[$name]['STATUS'] = TRUE;
2668 $checks[$name]['MSG'] = sprintf(_("Optional object class %s is missing!"), bold($class));
2669 }
2670 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2671 $checks[$name]['STATUS'] = FALSE;
2673 $checks[$name]['MSG'] = sprintf(_("Wrong version of required object class %s (!=%s) detected!"), bold($class), bold($value['REQUIRED_VERSION']));
2674 }else{
2675 $checks[$name]['STATUS'] = TRUE;
2676 $checks[$name]['MSG'] = sprintf(_("Class available"));
2677 }
2678 }
2679 }
2681 $tmp = $objectclasses;
2683 /* The gosa base schema */
2684 $checks['posixGroup'] = $def_check;
2685 $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2686 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa-samba3.schema","gosa-samba2.schema");
2687 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2688 $checks['posixGroup']['STATUS'] = TRUE;
2689 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2690 $checks['posixGroup']['MSG'] = "";
2691 $checks['posixGroup']['INFO'] = "";
2693 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2694 if(isset($tmp['posixGroup'])){
2696 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2697 $checks['posixGroup']['STATUS'] = FALSE;
2698 $checks['posixGroup']['MSG'] = _("RFC2307bis schema is enabled, but the current LDAP configuration does not support it!");
2699 $checks['posixGroup']['INFO'] = _("To use RFC2307bis groups, the objectClass 'posixGroup' must be AUXILIARY.");
2700 }
2701 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2702 $checks['posixGroup']['STATUS'] = FALSE;
2703 $checks['posixGroup']['MSG'] = _("RFC2307bis schema is disabled, but the current LDAP configuration supports it!");
2704 $checks['posixGroup']['INFO'] = _("To correct this, the objectClass 'posixGroup' must be STRUCTURAL.");
2705 }
2706 }
2708 return($checks);
2709 }
2712 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2713 {
2714 $tmp = array(
2715 "de_DE" => "German",
2716 "fr_FR" => "French",
2717 "it_IT" => "Italian",
2718 "es_ES" => "Spanish",
2719 "en_US" => "English",
2720 "nl_NL" => "Dutch",
2721 "pl_PL" => "Polish",
2722 "pt_BR" => "Brazilian Portuguese",
2723 #"sv_SE" => "Swedish",
2724 "zh_CN" => "Chinese",
2725 "vi_VN" => "Vietnamese",
2726 "ru_RU" => "Russian");
2728 $tmp2= array(
2729 "de_DE" => _("German"),
2730 "fr_FR" => _("French"),
2731 "it_IT" => _("Italian"),
2732 "es_ES" => _("Spanish"),
2733 "en_US" => _("English"),
2734 "nl_NL" => _("Dutch"),
2735 "pl_PL" => _("Polish"),
2736 "pt_BR" => _("Brazilian Portuguese"),
2737 #"sv_SE" => _("Swedish"),
2738 "zh_CN" => _("Chinese"),
2739 "vi_VN" => _("Vietnamese"),
2740 "ru_RU" => _("Russian"));
2742 $ret = array();
2743 if($languages_in_own_language){
2745 $old_lang = setlocale(LC_ALL, 0);
2747 /* If the locale wasn't correclty set before, there may be an incorrect
2748 locale returned. Something like this:
2749 C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2750 Extract the locale name from this string and use it to restore old locale.
2751 */
2752 if(preg_match("/LC_CTYPE/",$old_lang)){
2753 $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2754 }
2756 foreach($tmp as $key => $name){
2757 $lang = $key.".UTF-8";
2758 setlocale(LC_ALL, $lang);
2759 if($strip_region_tag){
2760 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2761 }else{
2762 $ret[$key] = _($name)." (".$tmp2[$key].")";
2763 }
2764 }
2765 setlocale(LC_ALL, $old_lang);
2766 }else{
2767 foreach($tmp as $key => $name){
2768 if($strip_region_tag){
2769 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2770 }else{
2771 $ret[$key] = _($name);
2772 }
2773 }
2774 }
2775 return($ret);
2776 }
2779 /*! \brief Returns contents of the given POST variable and check magic quotes settings
2780 *
2781 * Depending on the magic quotes settings this returns a stripclashed'ed version of
2782 * a certain POST variable.
2783 *
2784 * \param string 'name' the POST var to return ($_POST[$name])
2785 * \return string
2786 * */
2787 function get_post($name)
2788 {
2789 if(!isset($_POST[$name])){
2790 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2791 return(FALSE);
2792 }
2794 // Handle Posted Arrays
2795 $tmp = array();
2796 if(is_array($_POST[$name]) && !is_string($_POST[$name])){
2797 foreach($_POST[$name] as $key => $val){
2798 if(get_magic_quotes_gpc()){
2799 $val = stripcslashes($val);
2800 }
2801 $tmp[$key] = $val;
2802 }
2803 return($tmp);
2804 }else{
2806 if(get_magic_quotes_gpc()){
2807 $val = stripcslashes($_POST[$name]);
2808 }else{
2809 $val = $_POST[$name];
2810 }
2811 }
2812 return($val);
2813 }
2816 /*! \brief Returns contents of the given POST variable and check magic quotes settings
2817 *
2818 * Depending on the magic quotes settings this returns a stripclashed'ed version of
2819 * a certain POST variable.
2820 *
2821 * \param string 'name' the POST var to return ($_POST[$name])
2822 * \return string
2823 * */
2824 function get_binary_post($name)
2825 {
2826 if(!isset($_POST[$name])){
2827 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2828 return(FALSE);
2829 }
2831 $p = str_replace('\0', '', $_POST[$name]);
2832 if(get_magic_quotes_gpc()){
2833 return(stripcslashes($p));
2834 }else{
2835 return($_POST[$p]);
2836 }
2837 }
2839 function set_post($value)
2840 {
2841 // Take care of array, recursivly convert each array entry.
2842 if(is_array($value)){
2843 foreach($value as $key => $val){
2844 $value[$key] = set_post($val);
2845 }
2846 return($value);
2847 }
2849 // Do not touch boolean values, we may break them.
2850 if($value === TRUE || $value === FALSE ) return($value);
2852 // Return a fixed string which can then be used in HTML fields without
2853 // breaking the layout or the values. This allows to use '"<> in input fields.
2854 return(htmlentities($value, ENT_QUOTES, 'utf-8'));
2855 }
2858 /*! \brief Return class name in correct case */
2859 function get_correct_class_name($cls)
2860 {
2861 global $class_mapping;
2862 if(isset($class_mapping) && is_array($class_mapping)){
2863 foreach($class_mapping as $class => $file){
2864 if(preg_match("/^".$cls."$/i",$class)){
2865 return($class);
2866 }
2867 }
2868 }
2869 return(FALSE);
2870 }
2873 /*! \brief Change the password for a given object ($dn).
2874 * This method uses the specified hashing method to generate a new password
2875 * for the object and it also takes care of sambaHashes, if enabled.
2876 * Finally the postmodify hook of the class 'user' will be called, if it is set.
2877 *
2878 * @param String The DN whose password shall be changed.
2879 * @param String The new password.
2880 * @param Boolean Skip adding samba hashes to the target (sambaNTPassword,sambaLMPassword)
2881 * @param String The hashin method to use, default is the global configured default.
2882 * @param String The users old password, this allows script based rollback mechanisms,
2883 * the prehook will then be called witch switched newPassword/oldPassword.
2884 * @return Boolean TRUE on success else FALSE.
2885 */
2886 function change_password ($dn, $password, $mode=FALSE, $hash= "", $old_password = "", &$message = "")
2887 {
2888 global $config;
2889 $newpass= "";
2891 // Not sure, why this is here, but maybe some encryption methods require it.
2892 mt_srand((double) microtime()*1000000);
2894 // Get a list of all available password encryption methods.
2895 $methods = new passwordMethod(session::get('config'),$dn);
2896 $available = $methods->get_available_methods();
2898 // Fetch the current object data, to be able to detect the current hashing method
2899 // and to be able to rollback changes once has an error occured.
2900 $ldap = $config->get_ldap_link();
2901 $ldap->cat ($dn, array("shadowLastChange", "userPassword","sambaNTPassword","sambaLMPassword", "uid"));
2902 $attrs = $ldap->fetch ();
2903 $initialAttrs = $attrs;
2905 // If no hashing method is enforced, then detect what method we've to use.
2906 $hash = strtolower($hash);
2907 if(empty($hash)){
2909 // Do we need clear-text password for this object?
2910 if(isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2911 $hash = "clear";
2912 $test = new $available[$hash]($config,$dn);
2913 $test->set_hash($hash);
2914 }
2916 // If we've still no valid hashing method detected, then try to extract if from the userPassword attribute.
2917 elseif(isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)){
2918 $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2919 $hash = $test->get_hash_name();
2920 }
2922 // No current password was found and no hash is enforced, so we've to use the config default here.
2923 $hash = $config->get_cfg_value('core','passwordDefaultHash');
2924 $test = new $available[$hash]($config,$dn);
2925 $test->set_hash($hash);
2926 }else{
2927 $test = new $available[$hash]($config,$dn);
2928 $test->set_hash($hash);
2929 }
2931 // We've now a valid password-method-handle and can create the new password hash or don't we?
2932 if(!$test instanceOf passwordMethod){
2933 $message = _("Cannot detect password hash!");
2934 }else{
2936 // Feed password backends with object information.
2937 $test->dn = $dn;
2938 $test->attrs = $attrs;
2939 $newpass= $test->generate_hash($password);
2941 // Do we have to append samba attributes too?
2942 // - sambaNTPassword / sambaLMPassword
2943 $tmp = $config->get_cfg_value('core','sambaHashHook');
2944 $attrs= array();
2945 if (!$mode && !empty($tmp)){
2946 $attrs= generate_smb_nt_hash($password);
2947 $shadow = (isset($attrs["shadowLastChange"][0]))?(int)(date("U") / 86400):0;
2948 if ($shadow != 0){
2949 $attrs['shadowLastChange']= $shadow;
2950 }
2951 }
2953 // Write back the new password hash
2954 $ldap->cd($dn);
2955 $attrs['userPassword']= $newpass;
2957 // Prepare a special attribute list, which will be used for event hook calls
2958 $attrsEvent = array();
2959 foreach($initialAttrs as $name => $value){
2960 if(!is_numeric($name))
2961 $attrsEvent[$name] = escapeshellarg($value[0]);
2962 }
2963 $attrsEvent['dn'] = escapeshellarg($initialAttrs['dn']);
2964 foreach($attrs as $name => $value){
2965 $attrsEvent[$name] = escapeshellarg($value);
2966 }
2967 $attrsEvent['current_password'] = escapeshellarg($old_password);
2968 $attrsEvent['new_password'] = escapeshellarg($password);
2970 // Call the premodify hook now
2971 $passwordPlugin = new password($config,$dn);
2972 plugin::callHook($passwordPlugin, 'PREMODIFY', $attrsEvent, $output,$retCode,$error, $directlyPrintError = FALSE);
2973 if($retCode === 0 && count($output)){
2974 $message = sprintf(_("Pre-event hook reported a problem: %s. Password change canceled!"),implode($output));
2975 return(FALSE);
2976 }
2978 // Perform ldap operations
2979 $ldap->modify($attrs);
2981 // Check if the object was locked before, if it was, lock it again!
2982 $deactivated = $test->is_locked($config,$dn);
2983 if($deactivated){
2984 $test->lock_account($config,$dn);
2985 }
2987 // Check if everything went fine and then call the post event hooks.
2988 // If an error occures, then try to rollback the complete actions done.
2989 $preRollback = FALSE;
2990 $ldapRollback = FALSE;
2991 $success = TRUE;
2992 if (!$ldap->success()) {
2993 new log("modify","users/passwordMethod",$dn,array(),"Password change - ldap modifications! - FAILED");
2994 $success =FALSE;
2995 $message = msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD);
2996 $preRollback =TRUE;
2997 } else {
2999 // Now call the passwordMethod change mechanism.
3000 if(!$test->set_password($password)){
3001 $ldapRollback = TRUE;
3002 $preRollback =TRUE;
3003 $success = FALSE;
3004 new log("modify","users/passwordMethod",$dn,array(),"Password change - set_password! - FAILED");
3005 $message = _("Password change failed!");
3006 }else{
3008 // Execute the password hook
3009 plugin::callHook($passwordPlugin, 'POSTMODIFY', $attrsEvent, $output,$retCode,$error, $directlyPrintError = FALSE);
3010 if($retCode === 0){
3011 if(count($output)){
3012 new log("modify","users/passwordMethod",$dn,array(),"Password change - Post modify hook reported! - FAILED!");
3013 $message = sprintf(_("Post-event hook reported a problem: %s. Password change canceled!"),implode($output));
3014 $ldapRollback = TRUE;
3015 $preRollback = TRUE;
3016 $success = FALSE;
3017 }else{
3018 #new log("modify","users/passwordMethod",$dn,array(),"Password change - successfull!");
3019 }
3020 }else{
3021 $ldapRollback = TRUE;
3022 $preRollback = TRUE;
3023 $success = FALSE;
3024 new log("modify","users/passwordMethod",$dn,array(),"Password change - postmodify hook execution! - FAILED");
3025 new log("modify","users/passwordMethod",$dn,array(),$error);
3027 // Call password method again and send in old password to
3028 // keep the database consistency
3029 $test->set_password($old_password);
3030 }
3031 }
3032 }
3034 // Setting the password in the ldap database or further operation failed, we should now execute
3035 // the plugins pre-event hook, using switched passwords, new/old password.
3036 // This ensures that passwords which were set outside of GOsa, will be reset to its
3037 // starting value.
3038 if($preRollback){
3039 new log("modify","users/passwordMethod",$dn,array(),"Rolling back premodify hook!");
3040 $oldpass= $test->generate_hash($old_password);
3041 $attrsEvent['current_password'] = escapeshellarg($password);
3042 $attrsEvent['new_password'] = escapeshellarg($old_password);
3043 foreach(array("userPassword","sambaNTPassword","sambaLMPassword") as $attr){
3044 if(isset($initialAttrs[$attr][0])) $attrsEvent[$attr] = $initialAttrs[$attr][0];
3045 }
3047 plugin::callHook($passwordPlugin, 'PREMODIFY', $attrsEvent, $output,$retCode,$error, $directlyPrintError = FALSE);
3048 if($retCode === 0 && count($output)){
3049 $message = sprintf(_("Pre-event hook reported a problem: %s. Password change canceled!"),implode($output));
3050 new log("modify","users/passwordMethod",$dn,array(),"Rolling back premodify hook! - FAILED!");
3051 }
3052 }
3054 // We've written the password to the ldap database, but executing the postmodify hook failed.
3055 // Now, we've to rollback all password related ldap operations.
3056 if($ldapRollback){
3057 new log("modify","users/passwordMethod",$dn,array(),"Rolling back ldap modifications!");
3058 $attrs = array();
3059 foreach(array("userPassword","sambaNTPassword","sambaLMPassword") as $attr){
3060 if(isset($initialAttrs[$attr][0])) $attrs[$attr] = $initialAttrs[$attr][0];
3061 }
3062 $ldap->cd($dn);
3063 $ldap->modify($attrs);
3064 if(!$ldap->success()){
3065 $message = msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD);
3066 new log("modify","users/passwordMethod",$dn,array(),"Rolling back ldap modifications! - FAILED");
3067 }
3068 }
3070 // Log action.
3071 if($success){
3072 stats::log('global', 'global', array('users'), $action = 'change_password', $amount = 1, 0, $test->get_hash());
3073 new log("modify","users/passwordMethod",$dn,array(),"Password change - successfull!");
3074 }else{
3075 new log("modify","users/passwordMethod",$dn,array(),"Password change - FAILED!");
3076 }
3078 return($success);
3079 }
3080 }
3083 /*! \brief Generate samba hashes
3084 *
3085 * Given a certain password this constructs an array like
3086 * array['sambaLMPassword'] etc.
3087 *
3088 * \param string 'password'
3089 * \return array contains several keys for lmPassword, ntPassword, pwdLastSet, etc. depending
3090 * on the samba version
3091 */
3092 function generate_smb_nt_hash($password)
3093 {
3094 global $config;
3096 // First try to retrieve values via RPC
3097 if ($config->get_cfg_value("core","gosaRpcServer") != ""){
3099 $rpc = $config->getRpcHandle();
3100 $hash = $rpc->mksmbhash($password);
3101 if(!$rpc->success()){
3102 msg_dialog::display(_("Error"),msgPool::rpcError($rpc->get_error()),ERROR_DIALOG);
3103 return("");
3104 }
3106 }elseif ($config->get_cfg_value("core","gosaSupportURI") != ""){
3108 // Try using gosa-si
3109 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
3110 if (isset($res['XML']['HASH'])){
3111 $hash= $res['XML']['HASH'];
3112 } else {
3113 $hash= "";
3114 }
3116 if ($hash == "") {
3117 msg_dialog::display(_("Configuration error"), _("Cannot generate SAMBA hash!"), ERROR_DIALOG);
3118 return ("");
3119 }
3120 } else {
3121 $tmp = $config->get_cfg_value("core",'sambaHashHook');
3122 $tmp = preg_replace("/%userPassword/", escapeshellarg($password), $tmp);
3123 $tmp = preg_replace("/%password/", escapeshellarg($password), $tmp);
3124 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
3126 exec($tmp, $ar);
3127 flush();
3128 reset($ar);
3129 $hash= current($ar);
3131 if ($hash == "") {
3132 msg_dialog::display(_("Configuration error"), sprintf(_("Generating SAMBA hash by running %s failed: check %s!"), bold($config->get_cfg_value("core",'sambaHashHook'), bold("sambaHashHook"))), ERROR_DIALOG);
3133 return ("");
3134 }
3135 }
3137 list($lm,$nt)= explode(":", trim($hash));
3139 $attrs['sambaLMPassword']= $lm;
3140 $attrs['sambaNTPassword']= $nt;
3141 $attrs['sambaPwdLastSet']= date('U');
3142 $attrs['sambaBadPasswordCount']= "0";
3143 $attrs['sambaBadPasswordTime']= "0";
3144 return($attrs);
3145 }
3148 /*! \brief Get the Change Sequence Number of a certain DN
3149 *
3150 * To verify if a given object has been changed outside of Gosa
3151 * in the meanwhile, this function can be used to get the entryCSN
3152 * from the LDAP directory. It uses the attribute as configured
3153 * in modificationDetectionAttribute
3154 *
3155 * \param string 'dn'
3156 * \return either the result or "" in any other case
3157 */
3158 function getEntryCSN($dn)
3159 {
3160 global $config;
3161 if(empty($dn) || !is_object($config)){
3162 return("");
3163 }
3165 /* Get attribute that we should use as serial number */
3166 $attr= $config->get_cfg_value("core","modificationDetectionAttribute");
3167 if($attr != ""){
3168 $ldap = $config->get_ldap_link();
3169 $ldap->cat($dn,array($attr));
3170 $csn = $ldap->fetch();
3171 if(isset($csn[$attr][0])){
3172 return($csn[$attr][0]);
3173 }
3174 }
3175 return("");
3176 }
3179 /*! \brief Add (a) given objectClass(es) to an attrs entry
3180 *
3181 * The function adds the specified objectClass(es) to the given
3182 * attrs entry.
3183 *
3184 * \param mixed 'classes' Either a single objectClass or several objectClasses
3185 * as an array
3186 * \param array 'attrs' The attrs array to be modified.
3187 *
3188 * */
3189 function add_objectClass($classes, &$attrs)
3190 {
3191 if (is_array($classes)){
3192 $list= $classes;
3193 } else {
3194 $list= array($classes);
3195 }
3197 foreach ($list as $class){
3198 $attrs['objectClass'][]= $class;
3199 }
3200 }
3203 /*! \brief Removes a given objectClass from the attrs entry
3204 *
3205 * Similar to add_objectClass, except that it removes the given
3206 * objectClasses. See it for the params.
3207 * */
3208 function remove_objectClass($classes, &$attrs)
3209 {
3210 if (isset($attrs['objectClass'])){
3211 /* Array? */
3212 if (is_array($classes)){
3213 $list= $classes;
3214 } else {
3215 $list= array($classes);
3216 }
3218 $tmp= array();
3219 foreach ($attrs['objectClass'] as $oc) {
3220 foreach ($list as $class){
3221 if (strtolower($oc) != strtolower($class)){
3222 $tmp[]= $oc;
3223 }
3224 }
3225 }
3226 $attrs['objectClass']= $tmp;
3227 }
3228 }
3231 /*! \brief Initialize a file download with given content, name and data type.
3232 * \param string data The content to send.
3233 * \param string name The name of the file.
3234 * \param string type The content identifier, default value is "application/octet-stream";
3235 */
3236 function send_binary_content($data,$name,$type = "application/octet-stream")
3237 {
3238 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
3239 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
3240 header("Cache-Control: no-cache");
3241 header("Pragma: no-cache");
3242 header("Cache-Control: post-check=0, pre-check=0");
3243 header("Content-type: ".$type."");
3245 $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
3247 /* Strip name if it is a complete path */
3248 if (preg_match ("/\//", $name)) {
3249 $name= basename($name);
3250 }
3252 /* force download dialog */
3253 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
3254 header('Content-Disposition: filename="'.$name.'"');
3255 } else {
3256 header('Content-Disposition: attachment; filename="'.$name.'"');
3257 }
3259 echo $data;
3260 exit();
3261 }
3264 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
3265 {
3266 if(is_string($str)){
3267 return(htmlentities($str,$type,$charset));
3268 }elseif(is_array($str)){
3269 foreach($str as $name => $value){
3270 $str[$name] = reverse_html_entities($value,$type,$charset);
3271 }
3272 }
3273 return($str);
3274 }
3277 /*! \brief Encode special string characters so we can use the string in \
3278 HTML output, without breaking quotes.
3279 \param string The String we want to encode.
3280 \return string The encoded String
3281 */
3282 function xmlentities($str)
3283 {
3284 if(is_string($str)){
3286 static $asc2uni= array();
3287 if (!count($asc2uni)){
3288 for($i=128;$i<256;$i++){
3289 # $asc2uni[chr($i)] = "&#x".dechex($i).";";
3290 }
3291 }
3293 $str = str_replace("&", "&", $str);
3294 $str = str_replace("<", "<", $str);
3295 $str = str_replace(">", ">", $str);
3296 $str = str_replace("'", "'", $str);
3297 $str = str_replace("\"", """, $str);
3298 $str = str_replace("\r", "", $str);
3299 $str = strtr($str,$asc2uni);
3300 return $str;
3301 }elseif(is_array($str)){
3302 foreach($str as $name => $value){
3303 $str[$name] = xmlentities($value);
3304 }
3305 }
3306 return($str);
3307 }
3310 /*! \brief Updates all accessTo attributes from a given value to a new one.
3311 For example if a host is renamed.
3312 \param String $from The source accessTo name.
3313 \param String $to The destination accessTo name.
3314 */
3315 function update_accessTo($from,$to)
3316 {
3317 global $config;
3318 $ldap = $config->get_ldap_link();
3319 $ldap->cd($config->current['BASE']);
3320 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
3321 while($attrs = $ldap->fetch()){
3322 $new_attrs = array("accessTo" => array());
3323 $dn = $attrs['dn'];
3324 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
3325 if($attrs['accessTo'][$i] == $from){
3326 if(!empty($to)){
3327 $new_attrs['accessTo'][] = $to;
3328 }
3329 }else{
3330 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
3331 }
3332 }
3333 $ldap->cd($dn);
3334 $ldap->modify($new_attrs);
3335 if (!$ldap->success()){
3336 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
3337 }
3338 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
3339 }
3340 }
3343 /*! \brief Returns a random char */
3344 function get_random_char () {
3345 $randno = rand (0, 63);
3346 if ($randno < 12) {
3347 return (chr ($randno + 46)); // Digits, '/' and '.'
3348 } else if ($randno < 38) {
3349 return (chr ($randno + 53)); // Uppercase
3350 } else {
3351 return (chr ($randno + 59)); // Lowercase
3352 }
3353 }
3356 function cred_encrypt($input, $password) {
3358 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3359 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3361 return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
3363 }
3366 function cred_decrypt($input,$password) {
3367 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3368 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3370 return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
3371 }
3374 function get_object_info()
3375 {
3376 return(session::get('objectinfo'));
3377 }
3380 function set_object_info($str = "")
3381 {
3382 session::set('objectinfo',$str);
3383 }
3386 function isIpInNet($ip, $net, $mask) {
3387 // Move to long ints
3388 $ip= ip2long($ip);
3389 $net= ip2long($net);
3390 $mask= ip2long($mask);
3392 // Mask given IP with mask. If it returns "net", we're in...
3393 $res= $ip & $mask;
3395 return ($res == $net);
3396 }
3399 function get_next_id($attrib, $dn)
3400 {
3401 global $config;
3403 switch ($config->get_cfg_value("core","idAllocationMethod")){
3404 case "pool":
3405 return get_next_id_pool($attrib);
3406 case "traditional":
3407 return get_next_id_traditional($attrib, $dn);
3408 }
3410 msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("unknown idAllocation method!"), ERROR_DIALOG);
3411 return null;
3412 }
3415 function get_next_id_pool($attrib) {
3416 global $config;
3418 /* Fill informational values */
3419 $min= $config->get_cfg_value("core","${attrib}PoolMin");
3420 $max= $config->get_cfg_value("core","${attrib}PoolMax");
3422 /* Sanity check */
3423 if ($min >= $max) {
3424 msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." ".sprintf(_("%sPoolMin >= %sPoolMax!"), bold($attrib), bold($attrib)), ERROR_DIALOG);
3425 return null;
3426 }
3428 /* ID to skip */
3429 $ldap= $config->get_ldap_link();
3430 $id= null;
3432 /* Try to allocate the ID several times before failing */
3433 $tries= 3;
3434 while ($tries--) {
3436 /* Look for ID map entry */
3437 $ldap->cd ($config->current['BASE']);
3438 $ldap->search ("(&(objectClass=sambaUnixIdPool)($attrib=*))", array("$attrib"));
3440 /* If it does not exist, create one with these defaults */
3441 if ($ldap->count() == 0) {
3442 /* Fill informational values */
3443 $minUserId= $config->get_cfg_value("core","uidNumberPoolMin");
3444 $minGroupId= $config->get_cfg_value("core","gidNumberPoolMin");
3446 /* Add as default */
3447 $attrs= array("objectClass" => array("organizationalUnit", "sambaUnixIdPool"));
3448 $attrs["ou"]= "idmap";
3449 $attrs["uidNumber"]= $minUserId;
3450 $attrs["gidNumber"]= $minGroupId;
3451 $ldap->cd("ou=idmap,".$config->current['BASE']);
3452 $ldap->add($attrs);
3453 if ($ldap->error != "Success") {
3454 msg_dialog::display(_("Error"), _("Cannot create sambaUnixIdPool entry!"), ERROR_DIALOG);
3455 return null;
3456 }
3457 $tries++;
3458 continue;
3459 }
3460 /* Bail out if it's not unique */
3461 if ($ldap->count() != 1) {
3462 msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("sambaUnixIdPool is not unique!"), ERROR_DIALOG);
3463 return null;
3464 }
3466 /* Store old attrib and generate new */
3467 $attrs= $ldap->fetch();
3468 $dn= $ldap->getDN();
3469 $oldAttr= $attrs[$attrib][0];
3470 $newAttr= $oldAttr + 1;
3472 /* Sanity check */
3473 if ($newAttr >= $max) {
3474 msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("no ID available!"), ERROR_DIALOG);
3475 return null;
3476 }
3477 if ($newAttr < $min) {
3478 msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("no ID available!"), ERROR_DIALOG);
3479 return null;
3480 }
3482 #FIXME: PHP is not able to do a modification of "del: .../add: ...", so this
3483 # is completely unsafe in the moment.
3484 #/* Remove old attr, add new attr */
3485 #$attrs= array($attrib => $oldAttr);
3486 #$ldap->rm($attrs, $dn);
3487 #if ($ldap->error != "Success") {
3488 # continue;
3489 #}
3490 $ldap->cd($dn);
3491 $ldap->modify(array($attrib => $newAttr));
3492 if ($ldap->error != "Success") {
3493 msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." ".$ldap->get_error(), ERROR_DIALOG);
3494 return null;
3495 } else {
3496 return $oldAttr;
3497 }
3498 }
3500 /* Bail out if we had problems getting the next id */
3501 if (!$tries) {
3502 msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("maximum number of tries exceeded!"), ERROR_DIALOG);
3503 }
3505 return $id;
3506 }
3509 function get_next_id_traditional($attrib, $dn)
3510 {
3511 global $config;
3513 $ids= array();
3514 $ldap= $config->get_ldap_link();
3516 $ldap->cd ($config->current['BASE']);
3517 if (preg_match('/gidNumber/i', $attrib)){
3518 $oc= "posixGroup";
3519 } else {
3520 $oc= "posixAccount";
3521 }
3522 $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
3524 /* Get list of ids */
3525 while ($attrs= $ldap->fetch()){
3526 $ids[]= (int)$attrs["$attrib"][0];
3527 }
3529 /* Add the nobody id */
3530 $ids[]= 65534;
3532 /* get the ranges */
3533 $tmp = array('0'=> 1000);
3534 if (preg_match('/posixAccount/', $oc) && $config->get_cfg_value("core","uidNumberBase") != ""){
3535 $tmp= explode('-',$config->get_cfg_value("core","uidNumberBase"));
3536 } elseif($config->get_cfg_value("core","gidNumberBase") != ""){
3537 $tmp= explode('-',$config->get_cfg_value("core","gidNumberBase"));
3538 }
3540 /* Set hwm to max if not set - for backward compatibility */
3541 $lwm= $tmp[0];
3542 if (isset($tmp[1])){
3543 $hwm= $tmp[1];
3544 } else {
3545 $hwm= pow(2,32);
3546 }
3547 /* Find out next free id near to UID_BASE */
3548 if ($config->get_cfg_value("core","baseIdHook") == ""){
3549 $base= $lwm;
3550 } else {
3551 /* Call base hook */
3552 $base= get_base_from_hook($dn, $attrib);
3553 }
3554 for ($id= $base; $id++; $id < pow(2,32)){
3555 if (!in_array($id, $ids)){
3556 return ($id);
3557 }
3558 }
3560 /* Should not happen */
3561 if ($id == $hwm){
3562 msg_dialog::display(_("Error"), _("Cannot allocate free ID!"), ERROR_DIALOG);
3563 exit;
3564 }
3565 }
3568 /* Mark the occurance of a string with a span */
3569 function mark($needle, $haystack, $ignorecase= true)
3570 {
3571 $result= "";
3573 while (preg_match('/^(.*)('.preg_quote($needle).')(.*)$/i', $haystack, $matches)) {
3574 $result.= $matches[1]."<span class='mark'>".$matches[2]."</span>";
3575 $haystack= $matches[3];
3576 }
3578 return $result.$haystack;
3579 }
3582 /* Return an image description using the path */
3583 function image($path, $action= "", $title= "", $align= "middle")
3584 {
3585 global $config;
3586 global $BASE_DIR;
3587 $label= null;
3589 // Bail out, if there's no style file
3590 if(!session::global_is_set("img-styles")){
3592 // Get theme
3593 if (isset ($config)){
3594 $theme= $config->get_cfg_value("core","theme");
3595 } else {
3597 // Fall back to default theme
3598 $theme= "default";
3599 }
3601 if (!file_exists("$BASE_DIR/ihtml/themes/$theme/img.styles")){
3602 die ("No img.style for this theme found!");
3603 }
3605 session::global_set('img-styles', unserialize(file_get_contents("$BASE_DIR/ihtml/themes/$theme/img.styles")));
3606 }
3607 $styles= session::global_get('img-styles');
3609 /* Extract labels from path */
3610 if (preg_match("/\.png\[(.*)\]$/", $path, $matches)) {
3611 $label= $matches[1];
3612 }
3614 $lbl= "";
3615 if ($label) {
3616 if (isset($styles["images/label-".$label.".png"])) {
3617 $lbl= "<div style='".$styles["images/label-".$label.".png"]."'></div>";
3618 } else {
3619 die("Invalid label specified: $label\n");
3620 }
3622 $path= preg_replace("/\[.*\]$/", "", $path);
3623 }
3625 // Non middle layout?
3626 if ($align == "middle") {
3627 $align= "";
3628 } else {
3629 $align= ";vertical-align:$align";
3630 }
3632 // Clickable image or not?
3633 if ($title != "") {
3634 $title= "title='$title'";
3635 }
3636 if ($action == "") {
3637 return "<div class='img' $title style='".$styles[$path]."$align'>$lbl</div>";
3638 } else {
3639 return "<input type='submit' class='img' id='$action' value='' name='$action' $title style='".$styles[$path]."$align'>";
3640 }
3641 }
3643 /*! \brief Encodes a complex string to be useable in HTML posts.
3644 */
3645 function postEncode($str)
3646 {
3647 return(preg_replace("/=/","_", base64_encode($str)));
3648 }
3650 /*! \brief Decodes a string encoded by postEncode
3651 */
3652 function postDecode($str)
3653 {
3654 return(base64_decode(preg_replace("/_/","=", $str)));
3655 }
3658 /*! \brief Generate styled output
3659 */
3660 function bold($str)
3661 {
3662 return "<span class='highlight'>$str</span>";
3663 }
3667 /*! \brief Detect the special character handling for the currently used ldap database.
3668 * For example some convert , to \2C or " to \22.
3669 *
3670 * @param Config The GOsa configuration object.
3671 * @return Array An array containing a character mapping the use.
3672 */
3673 function detectLdapSpecialCharHandling()
3674 {
3675 // The list of chars to test for
3676 global $config;
3677 if(!$config) return(NULL);
3679 // In the DN we've to use escaped characters, but the object name (o)
3680 // has the be un-escaped.
3681 $name = 'GOsaLdapEncoding_,_"_(_)_+';
3682 $dnName = 'GOsaLdapEncoding_\,_\"_(_)_\+';
3684 // Prapare name to be useable in filters
3685 $fixed= normalizeLdap(str_replace('\\\\', '\\\\\\', $name));
3686 $filterName = str_replace('\\,', '\\\\,', $fixed);
3688 // Create the target dn
3689 $oDN = "o={$dnName},".$config->current['BASE'];
3691 // Get ldap connection and check if we've already created the character
3692 // detection object.
3693 $ldapCID = ldap_connect($config->current['SERVER']);
3694 ldap_set_option($ldapCID, LDAP_OPT_PROTOCOL_VERSION, 3);
3695 ldap_bind($ldapCID, $config->current['ADMINDN'],$config->current['ADMINPASSWORD']);
3696 $res = ldap_list($ldapCID, $config->current['BASE'],
3697 "(&(o=".$filterName.")(objectClass=organization))",
3698 array('dn'));
3700 // If we haven't created the character-detection object, then create it now.
3701 $cnt = ldap_count_entries($ldapCID, $res);
3702 if(!$cnt){
3703 $obj = array();
3704 $obj['objectClass'] = array('top','organization');
3705 $obj['o'] = $name;
3706 $obj['description'] = 'GOsa character encoding test-object.';
3707 if(!@ldap_add($ldapCID, $oDN, $obj)){
3708 trigger_error("GOsa couldn't detect the special character handling used by your ldap!");
3709 return(NULL);
3710 }
3711 }
3713 // Read the character-handling detection entry from the ldap.
3714 $res = ldap_list($ldapCID, $config->current['BASE'],
3715 "(&(o=".$filterName.")(objectClass=organization))",
3716 array('dn','o'));
3717 $cnt = ldap_count_entries($ldapCID, $res);
3718 if($cnt != 1 || !$res){
3719 trigger_error("GOsa couldn't detect the special character handling used by your ldap!");
3720 return(NULL);
3721 }else{
3723 // Get the character handling entry from the ldap and check how the
3724 // values were written. Compare them with what
3725 // we've initially intended to write and create a mapping out
3726 // of the results.
3727 $re = ldap_first_entry($ldapCID, $res);
3728 $attrs = ldap_get_attributes($ldapCID, $re);
3730 // Extract the interessting characters out of the dn and the
3731 // initially used $name for the entry.
3732 $mapDNstr = preg_replace("/^o=GOsaLdapEncoding_([^,]*),.*$/","\\1", trim(ldap_get_dn($ldapCID, $re)));
3733 $mapDN = preg_split("/_/", $mapDNstr,0, PREG_SPLIT_NO_EMPTY);
3735 $mapNameStr = preg_replace("/^GOsaLdapEncoding_/","",$dnName);
3736 $mapName = preg_split("/_/", $mapNameStr,0, PREG_SPLIT_NO_EMPTY);
3738 // Create a mapping out of the results.
3739 $map = array();
3740 foreach($mapName as $key => $entry){
3741 $map[$entry] = $mapDN[$key];
3742 }
3743 return($map);
3744 }
3745 return(NULL);
3746 }
3749 /*! \brief Replaces placeholder in a given string.
3750 * For example:
3751 * '%uid@gonicus.de' Replaces '%uid' with 'uid'.
3752 * '{%uid[0]@gonicus.de}' Replaces '%uid[0]' with the first char of 'uid'.
3753 * '%uid[2-4]@gonicus.de' Replaces '%uid[2-4]' with three chars from 'uid' starting from the second.
3754 *
3755 * The surrounding {} in example 2 are optional.
3756 *
3757 * @param String The string to perform the action on.
3758 * @param Array An array of replacements.
3759 * @return The resulting string.
3760 */
3761 function fillReplacements($str, $attrs, $shellArg = FALSE, $default = "")
3762 {
3763 // Search for '{%...[n-m]}
3764 // Get all matching parts of the given string and sort them by
3765 // length, to avoid replacing strings like '%uidNumber' with 'uid'
3766 // instead of 'uidNumber'; The longest tring at first.
3767 preg_match_all('/(\{?%([a-z0-9]+)(\[(([0-9]+)(\-([0-9]+))?)\])?\}?)/i', $str ,$matches, PREG_SET_ORDER);
3768 $hits = array();
3769 foreach($matches as $match){
3770 $hits[strlen($match[2]).$match[0]] = $match;
3771 }
3772 krsort($hits);
3774 // Replace the placeholder in the given string now.
3775 foreach($hits as $match){
3777 // Avoid errors about undefined index.
3778 $name = $match[2];
3779 if(!isset($attrs[$name])) $attrs[$name] = $default;
3781 // Calculate the replacement
3782 $start = (isset($match[5])) ? $match[5] : 0;
3783 $end = strlen($attrs[$name]);
3784 if(isset($match[5]) && !isset($match[7])){
3785 $end = 1;
3786 }elseif(isset($match[5]) && isset($match[7])){
3787 $end = ($match[7]-$start+1);
3788 }
3789 $value = substr($attrs[$name], $start, $end);
3791 // Use values which are valid for shell execution?
3792 if($shellArg) $value = escapeshellarg($value);
3794 // Replace the placeholder within the string.
3795 $str = preg_replace("/".preg_quote($match[0],'/')."/", $value, $str);
3796 }
3797 return($str);
3798 }
3801 /*! \brief Generate a list of uid proposals based on a rule
3802 *
3803 * Unroll given rule string by filling in attributes and replacing
3804 * all keywords.
3805 *
3806 * \param string 'rule' The rule string from gosa.conf.
3807 * \param array 'attributes' A dictionary of attribute/value mappings
3808 * \return array List of valid not used uids
3809 */
3810 function gen_uids($rule, $attributes)
3811 {
3812 global $config;
3813 $ldap = $config->get_ldap_link();
3814 $ldap->cd($config->current['BASE']);
3817 // Strip out non ascii chars
3818 foreach($attributes as $name => $value){
3819 $value = iconv('UTF-8', 'US-ASCII//TRANSLIT', $value);
3820 $value = preg_replace('/[^(\x20-\x7F)]*/','',$value);
3821 $attributes[$name] = strtolower($value);
3822 }
3824 // Search for '{%...[n-m]}
3825 // Get all matching parts of the given string and sort them by
3826 // length, to avoid replacing strings like '%uidNumber' with 'uid'
3827 // instead of 'uidNumber'; The longest tring at first.
3828 preg_match_all('/(\{?%([a-z0-9]+)(\[(([0-9]+)(\-([0-9]+))?)\])?\}?)/i', $rule ,$matches, PREG_SET_ORDER);
3829 $replacements = array();
3830 foreach($matches as $match){
3832 // No start position given, then add the complete value
3833 if(!isset($match[5])){
3834 $replacements[$match[0]][] = $attributes[$match[2]];
3836 // Start given but no end, so just add a simple character
3837 }elseif(!isset($match[7])){
3838 if(isset($attributes[$match[2]][$match[5]])){
3839 $replacements[$match[0]][] = $attributes[$match[2]][$match[5]];
3840 }
3842 // Add all values in range
3843 }else{
3844 $str = "";
3845 for($i=$match[5]; $i<= $match[7]; $i++){
3846 if(isset($attributes[$match[2]][$i])){
3847 $str .= $attributes[$match[2]][$i];
3848 $replacements[$match[0]][] = $str;
3849 }
3850 }
3851 }
3852 }
3854 // Create proposal array
3855 $rules = array($rule);
3856 foreach($replacements as $tag => $values){
3857 $rules = gen_uid_proposals($rules, $tag,$values);
3858 }
3861 // Search for id tags {id:3} / {id#3}
3862 preg_match_all('/\{id(#|:)([0-9])+\}/i', $rule ,$matches, PREG_SET_ORDER);
3863 $idReplacements = array();
3864 foreach($matches as $match){
3865 if(count($match) != 3) continue;
3867 // Generate random number
3868 if($match[1] == '#'){
3869 foreach($rules as $id => $ruleStr){
3870 $genID = rand(pow(10,$match[2] -1),pow(10, ($match[2])) - 1);
3871 $rules[$id] = preg_replace("/".preg_quote($match[0],'/')."/", $genID,$ruleStr);
3872 }
3873 }
3875 // Search for next free id
3876 if($match[1] == ':'){
3878 // Walk through rules and replace all occurences of {id:..}
3879 foreach($rules as $id => $ruleStr){
3880 $genID = 0;
3881 $start = TRUE;
3882 while($start || $ldap->count()){
3883 $start = FALSE;
3884 $number= sprintf("%0".$match[2]."d", $genID);
3885 $testRule = preg_replace("/".preg_quote($match[0],'/')."/",$number,$ruleStr);
3886 $ldap->search('uid='.normalizeLdap($testRule));
3887 $genID ++;
3888 }
3889 $rules[$id] = preg_replace("/".preg_quote($match[0],'/')."/",$number,$ruleStr);
3890 }
3891 }
3892 }
3894 // Create result set by checking which uid is already used and which is free.
3895 $ret = array();
3896 foreach($rules as $rule){
3897 $ldap->search('uid='.normalizeLdap($rule));
3898 if(!$ldap->count()){
3899 $ret[] = $rule;
3900 }
3901 }
3903 return($ret);
3904 }
3907 function gen_uid_proposals(&$rules, $tag, $values)
3908 {
3909 $newRules = array();
3910 foreach($rules as $rule){
3911 foreach($values as $value){
3912 $newRules[] = preg_replace("/".preg_quote($tag,'/')."/", $value, $rule);
3913 }
3914 }
3915 return($newRules);
3916 }
3918 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3919 ?>