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