Code

Fixed id allocation
[gosa.git] / gosa-core / include / functions.inc
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 /* Define globals for revision comparing */
27 $svn_path = '$HeadURL$';
28 $svn_revision = '$Revision$';
30 /* Configuration file location */
31 if(!isset($_SERVER['CONFIG_DIR'])){
32   define ("CONFIG_DIR", "/etc/gosa");
33 }else{
34   define ("CONFIG_DIR",$_SERVER['CONFIG_DIR']);
35 }
37 /* Allow setting the config file in the apache configuration
38     e.g.  SetEnv CONFIG_FILE gosa.conf.2.6
39  */
40 if(!isset($_SERVER['CONFIG_FILE'])){
41   define ("CONFIG_FILE", "gosa.conf");
42 }else{
43   define ("CONFIG_FILE",$_SERVER['CONFIG_FILE']);
44 }
46 /* Define common locatitions */
47 define ("CONFIG_TEMPLATE_DIR", "../contrib");
48 define ("TEMP_DIR","/var/cache/gosa/tmp");
50 /* Define get_list flags */
51 define("GL_NONE",         0);
52 define("GL_SUBSEARCH",    1);
53 define("GL_SIZELIMIT",    2);
54 define("GL_CONVERT",      4);
55 define("GL_NO_ACL_CHECK", 8);
57 /* Heimdal stuff */
58 define('UNIVERSAL',0x00);
59 define('INTEGER',0x02);
60 define('OCTET_STRING',0x04);
61 define('OBJECT_IDENTIFIER ',0x06);
62 define('SEQUENCE',0x10);
63 define('SEQUENCE_OF',0x10);
64 define('SET',0x11);
65 define('SET_OF',0x11);
66 define('DEBUG',false);
67 define('HDB_KU_MKEY',0x484442);
68 define('TWO_BIT_SHIFTS',0x7efc);
69 define('DES_CBC_CRC',1);
70 define('DES_CBC_MD4',2);
71 define('DES_CBC_MD5',3);
72 define('DES3_CBC_MD5',5);
73 define('DES3_CBC_SHA1',16);
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     }
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)
154   global $class_mapping;
155   return(isset($class_mapping[$name]));
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)
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         }
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);
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="")
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   }
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()
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   }
262  
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'));
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)
288   $ui= session::global_get('ui');
289   if ($ui->dn == $dn){
290     $ui->dn= $newdn;
291     session::global_set('ui',$ui);
292   }
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= "")
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   }
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)
374   return (array_merge(array_diff($haystack, $needles)));
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)
383   // strcasecmp will work, because we only compare ASCII values here
384   return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
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)
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   }
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)
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");
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='')
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;
466 /* \brief Process htaccess authentication */
467 function process_htaccess ($username, $kerberos= FALSE)
469   global $config;
471   /* Search for $username and optional @REALM in all configured LDAP trees */
472   foreach($config->data["LOCATIONS"] as $name => $data){
473   
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" => "");
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)
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);
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)
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);
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)
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);
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)
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   }
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)
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   }
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)
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   }
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)
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);
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)
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);
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)
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{
1059         
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   }
1069   
1070    /* If there is no sub_department specified, fall back to old method, get_list().
1071    */
1072   if(!count($sub_bases) && !count($departments)){
1073     
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);
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)
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   }
1239  
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);
1247 /*! \brief Show sizelimit configuration dialog if exceeded */
1248 function check_sizelimit()
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 ("");
1267 /*! \brief Print a sizelimit warning */
1268 function print_sizelimit_warning()
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 ("");
1283 /*! \brief Handle sizelimit dialog related posts */
1284 function eval_sizelimit()
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   }
1315 function getMenuCache()
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   }
1338 /*! \brief Return the current userinfo object */
1339 function &get_userinfo()
1341   global $ui;
1343   return $ui;
1347 /*! \brief Get global smarty object */
1348 function &get_smarty()
1350   global $smarty;
1352   return $smarty;
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)
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, "/"));
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)
1412   return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
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)
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   }
1476  
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     }
1489   
1490   } else {
1491     return "";
1492   }
1496 /*! \brief Get the OU for users 
1497  *
1498  * Frontend for get_ou() with userRDN
1499  * */
1500 function get_people_ou()
1502   return (get_ou("userRDN"));
1506 /*! \brief Get the OU for groups
1507  *
1508  * Frontend for get_ou() with groupRDN
1509  */
1510 function get_groups_ou()
1512   return (get_ou("groupRDN"));
1516 /*! \brief Get the OU for winstations
1517  *
1518  * Frontend for get_ou() with sambaMachineAccountRDN
1519  */
1520 function get_winstations_ou()
1522   return (get_ou("sambaMachineAccountRDN"));
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)
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);
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()
1561   global $config;
1563   if (isset($config)){
1564     return ($config->get_cfg_value("strictNamingRules") == "true");
1565   }
1566   return (TRUE);
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()
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   }
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)
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')));
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)
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   }
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()
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;
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)
1738   global $REWRITE;
1740   foreach ($REWRITE as $key => $val){
1741     $s= str_replace("$key", "$val", $s);
1742   }
1744   return ($s);
1748 /*! \brief Return the base of a given DN
1749  *
1750  * \param string 'dn' a DN
1751  * */
1752 function dn2base($dn)
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);
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)
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);
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= "")
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=\"*\">&nbsp;$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.= "&nbsp;";
1813     $display.= "</div>\n";
1814   }
1815   return ($display);
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)
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'])."&amp;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'])."&amp;start=".
1896         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1897     } else {
1898       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1899         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1900     }
1901   }
1903   /* Draw increment */
1904   if($start < ($dcnt-$range)) {
1905     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;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;'>&nbsp;"._("Entries per page")."&nbsp;<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);
1933 /*! \brief Generate HTML for the 'Apply filter' button */
1934 function apply_filter()
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);
1946 /*! \brief Generate HTML for the 'Back' button */
1947 function back_to_main()
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);
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)
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);
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)
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);
2027 /*! \brief Recursion helper for gen_id() */
2028 function recurse($rule, $variables)
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);
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)
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));
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)
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));
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   }
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)
2252         return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
2256 /*! \brief Generate a clickable alphabet */
2257 function generate_alphabet($count= 10)
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'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</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>&nbsp;</td>";
2282   }
2284   return ($alphabet);
2288 /*! \brief Removes malicious characters from a (POST) string. */
2289 function validate($string)
2291   return (strip_tags(str_replace('\0', '', $string)));
2295 /*! \brief Evaluate the current GOsa version from the build in revision string */
2296 function get_gosa_version()
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));
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);
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)
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);
2397 /*! \brief Clean the smarty compile dir */
2398 function clean_smarty_compile_dir($directory)
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           }
2425         }
2426         // We should now create a fresh revision file
2427         clean_smarty_compile_dir($directory);
2428       } else {
2429         // Revision matches, nothing to do
2430       }
2431     }
2432   } else {
2433     // Smarty compile dir is not accessible
2434     // (Smarty will warn about this)
2435   }
2439 function create_revision($revision_file, $revision)
2441   $result= false;
2443   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2444     if($fh= fopen($revision_file, "w")) {
2445       if(fwrite($fh, $revision)) {
2446         $result= true;
2447       }
2448     }
2449     fclose($fh);
2450   } else {
2451     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2452   }
2454   return $result;
2458 function compare_revision($revision_file, $revision)
2460   // false means revision differs
2461   $result= false;
2463   if(file_exists($revision_file) && is_readable($revision_file)) {
2464     // Open file
2465     if($fh= fopen($revision_file, "r")) {
2466       // Compare File contents with current revision
2467       if($revision == fread($fh, filesize($revision_file))) {
2468         $result= true;
2469       }
2470     } else {
2471       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2472     }
2473     // Close file
2474     fclose($fh);
2475   }
2477   return $result;
2481 /*! \brief Return HTML for a progressbar
2482  *
2483  * \code
2484  * $smarty->assign("installprogress", progressbar($current_progress_in_percent),100,15,true); 
2485  * \endcode
2486  *
2487  * \param int 'percentage' Value to display
2488  * \param int 'width' width of the resulting output
2489  * \param int 'height' height of the resulting output
2490  * \param boolean 'showvalue' weither to show the percentage in the progressbar or not
2491  * */
2492 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2494   return("<img src='progress.php?x=$width&amp;y=$height&amp;p=$percentage'>");
2498 /*! \brief Lookup a key in an array case-insensitive
2499  *
2500  * Given an associative array this can lookup the value of
2501  * a certain key, regardless of the case.
2502  *
2503  * \code
2504  * $items = array ('FOO' => 'blub', 'bar' => 'blub');
2505  * array_key_ics('foo', $items); # Returns 'blub'
2506  * array_key_ics('BAR', $items); # Returns 'blub'
2507  * \endcode
2508  *
2509  * \param string 'key' needle
2510  * \param array 'items' haystack
2511  */
2512 function array_key_ics($ikey, $items)
2514   $tmp= array_change_key_case($items, CASE_LOWER);
2515   $ikey= strtolower($ikey);
2516   if (isset($tmp[$ikey])){
2517     return($tmp[$ikey]);
2518   }
2520   return ('');
2524 /*! \brief Determine if two arrays are different
2525  *
2526  * \param array 'src'
2527  * \param array 'dst'
2528  * \return boolean TRUE or FALSE
2529  * */
2530 function array_differs($src, $dst)
2532   /* If the count is differing, the arrays differ */
2533   if (count ($src) != count ($dst)){
2534     return (TRUE);
2535   }
2537   return (count(array_diff($src, $dst)) != 0);
2541 function saveFilter($a_filter, $values)
2543   if (isset($_POST['regexit'])){
2544     $a_filter["regex"]= $_POST['regexit'];
2546     foreach($values as $type){
2547       if (isset($_POST[$type])) {
2548         $a_filter[$type]= "checked";
2549       } else {
2550         $a_filter[$type]= "";
2551       }
2552     }
2553   }
2555   /* React on alphabet links if needed */
2556   if (isset($_GET['search'])){
2557     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2558     if ($s == "**"){
2559       $s= "*";
2560     }
2561     $a_filter['regex']= $s;
2562   }
2564   return ($a_filter);
2568 /*! \brief Escape all LDAP filter relevant characters */
2569 function normalizeLdap($input)
2571   return (addcslashes($input, '()|'));
2575 /*! \brief Return the gosa base directory */
2576 function get_base_dir()
2578   global $BASE_DIR;
2580   return $BASE_DIR;
2584 /*! \brief Test weither we are allowed to read the object */
2585 function obj_is_readable($dn, $object, $attribute)
2587   global $ui;
2589   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2593 /*! \brief Test weither we are allowed to change the object */
2594 function obj_is_writable($dn, $object, $attribute)
2596   global $ui;
2598   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2602 /*! \brief Explode a DN into its parts
2603  *
2604  * Similar to explode (http://php.net/explode), but a bit more specific
2605  * for the needs when splitting, exploding LDAP DNs.
2606  *
2607  * \param string 'dn' the DN to split
2608  * \param config-object a config object. only neeeded if DN shall be verified in the LDAP
2609  * \param boolean verify_in_ldap check weither DN is valid
2610  *
2611  */
2612 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2614   /* Initialize variables */
2615   $ret  = array("count" => 0);  // Set count to 0
2616   $next = true;                 // if false, then skip next loops and return
2617   $cnt  = 0;                    // Current number of loops
2618   $max  = 100;                  // Just for security, prevent looops
2619   $ldap = NULL;                 // To check if created result a valid
2620   $keep = "";                   // save last failed parse string
2622   /* Check each parsed dn in ldap ? */
2623   if($config!==NULL && $verify_in_ldap){
2624     $ldap = $config->get_ldap_link();
2625   }
2627   /* Lets start */
2628   $called = false;
2629   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2631     $cnt ++;
2632     if(!preg_match("/,/",$dn)){
2633       $next = false;
2634     }
2635     $object = preg_replace("/[,].*$/","",$dn);
2636     $dn     = preg_replace("/^[^,]+,/","",$dn);
2638     $called = true;
2640     /* Check if current dn is valid */
2641     if($ldap!==NULL){
2642       $ldap->cd($dn);
2643       $ldap->cat($dn,array("dn"));
2644       if($ldap->count()){
2645         $ret[]  = $keep.$object;
2646         $keep   = "";
2647       }else{
2648         $keep  .= $object.",";
2649       }
2650     }else{
2651       $ret[]  = $keep.$object;
2652       $keep   = "";
2653     }
2654   }
2656   /* No dn was posted */
2657   if($cnt == 0 && !empty($dn)){
2658     $ret[] = $dn;
2659   }
2661   /* Append the rest */
2662   $test = $keep.$dn;
2663   if($called && !empty($test)){
2664     $ret[] = $keep.$dn;
2665   }
2666   $ret['count'] = count($ret) - 1;
2668   return($ret);
2672 function get_base_from_hook($dn, $attrib)
2674   global $config;
2676   if ($config->get_cfg_value("baseIdHook") != ""){
2677     
2678     /* Call hook script - if present */
2679     $command= $config->get_cfg_value("baseIdHook");
2681     if ($command != ""){
2682       $command.= " ".escapeshellarg(LDAP::fix($dn))." ".escapeshellarg($attrib);
2683       if (check_command($command)){
2684         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2685         exec($command, $output);
2686         if (preg_match("/^[0-9]+$/", $output[0])){
2687           return ($output[0]);
2688         } else {
2689           msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2690           return ($config->get_cfg_value("uidNumberBase"));
2691         }
2692       } else {
2693         msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2694         return ($config->get_cfg_value("uidNumberBase"));
2695       }
2697     } else {
2699       msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2700       return ($config->get_cfg_value("uidNumberBase"));
2702     }
2703   }
2707 /*! \brief Check if schema version matches the requirements */
2708 function check_schema_version($class, $version)
2710   return preg_match("/\(v$version\)/", $class['DESC']);
2714 /*! \brief Check if LDAP schema matches the requirements */
2715 function check_schema($cfg,$rfc2307bis = FALSE)
2717   $messages= array();
2719   /* Get objectclasses */
2720   $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2721   $objectclasses = $ldap->get_objectclasses();
2722   if(count($objectclasses) == 0){
2723     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2724   }
2726   /* This is the default block used for each entry.
2727    *  to avoid unset indexes.
2728    */
2729   $def_check = array("REQUIRED_VERSION" => "0",
2730       "SCHEMA_FILES"     => array(),
2731       "CLASSES_REQUIRED" => array(),
2732       "STATUS"           => FALSE,
2733       "IS_MUST_HAVE"     => FALSE,
2734       "MSG"              => "",
2735       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2737   /* The gosa base schema */
2738   $checks['gosaObject'] = $def_check;
2739   $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2740   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa-samba3.schema","gosa-samba2.schema");
2741   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2742   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2744   /* GOsa Account class */
2745   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.6";
2746   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa-samba3.schema","gosa-samba2.schema");
2747   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2748   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2749   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2751   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2752   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2753   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa-samba3.schema","gosa-samba2.schema");
2754   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2755   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2756   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2758   /* Some other checks */
2759   foreach(array(
2760         "gosaCacheEntry"        => array("version" => "2.6.1", "class" => "gosaAccount"),
2761         "gosaDepartment"        => array("version" => "2.6.1", "class" => "gosaAccount"),
2762         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2763         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2764         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2765         "gosaUserTemplate"      => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2766         "gosaMailAccount"       => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa-samba3.schema"),
2767         "gosaProxyAccount"      => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa-samba3.schema"),
2768         "gosaApplication"       => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2769         "gosaApplicationGroup"  => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2770         "GOhard"                => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2771         "gotoTerminal"          => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2772         "goServer"              => array("version" => "2.6.1", "class" => "server","file" => "goserver.schema"),
2773         "goTerminalServer"      => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2774         "goShareServer"         => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2775         "goNtpServer"           => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2776         "goSyslogServer"        => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2777         "goLdapServer"          => array("version" => "2.6.1", "class" => "goServer"),
2778         "goCupsServer"          => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2779         "goImapServer"          => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa-samba3.schema"),
2780         "goKrbServer"           => array("version" => "2.6.1", "class" => "goServer"),
2781         "goFaxServer"           => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2782         ) as $name => $values){
2784           $checks[$name] = $def_check;
2785           if(isset($values['version'])){
2786             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2787           }
2788           if(isset($values['file'])){
2789             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2790           }
2791           if (isset($values['class'])) {
2792             $checks[$name]["CLASSES_REQUIRED"] = is_array($values['class'])?$values['class']:array($values['class']);
2793           }
2794         }
2795   foreach($checks as $name => $value){
2796     foreach($value['CLASSES_REQUIRED'] as $class){
2798       if(!isset($objectclasses[$name])){
2799         if($value['IS_MUST_HAVE']){
2800           $checks[$name]['STATUS'] = FALSE;
2801           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2802         } else {
2803           $checks[$name]['STATUS'] = TRUE;
2804           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2805         }
2806       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2807         $checks[$name]['STATUS'] = FALSE;
2809         $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2810       }else{
2811         $checks[$name]['STATUS'] = TRUE;
2812         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2813       }
2814     }
2815   }
2817   $tmp = $objectclasses;
2819   /* The gosa base schema */
2820   $checks['posixGroup'] = $def_check;
2821   $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2822   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa-samba3.schema","gosa-samba2.schema");
2823   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2824   $checks['posixGroup']['STATUS']           = TRUE;
2825   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2826   $checks['posixGroup']['MSG']              = "";
2827   $checks['posixGroup']['INFO']             = "";
2829   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2830   if(isset($tmp['posixGroup'])){
2832     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2833       $checks['posixGroup']['STATUS']           = FALSE;
2834       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2835       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2836     }
2837     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2838       $checks['posixGroup']['STATUS']           = FALSE;
2839       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2840       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2841     }
2842   }
2844   return($checks);
2848 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2850   $tmp = array(
2851         "de_DE" => "German",
2852         "fr_FR" => "French",
2853         "it_IT" => "Italian",
2854         "es_ES" => "Spanish",
2855         "en_US" => "English",
2856         "nl_NL" => "Dutch",
2857         "pl_PL" => "Polish",
2858         #"sv_SE" => "Swedish",
2859         "zh_CN" => "Chinese",
2860         "vi_VN" => "Vietnamese",
2861         "ru_RU" => "Russian");
2862   
2863   $tmp2= array(
2864         "de_DE" => _("German"),
2865         "fr_FR" => _("French"),
2866         "it_IT" => _("Italian"),
2867         "es_ES" => _("Spanish"),
2868         "en_US" => _("English"),
2869         "nl_NL" => _("Dutch"),
2870         "pl_PL" => _("Polish"),
2871         #"sv_SE" => _("Swedish"),
2872         "zh_CN" => _("Chinese"),
2873         "vi_VN" => _("Vietnamese"),
2874         "ru_RU" => _("Russian"));
2876   $ret = array();
2877   if($languages_in_own_language){
2879     $old_lang = setlocale(LC_ALL, 0);
2881     /* If the locale wasn't correclty set before, there may be an incorrect
2882         locale returned. Something like this: 
2883           C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2884         Extract the locale name from this string and use it to restore old locale.
2885      */
2886     if(preg_match("/LC_CTYPE/",$old_lang)){
2887       $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2888     }
2889     
2890     foreach($tmp as $key => $name){
2891       $lang = $key.".UTF-8";
2892       setlocale(LC_ALL, $lang);
2893       if($strip_region_tag){
2894         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2895       }else{
2896         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2897       }
2898     }
2899     setlocale(LC_ALL, $old_lang);
2900   }else{
2901     foreach($tmp as $key => $name){
2902       if($strip_region_tag){
2903         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2904       }else{
2905         $ret[$key] = _($name);
2906       }
2907     }
2908   }
2909   return($ret);
2913 /*! \brief Returns contents of the given POST variable and check magic quotes settings
2914  *
2915  * Depending on the magic quotes settings this returns a stripclashed'ed version of
2916  * a certain POST variable.
2917  *
2918  * \param string 'name' the POST var to return ($_POST[$name])
2919  * \return string
2920  * */
2921 function get_post($name)
2923   if(!isset($_POST[$name])){
2924     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2925     return(FALSE);
2926   }
2928   if(get_magic_quotes_gpc()){
2929     return(stripcslashes(validate($_POST[$name])));
2930   }else{
2931     return(validate($_POST[$name]));
2932   }
2936 /*! \brief Return class name in correct case */
2937 function get_correct_class_name($cls)
2939   global $class_mapping;
2940   if(isset($class_mapping) && is_array($class_mapping)){
2941     foreach($class_mapping as $class => $file){
2942       if(preg_match("/^".$cls."$/i",$class)){
2943         return($class);
2944       }
2945     }
2946   }
2947   return(FALSE);
2951 /*! \brief Change the password of a given DN
2952  * 
2953  * Change the password of a given DN with the specified hash.
2954  *
2955  * \param string 'dn' the DN whose password shall be changed
2956  * \param string 'password' the password
2957  * \param int mode
2958  * \param string 'hash' which hash to use to encrypt it, default is empty
2959  * for cleartext storage.
2960  * \return boolean TRUE on success FALSE on error
2961  */
2962 function change_password ($dn, $password, $mode=0, $hash= "")
2964   global $config;
2965   $newpass= "";
2967   /* Convert to lower. Methods are lowercase */
2968   $hash= strtolower($hash);
2970   // Get all available encryption Methods
2972   // NON STATIC CALL :)
2973   $methods = new passwordMethod(session::get('config'),$dn);
2974   $available = $methods->get_available_methods();
2976   // read current password entry for $dn, to detect the encryption Method
2977   $ldap       = $config->get_ldap_link();
2978   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2979   $attrs      = $ldap->fetch ();
2981   /* Is ensure that clear passwords will stay clear */
2982   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2983     $hash = "clear";
2984   }
2986   // Detect the encryption Method
2987   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2989     /* Check for supported algorithm */
2990     mt_srand((double) microtime()*1000000);
2992     /* Extract used hash */
2993     if ($hash == ""){
2994       $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2995     } else {
2996       $test = new $available[$hash]($config,$dn);
2997       $test->set_hash($hash);
2998     }
3000   } else {
3001     // User MD5 by default
3002     $hash= "md5";
3003     $test = new  $available['md5']($config, $dn);
3004   }
3006   if($test instanceOf passwordMethod){
3008     $deactivated = $test->is_locked($config,$dn);
3010     /* Feed password backends with information */
3011     $test->dn= $dn;
3012     $test->attrs= $attrs;
3013     $newpass= $test->generate_hash($password);
3015     // Update shadow timestamp?
3016     if (isset($attrs["shadowLastChange"][0])){
3017       $shadow= (int)(date("U") / 86400);
3018     } else {
3019       $shadow= 0;
3020     }
3022     // Write back modified entry
3023     $ldap->cd($dn);
3024     $attrs= array();
3026     // Not for groups
3027     if ($mode == 0){
3029         // Create SMB Password
3030         if ($config->get_cfg_value('sambaHashHook', NULL)) { 
3031             $attrs= generate_smb_nt_hash($password);
3033             if ($shadow != 0){
3034                 $attrs['shadowLastChange']= $shadow;
3035             }
3036         }
3037     }
3039     $attrs['userPassword']= array();
3040     $attrs['userPassword']= $newpass;
3042     $ldap->modify($attrs);
3044     /* Read ! if user was deactivated */
3045     if($deactivated){
3046       $test->lock_account($config,$dn);
3047     }
3049     new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
3051     if (!$ldap->success()) {
3052       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
3053     } else {
3055       /* Run backend method for change/create */
3056       if(!$test->set_password($password)){
3057         return(FALSE);
3058       }
3060       /* Find postmodify entries for this class */
3061       $command= $config->search("password", "POSTMODIFY",array('menu'));
3063       if ($command != ""){
3064         /* Walk through attribute list */
3065         $command= preg_replace("/%userPassword/", escapeshellarg($password), $command);
3066         $command= preg_replace("/%dn/", escapeshellarg($dn), $command);
3068         if (check_command($command)){
3069           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
3070           exec($command);
3071         } else {
3072           $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
3073           msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
3074         }
3075       }
3076     }
3077     return(TRUE);
3078   }
3082 /*! \brief Generate samba hashes
3083  *
3084  * Given a certain password this constructs an array like
3085  * array['sambaLMPassword'] etc.
3086  *
3087  * \param string 'password'
3088  * \return array contains several keys for lmPassword, ntPassword, pwdLastSet, etc. depending
3089  * on the samba version
3090  */
3091 function generate_smb_nt_hash($password)
3093   global $config;
3095   # Try to use gosa-si?
3096   if ($config->get_cfg_value("gosaSupportURI") != ""){
3097         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
3098     if (isset($res['XML']['HASH'])){
3099         $hash= $res['XML']['HASH'];
3100     } else {
3101       $hash= "";
3102     }
3104     if ($hash == "") {
3105       msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
3106       return ("");
3107     }
3108   } else {
3109           $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
3110           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
3112           exec($tmp, $ar);
3113           flush();
3114           reset($ar);
3115           $hash= current($ar);
3117     if ($hash == "") {
3118       msg_dialog::display(_("Configuration error"), sprintf(_("Cannot generate samba hash: running '%s' failed, check the 'sambaHashHook'!"),$config->get_cfg_value('sambaHashHook')), ERROR_DIALOG);
3119       return ("");
3120     }
3121   }
3123   list($lm,$nt)= explode(":", trim($hash));
3125   $attrs['sambaLMPassword']= $lm;
3126   $attrs['sambaNTPassword']= $nt;
3127   $attrs['sambaPwdLastSet']= date('U');
3128   $attrs['sambaBadPasswordCount']= "0";
3129   $attrs['sambaBadPasswordTime']= "0";
3130   return($attrs);
3134 /*! \brief Get the Change Sequence Number of a certain DN
3135  *
3136  * To verify if a given object has been changed outside of Gosa
3137  * in the meanwhile, this function can be used to get the entryCSN
3138  * from the LDAP directory. It uses the attribute as configured
3139  * in modificationDetectionAttribute
3140  *
3141  * \param string 'dn'
3142  * \return either the result or "" in any other case
3143  */
3144 function getEntryCSN($dn)
3146   global $config;
3147   if(empty($dn) || !is_object($config)){
3148     return("");
3149   }
3151   /* Get attribute that we should use as serial number */
3152   $attr= $config->get_cfg_value("modificationDetectionAttribute");
3153   if($attr != ""){
3154     $ldap = $config->get_ldap_link();
3155     $ldap->cat($dn,array($attr));
3156     $csn = $ldap->fetch();
3157     if(isset($csn[$attr][0])){
3158       return($csn[$attr][0]);
3159     }
3160   }
3161   return("");
3165 /*! \brief Add (a) given objectClass(es) to an attrs entry
3166  * 
3167  * The function adds the specified objectClass(es) to the given
3168  * attrs entry.
3169  *
3170  * \param mixed 'classes' Either a single objectClass or several objectClasses
3171  * as an array
3172  * \param array 'attrs' The attrs array to be modified.
3173  *
3174  * */
3175 function add_objectClass($classes, &$attrs)
3177   if (is_array($classes)){
3178     $list= $classes;
3179   } else {
3180     $list= array($classes);
3181   }
3183   foreach ($list as $class){
3184     $attrs['objectClass'][]= $class;
3185   }
3189 /*! \brief Removes a given objectClass from the attrs entry
3190  *
3191  * Similar to add_objectClass, except that it removes the given
3192  * objectClasses. See it for the params.
3193  * */
3194 function remove_objectClass($classes, &$attrs)
3196   if (isset($attrs['objectClass'])){
3197     /* Array? */
3198     if (is_array($classes)){
3199       $list= $classes;
3200     } else {
3201       $list= array($classes);
3202     }
3204     $tmp= array();
3205     foreach ($attrs['objectClass'] as $oc) {
3206       foreach ($list as $class){
3207         if (strtolower($oc) != strtolower($class)){
3208           $tmp[]= $oc;
3209         }
3210       }
3211     }
3212     $attrs['objectClass']= $tmp;
3213   }
3217 /*! \brief  Initialize a file download with given content, name and data type. 
3218  *  \param  string data The content to send.
3219  *  \param  string name The name of the file.
3220  *  \param  string type The content identifier, default value is "application/octet-stream";
3221  */
3222 function send_binary_content($data,$name,$type = "application/octet-stream")
3224   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
3225   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
3226   header("Cache-Control: no-cache");
3227   header("Pragma: no-cache");
3228   header("Cache-Control: post-check=0, pre-check=0");
3229   header("Content-type: ".$type."");
3231   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
3233   /* Strip name if it is a complete path */
3234   if (preg_match ("/\//", $name)) {
3235         $name= basename($name);
3236   }
3237   
3238   /* force download dialog */
3239   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
3240     header('Content-Disposition: filename="'.$name.'"');
3241   } else {
3242     header('Content-Disposition: attachment; filename="'.$name.'"');
3243   }
3245   echo $data;
3246   exit();
3250 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
3252   if(is_string($str)){
3253     return(htmlentities($str,$type,$charset));
3254   }elseif(is_array($str)){
3255     foreach($str as $name => $value){
3256       $str[$name] = reverse_html_entities($value,$type,$charset);
3257     }
3258   }
3259   return($str);
3263 /*! \brief Encode special string characters so we can use the string in \
3264            HTML output, without breaking quotes.
3265     \param string The String we want to encode.
3266     \return string The encoded String
3267  */
3268 function xmlentities($str)
3269
3270   if(is_string($str)){
3272     static $asc2uni= array();
3273     if (!count($asc2uni)){
3274       for($i=128;$i<256;$i++){
3275     #    $asc2uni[chr($i)] = "&#x".dechex($i).";";
3276       }
3277     }
3279     $str = str_replace("&", "&amp;", $str);
3280     $str = str_replace("<", "&lt;", $str);
3281     $str = str_replace(">", "&gt;", $str);
3282     $str = str_replace("'", "&apos;", $str);
3283     $str = str_replace("\"", "&quot;", $str);
3284     $str = str_replace("\r", "", $str);
3285     $str = strtr($str,$asc2uni);
3286     return $str;
3287   }elseif(is_array($str)){
3288     foreach($str as $name => $value){
3289       $str[$name] = xmlentities($value);
3290     }
3291   }
3292   return($str);
3296 /*! \brief  Updates all accessTo attributes from a given value to a new one.
3297             For example if a host is renamed.
3298     \param  String  $from The source accessTo name.
3299     \param  String  $to   The destination accessTo name.
3300 */
3301 function update_accessTo($from,$to)
3303   global $config;
3304   $ldap = $config->get_ldap_link();
3305   $ldap->cd($config->current['BASE']);
3306   $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
3307   while($attrs = $ldap->fetch()){
3308     $new_attrs = array("accessTo" => array());
3309     $dn = $attrs['dn'];
3310     for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
3311       $new_attrs['objectClass'][] =  $attrs['objectClass'][$i];
3312     }
3313     for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
3314       if($attrs['accessTo'][$i] == $from){
3315         if(!empty($to)){
3316           $new_attrs['accessTo'][] =  $to;
3317         }
3318       }else{
3319         $new_attrs['accessTo'][] =  $attrs['accessTo'][$i]; 
3320       }
3321     }
3322     $ldap->cd($dn);
3323     $ldap->modify($new_attrs);
3324     if (!$ldap->success()){
3325       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
3326     }
3327     new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
3328   }
3332 /*! \brief Returns a random char */
3333 function get_random_char () {
3334      $randno = rand (0, 63);
3335      if ($randno < 12) {
3336          return (chr ($randno + 46)); // Digits, '/' and '.'
3337      } else if ($randno < 38) {
3338          return (chr ($randno + 53)); // Uppercase
3339      } else {
3340          return (chr ($randno + 59)); // Lowercase
3341      }
3345 function cred_encrypt($input, $password) {
3347   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3348   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3350   return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
3355 function cred_decrypt($input,$password) {
3356   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3357   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3359   return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
3363 function get_object_info()
3365   return(session::get('objectinfo'));
3369 function set_object_info($str = "")
3371   session::set('objectinfo',$str);
3375 function isIpInNet($ip, $net, $mask) {
3376    // Move to long ints
3377    $ip= ip2long($ip);
3378    $net= ip2long($net);
3379    $mask= ip2long($mask);
3381    // Mask given IP with mask. If it returns "net", we're in...
3382    $res= $ip & $mask;
3384    return ($res == $net);
3388 function get_next_id($attrib, $dn)
3390   global $config;
3392   switch ($config->get_cfg_value("idAllocationMethod", "traditional")){
3393     case "pool":
3394       return get_next_id_pool($attrib);
3395     case "traditional":
3396       return get_next_id_traditional($attrib, $dn);
3397   }
3399   msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("unknown idAllocation method!"), ERROR_DIALOG);
3400   return null;
3404 function get_next_id_pool($attrib) {
3405   global $config;
3407   /* Fill informational values */
3408   $min= $config->get_cfg_value("${attrib}PoolMin", 10000);
3409   $max= $config->get_cfg_value("${attrib}PoolMax", 40000);
3411   /* Sanity check */
3412   if ($min >= $max) {
3413     msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." ".sprintf(_("%sPoolMin >= %sPoolMax!"), $attrib), ERROR_DIALOG);
3414     return null;
3415   }
3417   /* ID to skip */
3418   $ldap= $config->get_ldap_link();
3419   $id= null;
3421   /* Try to allocate the ID several times before failing */
3422   $tries= 3;
3423   while ($tries--) {
3425     /* Look for ID map entry */
3426     $ldap->cd ($config->current['BASE']);
3427     $ldap->search ("(&(objectClass=sambaUnixIdPool)($attrib=*))", array("$attrib"));
3429     /* If it does not exist, create one with these defaults */
3430     if ($ldap->count() == 0) {
3431       /* Fill informational values */
3432       $minUserId= $config->get_cfg_value("uidPoolMin", 10000);
3433       $minGroupId= $config->get_cfg_value("gidPoolMin", 10000);
3435       /* Add as default */
3436       $attrs= array("objectClass" => array("organizationalUnit", "sambaUnixIdPool"));
3437       $attrs["ou"]= "idmap";
3438       $attrs["uidNumber"]= $minUserId;
3439       $attrs["gidNumber"]= $minGroupId;
3440       $ldap->cd("ou=idmap,".$config->current['BASE']);
3441       $ldap->add($attrs);
3442       if ($ldap->error != "Success") {
3443         msg_dialog::display(_("Error"), _("Cannot create sambaUnixIdPool entry!"), ERROR_DIALOG);
3444         return null;
3445       }
3446       $tries++;
3447       continue;
3448     }
3449     /* Bail out if it's not unique */
3450     if ($ldap->count() != 1) {
3451       msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("sambaUnixIdPool is not unique!"), ERROR_DIALOG);
3452       return null;
3453     }
3455     /* Store old attrib and generate new */
3456     $attrs= $ldap->fetch();
3457     $dn= $ldap->getDN();
3458     $oldAttr= $attrs[$attrib][0];
3459     $newAttr= $oldAttr + 1;
3461     /* Sanity check */
3462     if ($newAttr >= $max) {
3463       msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("no ID available!"), ERROR_DIALOG);
3464       return null;
3465     }
3466     if ($newAttr < $min) {
3467       msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("no ID available!"), ERROR_DIALOG);
3468       return null;
3469     }
3471     #FIXME: PHP is not able to do a modification of "del: .../add: ...", so this
3472     #       is completely unsafe in the moment.
3473     #/* Remove old attr, add new attr */
3474     #$attrs= array($attrib => $oldAttr);
3475     #$ldap->rm($attrs, $dn);
3476     #if ($ldap->error != "Success") {
3477     #  continue;
3478     #}
3479     $ldap->cd($dn);
3480     $ldap->modify(array($attrib => $newAttr));
3481     if ($ldap->error != "Success") {
3482       msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." ".$ldap->get_error(), ERROR_DIALOG);
3483       return null;
3484     } else {
3485       return $oldAttr;
3486     }
3487   }
3489   /* Bail out if we had problems getting the next id */
3490   if (!$tries) {
3491     msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("maximum tries exceeded!"), ERROR_DIALOG);
3492   }
3494   return $id;
3498 function get_next_id_traditional($attrib, $dn)
3500   global $config;
3502   $ids= array();
3503   $ldap= $config->get_ldap_link();
3505   $ldap->cd ($config->current['BASE']);
3506   if (preg_match('/gidNumber/i', $attrib)){
3507     $oc= "posixGroup";
3508   } else {
3509     $oc= "posixAccount";
3510   }
3511   $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
3513   /* Get list of ids */
3514   while ($attrs= $ldap->fetch()){
3515     $ids[]= (int)$attrs["$attrib"][0];
3516   }
3518   /* Add the nobody id */
3519   $ids[]= 65534;
3521   /* get the ranges */
3522   $tmp = array('0'=> 1000);
3523   if (preg_match('/posixAccount/', $oc) && $config->get_cfg_value("uidNumberBase") != ""){
3524     $tmp= explode('-',$config->get_cfg_value("uidNumberBase"));
3525   } elseif($config->get_cfg_value("gidNumberBase") != ""){
3526     $tmp= explode('-',$config->get_cfg_value("gidNumberBase"));
3527   }
3529   /* Set hwm to max if not set - for backward compatibility */
3530   $lwm= $tmp[0];
3531   if (isset($tmp[1])){
3532     $hwm= $tmp[1];
3533   } else {
3534     $hwm= pow(2,32);
3535   }
3536   /* Find out next free id near to UID_BASE */
3537   if ($config->get_cfg_value("baseIdHook") == ""){
3538     $base= $lwm;
3539   } else {
3540     /* Call base hook */
3541     $base= get_base_from_hook($dn, $attrib);
3542   }
3543   for ($id= $base; $id++; $id < $hwm){
3544     if (!in_array($id, $ids)){
3545       return ($id);
3546     }
3547   }
3549   /* Should not happen */
3550   if ($id == $hwm){
3551     msg_dialog::display(_("Error"), _("Cannot allocate a free ID!"), ERROR_DIALOG);
3552     exit;
3553   }
3557 /* Mark the occurance of a string with a span */
3558 function mark($needle, $haystack, $ignorecase= true)
3560   $result= "";
3562   while (preg_match('/^(.*)('.preg_quote($needle).')(.*)$/i', $haystack, $matches)) {
3563     $result.= $matches[1]."<span class='mark'>".$matches[2]."</span>";
3564     $haystack= $matches[3];
3565   }
3567   return $result.$haystack;
3570 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3571 ?>