Code

Do not write sambaHashes while there is now sambaHashHook defined.
[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 /* Configuration file location */
27 if(!isset($_SERVER['CONFIG_DIR'])){
28   define ("CONFIG_DIR", "/etc/gosa");
29 }else{
30   define ("CONFIG_DIR",$_SERVER['CONFIG_DIR']);
31 }
33 /* Allow setting the config file in the apache configuration
34     e.g.  SetEnv CONFIG_FILE gosa.conf.2.6
35  */
36 if(!isset($_SERVER['CONFIG_FILE'])){
37   define ("CONFIG_FILE", "gosa.conf");
38 }else{
39   define ("CONFIG_FILE",$_SERVER['CONFIG_FILE']);
40 }
42 /* Define common locatitions */
43 define ("CONFIG_TEMPLATE_DIR", "../contrib");
44 define ("TEMP_DIR","/var/cache/gosa/tmp");
46 /* Define get_list flags */
47 define("GL_NONE",         0);
48 define("GL_SUBSEARCH",    1);
49 define("GL_SIZELIMIT",    2);
50 define("GL_CONVERT",      4);
51 define("GL_NO_ACL_CHECK", 8);
53 /* Heimdal stuff */
54 define('UNIVERSAL',0x00);
55 define('INTEGER',0x02);
56 define('OCTET_STRING',0x04);
57 define('OBJECT_IDENTIFIER ',0x06);
58 define('SEQUENCE',0x10);
59 define('SEQUENCE_OF',0x10);
60 define('SET',0x11);
61 define('SET_OF',0x11);
62 define('DEBUG',false);
63 define('HDB_KU_MKEY',0x484442);
64 define('TWO_BIT_SHIFTS',0x7efc);
65 define('DES_CBC_CRC',1);
66 define('DES_CBC_MD4',2);
67 define('DES_CBC_MD5',3);
68 define('DES3_CBC_MD5',5);
69 define('DES3_CBC_SHA1',16);
71 /* Define globals for revision comparing */
72 $svn_path = '$HeadURL$';
73 $svn_revision = '$Revision$';
75 /* Include required files */
76 require_once("class_location.inc");
77 require_once ("functions_debug.inc");
78 require_once ("accept-to-gettext.inc");
80 /* Define constants for debugging */
81 define ("DEBUG_TRACE",   1); /*! Debug level for tracing of common actions (save, check, etc.) */
82 define ("DEBUG_LDAP",    2); /*! Debug level for LDAP queries */
83 define ("DEBUG_MYSQL",   4); /*! Debug level for mysql operations */
84 define ("DEBUG_SHELL",   8); /*! Debug level for shell commands */
85 define ("DEBUG_POST",   16); /*! Debug level for POST content */
86 define ("DEBUG_SESSION",32); /*! Debug level for SESSION content */
87 define ("DEBUG_CONFIG", 64); /*! Debug level for CONFIG information */
88 define ("DEBUG_ACL",    128); /*! Debug level for ACL infos */
89 define ("DEBUG_SI",     256); /*! Debug level for communication with gosa-si */
90 define ("DEBUG_MAIL",   512); /*! Debug level for all about mail (mailAccounts, imap, sieve etc.) */
91 define ("DEBUG_FAI",   1024); // FAI (incomplete)
94 // Define shadow states
95 define ("POSIX_ACCOUNT_EXPIRED", 1); 
96 define ("POSIX_WARN_ABOUT_EXPIRATION", 2); 
97 define ("POSIX_FORCE_PASSWORD_CHANGE", 4); 
98 define ("POSIX_DISALLOW_PASSWORD_CHANGE", 8); 
100 /* Rewrite german 'umlauts' and spanish 'accents'
101    to get better results */
102 $REWRITE= array( "ä" => "ae",
103     "ö" => "oe",
104     "ü" => "ue",
105     "Ä" => "Ae",
106     "Ö" => "Oe",
107     "Ü" => "Ue",
108     "ß" => "ss",
109     "á" => "a",
110     "é" => "e",
111     "í" => "i",
112     "ó" => "o",
113     "ú" => "u",
114     "Á" => "A",
115     "É" => "E",
116     "Í" => "I",
117     "Ó" => "O",
118     "Ú" => "U",
119     "ñ" => "ny",
120     "Ñ" => "Ny" );
123 /*! \brief Does autoloading for classes used in GOsa.
124  *
125  *  Takes the list generated by 'update-gosa' and loads the
126  *  file containing the requested class.
127  *
128  *  \param  string 'class_name' The currently requested class
129  */
130 function __gosa_autoload($class_name) {
131     global $class_mapping, $BASE_DIR;
133     if ($class_mapping === NULL){
134             echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
135             exit;
136     }
138     if (isset($class_mapping["$class_name"])){
139       require_once($BASE_DIR."/".$class_mapping["$class_name"]);
140     } else {
141       echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
142       exit;
143     }
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   /* Search for keys and fill the variables array with all 
2107      possible values for that key. */
2108   $part= "";
2109   $trigger= false;
2110   $stripped= "";
2111   $variables= array();
2113   for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
2115     if ($rule[$pos] == "{" ){
2116       $trigger= true;
2117       $part= "";
2118       continue;
2119     }
2121     if ($rule[$pos] == "}" ){
2122       $variables[$pos]= expand_id($part, $attributes);
2123       $stripped.= "{".$pos."}";
2124       $trigger= false;
2125       continue;
2126     }
2128     if ($trigger){
2129       $part.= $rule[$pos];
2130     } else {
2131       $stripped.= $rule[$pos];
2132     }
2133   }
2135   /* Recurse through all possible combinations */
2136   $proposed= recurse($stripped, $variables);
2138   /* Get list of used ID's */
2139   $ldap= $config->get_ldap_link();
2140   $ldap->cd($config->current['BASE']);
2142   /* Remove used uids and watch out for id tags */
2143   $ret= array();
2144   foreach($proposed as $uid){
2146     /* Check for id tag and modify uid if needed */
2147     if(preg_match('/\{id(:|!)\d+}/',$uid, $m)){
2148       $size= preg_replace('/^.*{id(:|!)(\d+)}.*$/', '\\2', $uid);
2150       $start= $m[1]==":"?0:-1;
2151       for ($i= $start, $p= pow(10,$size)-1; $i < $p; $i++){
2152         if ($i == -1) {
2153           $number= "";
2154         } else {
2155           $number= sprintf("%0".$size."d", $i+1);
2156         }
2157         $res= preg_replace('/{id(:|!)\d+}/', $number, $uid);
2159         $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
2160         if($ldap->count() == 0){
2161           $uid= $res;
2162           break;
2163         }
2164       }
2166       /* Remove link if nothing has been found */
2167       $uid= preg_replace('/{id(:|!)\d+}/', '', $uid);
2168     }
2170     if(preg_match('/\{id#\d+}/',$uid)){
2171       $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
2173       while (true){
2174         mt_srand((double) microtime()*1000000);
2175         $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
2176         $res= preg_replace('/{id#(\d+)}/', $number, $uid);
2177         $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
2178         if($ldap->count() == 0){
2179           $uid= $res;
2180           break;
2181         }
2182       }
2184       /* Remove link if nothing has been found */
2185       $uid= preg_replace('/{id#\d+}/', '', $uid);
2186     }
2188     /* Don't assign used ones */
2189     $ldap->search("(uid=".preg_replace('/[{}]/', '', $uid).")",array('dn'));
2190     if($ldap->count() == 0){
2191       /* Add uid, but remove {} first. These are invalid anyway. */
2192       $ret[]= preg_replace('/[{}]/', '', $uid);
2193     }
2194   }
2196   return(array_unique($ret));
2200 /*! \brief Convert various data sizes to bytes
2201  *
2202  * Given a certain value in the format n(g|m|k), where n
2203  * is a value and (g|m|k) stands for Gigabyte, Megabyte and Kilobyte
2204  * this function returns the byte value.
2205  *
2206  * \param string 'value' a value in the above specified format
2207  * \return a byte value or the original value if specified string is simply
2208  * a numeric value
2209  *
2210  */
2211 function to_byte($value) {
2212   $value= strtolower(trim($value));
2214   if(!is_numeric(substr($value, -1))) {
2216     switch(substr($value, -1)) {
2217       case 'g':
2218         $mult= 1073741824;
2219         break;
2220       case 'm':
2221         $mult= 1048576;
2222         break;
2223       case 'k':
2224         $mult= 1024;
2225         break;
2226     }
2228     return ($mult * (int)substr($value, 0, -1));
2229   } else {
2230     return $value;
2231   }
2235 /*! \brief Check if a value exists in an array (case-insensitive)
2236  * 
2237  * This is just as http://php.net/in_array except that the comparison
2238  * is case-insensitive.
2239  *
2240  * \param string 'value' needle
2241  * \param array 'items' haystack
2242  */ 
2243 function in_array_ics($value, $items)
2245         return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
2249 /*! \brief Generate a clickable alphabet */
2250 function generate_alphabet($count= 10)
2252   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
2253   $alphabet= "";
2254   $c= 0;
2256   /* Fill cells with charaters */
2257   for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
2258     if ($c == 0){
2259       $alphabet.= "<tr>";
2260     }
2262     $ch = mb_substr($characters, $i, 1, "UTF8");
2263     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
2264       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
2266     if ($c++ == $count){
2267       $alphabet.= "</tr>";
2268       $c= 0;
2269     }
2270   }
2272   /* Fill remaining cells */
2273   while ($c++ <= $count){
2274     $alphabet.= "<td>&nbsp;</td>";
2275   }
2277   return ($alphabet);
2281 /*! \brief Removes malicious characters from a (POST) string. */
2282 function validate($string)
2284   return (strip_tags(str_replace('\0', '', $string)));
2288 /*! \brief Evaluate the current GOsa version from the build in revision string */
2289 function get_gosa_version()
2291     global $svn_revision, $svn_path;
2293     /* Extract informations */
2294     $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
2296     // Extract the relevant part out of the svn url
2297     $release= preg_replace('%^.*/gosa/(.*)/include/functions.inc.*$%', '\1', $svn_path);
2299     // Remove stuff which is not interesting
2300     if(preg_match("/gosa-core/i", $release)) $release = preg_replace("/[\/]gosa-core/i","",$release);
2302     // A Tagged Version
2303     if(preg_match("#/tags/#i", $svn_path)){
2304         $release = preg_replace("/tags[\/]*/i","",$release);
2305         $release = preg_replace("/\//","",$release) ;
2306         return (sprintf(_("GOsa %s"),$release));
2307     }
2309     // A Branched Version
2310     if(preg_match("#/branches/#i", $svn_path)){
2311         $release = preg_replace("/branches[\/]*/i","",$release);
2312         $release = preg_replace("/\//","",$release) ;
2313         return (sprintf(_("GOsa %s snapshot (Rev %s)"),$release , $revision));
2314     }
2316     // The trunk version
2317     if(preg_match("#/trunk/#i", $svn_path)){
2318         return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
2319     }
2321     return (sprintf(_("GOsa $release"), $revision));
2325 /*! \brief Recursively delete a path in the file system
2326  *
2327  * Will delete the given path and all its files recursively.
2328  * Can also follow links if told so.
2329  *
2330  * \param string 'path'
2331  * \param boolean 'followLinks' TRUE to follow links, FALSE (default)
2332  * for not following links
2333  */
2334 function rmdirRecursive($path, $followLinks=false) {
2335   $dir= opendir($path);
2336   while($entry= readdir($dir)) {
2337     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
2338       unlink($path."/".$entry);
2339     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
2340       rmdirRecursive($path."/".$entry);
2341     }
2342   }
2343   closedir($dir);
2344   return rmdir($path);
2348 /*! \brief Get directory content information
2349  *
2350  * Returns the content of a directory as an array in an
2351  * ascended sorted manner.
2352  *
2353  * \param string 'path'
2354  * \param boolean weither to sort the content descending.
2355  */
2356 function scan_directory($path,$sort_desc=false)
2358   $ret = false;
2360   /* is this a dir ? */
2361   if(is_dir($path)) {
2363     /* is this path a readable one */
2364     if(is_readable($path)){
2366       /* Get contents and write it into an array */   
2367       $ret = array();    
2369       $dir = opendir($path);
2371       /* Is this a correct result ?*/
2372       if($dir){
2373         while($fp = readdir($dir))
2374           $ret[]= $fp;
2375       }
2376     }
2377   }
2378   /* Sort array ascending , like scandir */
2379   sort($ret);
2381   /* Sort descending if parameter is sort_desc is set */
2382   if($sort_desc) {
2383     $ret = array_reverse($ret);
2384   }
2386   return($ret);
2390 /*! \brief Clean the smarty compile dir */
2391 function clean_smarty_compile_dir($directory)
2393   global $svn_revision;
2395   if(is_dir($directory) && is_readable($directory)) {
2396     // Set revision filename to REVISION
2397     $revision_file= $directory."/REVISION";
2399     /* Is there a stamp containing the current revision? */
2400     if(!file_exists($revision_file)) {
2401       // create revision file
2402       create_revision($revision_file, $svn_revision);
2403     } else {
2404       # check for "$config->...['CONFIG']/revision" and the
2405       # contents should match the revision number
2406       if(!compare_revision($revision_file, $svn_revision)){
2407         // If revision differs, clean compile directory
2408         foreach(scan_directory($directory) as $file) {
2409           if(($file==".")||($file=="..")) continue;
2410           if( is_file($directory."/".$file) &&
2411               is_writable($directory."/".$file)) {
2412             // delete file
2413             if(!unlink($directory."/".$file)) {
2414               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
2415               // This should never be reached
2416             }
2417           } elseif(is_dir($directory."/".$file) &&
2418               is_writable($directory."/".$file)) {
2419             // Just recursively delete it
2420             rmdirRecursive($directory."/".$file);
2421           }
2422         }
2423         // We should now create a fresh revision file
2424         clean_smarty_compile_dir($directory);
2425       } else {
2426         // Revision matches, nothing to do
2427       }
2428     }
2429   } else {
2430     // Smarty compile dir is not accessible
2431     // (Smarty will warn about this)
2432   }
2436 function create_revision($revision_file, $revision)
2438   $result= false;
2440   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2441     if($fh= fopen($revision_file, "w")) {
2442       if(fwrite($fh, $revision)) {
2443         $result= true;
2444       }
2445     }
2446     fclose($fh);
2447   } else {
2448     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2449   }
2451   return $result;
2455 function compare_revision($revision_file, $revision)
2457   // false means revision differs
2458   $result= false;
2460   if(file_exists($revision_file) && is_readable($revision_file)) {
2461     // Open file
2462     if($fh= fopen($revision_file, "r")) {
2463       // Compare File contents with current revision
2464       if($revision == fread($fh, filesize($revision_file))) {
2465         $result= true;
2466       }
2467     } else {
2468       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2469     }
2470     // Close file
2471     fclose($fh);
2472   }
2474   return $result;
2478 /*! \brief Return HTML for a progressbar
2479  *
2480  * \code
2481  * $smarty->assign("installprogress", progressbar($current_progress_in_percent),100,15,true); 
2482  * \endcode
2483  *
2484  * \param int 'percentage' Value to display
2485  * \param int 'width' width of the resulting output
2486  * \param int 'height' height of the resulting output
2487  * \param boolean 'showvalue' weither to show the percentage in the progressbar or not
2488  * */
2489 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2491   return("<img src='progress.php?x=$width&amp;y=$height&amp;p=$percentage'>");
2495 /*! \brief Lookup a key in an array case-insensitive
2496  *
2497  * Given an associative array this can lookup the value of
2498  * a certain key, regardless of the case.
2499  *
2500  * \code
2501  * $items = array ('FOO' => 'blub', 'bar' => 'blub');
2502  * array_key_ics('foo', $items); # Returns 'blub'
2503  * array_key_ics('BAR', $items); # Returns 'blub'
2504  * \endcode
2505  *
2506  * \param string 'key' needle
2507  * \param array 'items' haystack
2508  */
2509 function array_key_ics($ikey, $items)
2511   $tmp= array_change_key_case($items, CASE_LOWER);
2512   $ikey= strtolower($ikey);
2513   if (isset($tmp[$ikey])){
2514     return($tmp[$ikey]);
2515   }
2517   return ('');
2521 /*! \brief Determine if two arrays are different
2522  *
2523  * \param array 'src'
2524  * \param array 'dst'
2525  * \return boolean TRUE or FALSE
2526  * */
2527 function array_differs($src, $dst)
2529   /* If the count is differing, the arrays differ */
2530   if (count ($src) != count ($dst)){
2531     return (TRUE);
2532   }
2534   return (count(array_diff($src, $dst)) != 0);
2538 function saveFilter($a_filter, $values)
2540   if (isset($_POST['regexit'])){
2541     $a_filter["regex"]= $_POST['regexit'];
2543     foreach($values as $type){
2544       if (isset($_POST[$type])) {
2545         $a_filter[$type]= "checked";
2546       } else {
2547         $a_filter[$type]= "";
2548       }
2549     }
2550   }
2552   /* React on alphabet links if needed */
2553   if (isset($_GET['search'])){
2554     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2555     if ($s == "**"){
2556       $s= "*";
2557     }
2558     $a_filter['regex']= $s;
2559   }
2561   return ($a_filter);
2565 /*! \brief Escape all LDAP filter relevant characters */
2566 function normalizeLdap($input)
2568   return (addcslashes($input, '()|'));
2572 /*! \brief Return the gosa base directory */
2573 function get_base_dir()
2575   global $BASE_DIR;
2577   return $BASE_DIR;
2581 /*! \brief Test weither we are allowed to read the object */
2582 function obj_is_readable($dn, $object, $attribute)
2584   global $ui;
2586   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2590 /*! \brief Test weither we are allowed to change the object */
2591 function obj_is_writable($dn, $object, $attribute)
2593   global $ui;
2595   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2599 /*! \brief Explode a DN into its parts
2600  *
2601  * Similar to explode (http://php.net/explode), but a bit more specific
2602  * for the needs when splitting, exploding LDAP DNs.
2603  *
2604  * \param string 'dn' the DN to split
2605  * \param config-object a config object. only neeeded if DN shall be verified in the LDAP
2606  * \param boolean verify_in_ldap check weither DN is valid
2607  *
2608  */
2609 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2611   /* Initialize variables */
2612   $ret  = array("count" => 0);  // Set count to 0
2613   $next = true;                 // if false, then skip next loops and return
2614   $cnt  = 0;                    // Current number of loops
2615   $max  = 100;                  // Just for security, prevent looops
2616   $ldap = NULL;                 // To check if created result a valid
2617   $keep = "";                   // save last failed parse string
2619   /* Check each parsed dn in ldap ? */
2620   if($config!==NULL && $verify_in_ldap){
2621     $ldap = $config->get_ldap_link();
2622   }
2624   /* Lets start */
2625   $called = false;
2626   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2628     $cnt ++;
2629     if(!preg_match("/,/",$dn)){
2630       $next = false;
2631     }
2632     $object = preg_replace("/[,].*$/","",$dn);
2633     $dn     = preg_replace("/^[^,]+,/","",$dn);
2635     $called = true;
2637     /* Check if current dn is valid */
2638     if($ldap!==NULL){
2639       $ldap->cd($dn);
2640       $ldap->cat($dn,array("dn"));
2641       if($ldap->count()){
2642         $ret[]  = $keep.$object;
2643         $keep   = "";
2644       }else{
2645         $keep  .= $object.",";
2646       }
2647     }else{
2648       $ret[]  = $keep.$object;
2649       $keep   = "";
2650     }
2651   }
2653   /* No dn was posted */
2654   if($cnt == 0 && !empty($dn)){
2655     $ret[] = $dn;
2656   }
2658   /* Append the rest */
2659   $test = $keep.$dn;
2660   if($called && !empty($test)){
2661     $ret[] = $keep.$dn;
2662   }
2663   $ret['count'] = count($ret) - 1;
2665   return($ret);
2669 function get_base_from_hook($dn, $attrib)
2671   global $config;
2673   if ($config->get_cfg_value("baseIdHook") != ""){
2674     
2675     /* Call hook script - if present */
2676     $command= $config->get_cfg_value("baseIdHook");
2678     if ($command != ""){
2679       $command.= " '".LDAP::fix($dn)."' $attrib";
2680       if (check_command($command)){
2681         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2682         exec($command, $output);
2683         if (preg_match("/^[0-9]+$/", $output[0])){
2684           return ($output[0]);
2685         } else {
2686           msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2687           return ($config->get_cfg_value("uidNumberBase"));
2688         }
2689       } else {
2690         msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2691         return ($config->get_cfg_value("uidNumberBase"));
2692       }
2694     } else {
2696       msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2697       return ($config->get_cfg_value("uidNumberBase"));
2699     }
2700   }
2704 /*! \brief Check if schema version matches the requirements */
2705 function check_schema_version($class, $version)
2707   return preg_match("/\(v$version\)/", $class['DESC']);
2711 /*! \brief Check if LDAP schema matches the requirements */
2712 function check_schema($cfg,$rfc2307bis = FALSE)
2714   $messages= array();
2716   /* Get objectclasses */
2717   $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2718   $objectclasses = $ldap->get_objectclasses();
2719   if(count($objectclasses) == 0){
2720     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2721   }
2723   /* This is the default block used for each entry.
2724    *  to avoid unset indexes.
2725    */
2726   $def_check = array("REQUIRED_VERSION" => "0",
2727       "SCHEMA_FILES"     => array(),
2728       "CLASSES_REQUIRED" => array(),
2729       "STATUS"           => FALSE,
2730       "IS_MUST_HAVE"     => FALSE,
2731       "MSG"              => "",
2732       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2734   /* The gosa base schema */
2735   $checks['gosaObject'] = $def_check;
2736   $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2737   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa-samba3.schema","gosa-samba2.schema");
2738   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2739   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2741   /* GOsa Account class */
2742   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.6";
2743   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa-samba3.schema","gosa-samba2.schema");
2744   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2745   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2746   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2748   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2749   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2750   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa-samba3.schema","gosa-samba2.schema");
2751   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2752   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2753   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2755   /* Some other checks */
2756   foreach(array(
2757         "gosaCacheEntry"        => array("version" => "2.6.1", "class" => "gosaAccount"),
2758         "gosaDepartment"        => array("version" => "2.6.1", "class" => "gosaAccount"),
2759         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2760         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2761         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2762         "gosaUserTemplate"      => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2763         "gosaMailAccount"       => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa-samba3.schema"),
2764         "gosaProxyAccount"      => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa-samba3.schema"),
2765         "gosaApplication"       => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2766         "gosaApplicationGroup"  => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2767         "GOhard"                => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2768         "gotoTerminal"          => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2769         "goServer"              => array("version" => "2.6.1", "class" => "server","file" => "goserver.schema"),
2770         "goTerminalServer"      => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2771         "goShareServer"         => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2772         "goNtpServer"           => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2773         "goSyslogServer"        => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2774         "goLdapServer"          => array("version" => "2.6.1", "class" => "goServer"),
2775         "goCupsServer"          => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2776         "goImapServer"          => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa-samba3.schema"),
2777         "goKrbServer"           => array("version" => "2.6.1", "class" => "goServer"),
2778         "goFaxServer"           => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2779         ) as $name => $values){
2781           $checks[$name] = $def_check;
2782           if(isset($values['version'])){
2783             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2784           }
2785           if(isset($values['file'])){
2786             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2787           }
2788           if (isset($values['class'])) {
2789             $checks[$name]["CLASSES_REQUIRED"] = is_array($values['class'])?$values['class']:array($values['class']);
2790           }
2791         }
2792   foreach($checks as $name => $value){
2793     foreach($value['CLASSES_REQUIRED'] as $class){
2795       if(!isset($objectclasses[$name])){
2796         if($value['IS_MUST_HAVE']){
2797           $checks[$name]['STATUS'] = FALSE;
2798           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2799         } else {
2800           $checks[$name]['STATUS'] = TRUE;
2801           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2802         }
2803       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2804         $checks[$name]['STATUS'] = FALSE;
2806         $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2807       }else{
2808         $checks[$name]['STATUS'] = TRUE;
2809         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2810       }
2811     }
2812   }
2814   $tmp = $objectclasses;
2816   /* The gosa base schema */
2817   $checks['posixGroup'] = $def_check;
2818   $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2819   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa-samba3.schema","gosa-samba2.schema");
2820   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2821   $checks['posixGroup']['STATUS']           = TRUE;
2822   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2823   $checks['posixGroup']['MSG']              = "";
2824   $checks['posixGroup']['INFO']             = "";
2826   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2827   if(isset($tmp['posixGroup'])){
2829     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2830       $checks['posixGroup']['STATUS']           = FALSE;
2831       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2832       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2833     }
2834     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2835       $checks['posixGroup']['STATUS']           = FALSE;
2836       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2837       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2838     }
2839   }
2841   return($checks);
2845 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2847   $tmp = array(
2848         "de_DE" => "German",
2849         "fr_FR" => "French",
2850         "it_IT" => "Italian",
2851         "es_ES" => "Spanish",
2852         "en_US" => "English",
2853         "nl_NL" => "Dutch",
2854         "pl_PL" => "Polish",
2855         #"sv_SE" => "Swedish",
2856         "zh_CN" => "Chinese",
2857         "vi_VN" => "Vietnamese",
2858         "ru_RU" => "Russian");
2859   
2860   $tmp2= array(
2861         "de_DE" => _("German"),
2862         "fr_FR" => _("French"),
2863         "it_IT" => _("Italian"),
2864         "es_ES" => _("Spanish"),
2865         "en_US" => _("English"),
2866         "nl_NL" => _("Dutch"),
2867         "pl_PL" => _("Polish"),
2868         #"sv_SE" => _("Swedish"),
2869         "zh_CN" => _("Chinese"),
2870         "vi_VN" => _("Vietnamese"),
2871         "ru_RU" => _("Russian"));
2873   $ret = array();
2874   if($languages_in_own_language){
2876     $old_lang = setlocale(LC_ALL, 0);
2878     /* If the locale wasn't correclty set before, there may be an incorrect
2879         locale returned. Something like this: 
2880           C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2881         Extract the locale name from this string and use it to restore old locale.
2882      */
2883     if(preg_match("/LC_CTYPE/",$old_lang)){
2884       $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2885     }
2886     
2887     foreach($tmp as $key => $name){
2888       $lang = $key.".UTF-8";
2889       setlocale(LC_ALL, $lang);
2890       if($strip_region_tag){
2891         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2892       }else{
2893         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2894       }
2895     }
2896     setlocale(LC_ALL, $old_lang);
2897   }else{
2898     foreach($tmp as $key => $name){
2899       if($strip_region_tag){
2900         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2901       }else{
2902         $ret[$key] = _($name);
2903       }
2904     }
2905   }
2906   return($ret);
2910 /*! \brief Returns contents of the given POST variable and check magic quotes settings
2911  *
2912  * Depending on the magic quotes settings this returns a stripclashed'ed version of
2913  * a certain POST variable.
2914  *
2915  * \param string 'name' the POST var to return ($_POST[$name])
2916  * \return string
2917  * */
2918 function get_post($name)
2920   if(!isset($_POST[$name])){
2921     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2922     return(FALSE);
2923   }
2925   if(get_magic_quotes_gpc()){
2926     return(stripcslashes(validate($_POST[$name])));
2927   }else{
2928     return(validate($_POST[$name]));
2929   }
2933 /*! \brief Return class name in correct case */
2934 function get_correct_class_name($cls)
2936   global $class_mapping;
2937   if(isset($class_mapping) && is_array($class_mapping)){
2938     foreach($class_mapping as $class => $file){
2939       if(preg_match("/^".$cls."$/i",$class)){
2940         return($class);
2941       }
2942     }
2943   }
2944   return(FALSE);
2948 /*! \brief Change the password of a given DN
2949  * 
2950  * Change the password of a given DN with the specified hash.
2951  *
2952  * \param string 'dn' the DN whose password shall be changed
2953  * \param string 'password' the password
2954  * \param int mode
2955  * \param string 'hash' which hash to use to encrypt it, default is empty
2956  * for cleartext storage.
2957  * \return boolean TRUE on success FALSE on error
2958  */
2959 function change_password ($dn, $password, $mode=0, $hash= "")
2961   global $config;
2962   $newpass= "";
2964   /* Convert to lower. Methods are lowercase */
2965   $hash= strtolower($hash);
2967   // Get all available encryption Methods
2969   // NON STATIC CALL :)
2970   $methods = new passwordMethod(session::get('config'),$dn);
2971   $available = $methods->get_available_methods();
2973   // read current password entry for $dn, to detect the encryption Method
2974   $ldap       = $config->get_ldap_link();
2975   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2976   $attrs      = $ldap->fetch ();
2978   /* Is ensure that clear passwords will stay clear */
2979   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2980     $hash = "clear";
2981   }
2983   // Detect the encryption Method
2984   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2986     /* Check for supported algorithm */
2987     mt_srand((double) microtime()*1000000);
2989     /* Extract used hash */
2990     if ($hash == ""){
2991       $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2992     } else {
2993       $test = new $available[$hash]($config,$dn);
2994       $test->set_hash($hash);
2995     }
2997   } else {
2998     // User MD5 by default
2999     $hash= "md5";
3000     $test = new  $available['md5']($config, $dn);
3001   }
3003   if($test instanceOf passwordMethod){
3005     $deactivated = $test->is_locked($config,$dn);
3007     /* Feed password backends with information */
3008     $test->dn= $dn;
3009     $test->attrs= $attrs;
3010     $newpass= $test->generate_hash($password);
3012     // Update shadow timestamp?
3013     if (isset($attrs["shadowLastChange"][0])){
3014       $shadow= (int)(date("U") / 86400);
3015     } else {
3016       $shadow= 0;
3017     }
3019     // Write back modified entry
3020     $ldap->cd($dn);
3021     $attrs= array();
3023     // Not for groups
3024     if ($mode == 0){
3026         // Create SMB Password
3027         if ($config->get_cfg_value('sambaHashHook', NULL)) { 
3028             echo "111111";
3029             $attrs= generate_smb_nt_hash($password);
3031             if ($shadow != 0){
3032                 $attrs['shadowLastChange']= $shadow;
3033             }
3034         }
3035     }
3037     $attrs['userPassword']= array();
3038     $attrs['userPassword']= $newpass;
3040     $ldap->modify($attrs);
3042     /* Read ! if user was deactivated */
3043     if($deactivated){
3044       $test->lock_account($config,$dn);
3045     }
3047     new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
3049     if (!$ldap->success()) {
3050       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
3051     } else {
3053       /* Run backend method for change/create */
3054       if(!$test->set_password($password)){
3055         return(FALSE);
3056       }
3058       /* Find postmodify entries for this class */
3059       $command= $config->search("password", "POSTMODIFY",array('menu'));
3061       if ($command != ""){
3062         /* Walk through attribute list */
3063         $command= preg_replace("/%userPassword/", $password, $command);
3064         $command= preg_replace("/%dn/", $dn, $command);
3066         if (check_command($command)){
3067           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
3068           exec($command);
3069         } else {
3070           $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
3071           msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
3072         }
3073       }
3074     }
3075     return(TRUE);
3076   }
3080 /*! \brief Generate samba hashes
3081  *
3082  * Given a certain password this constructs an array like
3083  * array['sambaLMPassword'] etc.
3084  *
3085  * \param string 'password'
3086  * \return array contains several keys for lmPassword, ntPassword, pwdLastSet, etc. depending
3087  * on the samba version
3088  */
3089 function generate_smb_nt_hash($password)
3091   global $config;
3093   # Try to use gosa-si?
3094   if ($config->get_cfg_value("gosaSupportURI") != ""){
3095         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
3096     if (isset($res['XML']['HASH'])){
3097         $hash= $res['XML']['HASH'];
3098     } else {
3099       $hash= "";
3100     }
3102     if ($hash == "") {
3103       msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
3104       return ("");
3105     }
3106   } else {
3107           $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
3108           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
3110           exec($tmp, $ar);
3111           flush();
3112           reset($ar);
3113           $hash= current($ar);
3115     if ($hash == "") {
3116       msg_dialog::display(_("Configuration error"), sprintf(_("Cannot generate samba hash: running '%s' failed, check the 'sambaHashHook'!"),$config->get_cfg_value('sambaHashHook')), ERROR_DIALOG);
3117       return ("");
3118     }
3119   }
3121   list($lm,$nt)= explode(":", trim($hash));
3123   $attrs['sambaLMPassword']= $lm;
3124   $attrs['sambaNTPassword']= $nt;
3125   $attrs['sambaPwdLastSet']= date('U');
3126   $attrs['sambaBadPasswordCount']= "0";
3127   $attrs['sambaBadPasswordTime']= "0";
3128   return($attrs);
3132 /*! \brief Get the Change Sequence Number of a certain DN
3133  *
3134  * To verify if a given object has been changed outside of Gosa
3135  * in the meanwhile, this function can be used to get the entryCSN
3136  * from the LDAP directory. It uses the attribute as configured
3137  * in modificationDetectionAttribute
3138  *
3139  * \param string 'dn'
3140  * \return either the result or "" in any other case
3141  */
3142 function getEntryCSN($dn)
3144   global $config;
3145   if(empty($dn) || !is_object($config)){
3146     return("");
3147   }
3149   /* Get attribute that we should use as serial number */
3150   $attr= $config->get_cfg_value("modificationDetectionAttribute");
3151   if($attr != ""){
3152     $ldap = $config->get_ldap_link();
3153     $ldap->cat($dn,array($attr));
3154     $csn = $ldap->fetch();
3155     if(isset($csn[$attr][0])){
3156       return($csn[$attr][0]);
3157     }
3158   }
3159   return("");
3163 /*! \brief Add (a) given objectClass(es) to an attrs entry
3164  * 
3165  * The function adds the specified objectClass(es) to the given
3166  * attrs entry.
3167  *
3168  * \param mixed 'classes' Either a single objectClass or several objectClasses
3169  * as an array
3170  * \param array 'attrs' The attrs array to be modified.
3171  *
3172  * */
3173 function add_objectClass($classes, &$attrs)
3175   if (is_array($classes)){
3176     $list= $classes;
3177   } else {
3178     $list= array($classes);
3179   }
3181   foreach ($list as $class){
3182     $attrs['objectClass'][]= $class;
3183   }
3187 /*! \brief Removes a given objectClass from the attrs entry
3188  *
3189  * Similar to add_objectClass, except that it removes the given
3190  * objectClasses. See it for the params.
3191  * */
3192 function remove_objectClass($classes, &$attrs)
3194   if (isset($attrs['objectClass'])){
3195     /* Array? */
3196     if (is_array($classes)){
3197       $list= $classes;
3198     } else {
3199       $list= array($classes);
3200     }
3202     $tmp= array();
3203     foreach ($attrs['objectClass'] as $oc) {
3204       foreach ($list as $class){
3205         if (strtolower($oc) != strtolower($class)){
3206           $tmp[]= $oc;
3207         }
3208       }
3209     }
3210     $attrs['objectClass']= $tmp;
3211   }
3215 /*! \brief  Initialize a file download with given content, name and data type. 
3216  *  \param  string data The content to send.
3217  *  \param  string name The name of the file.
3218  *  \param  string type The content identifier, default value is "application/octet-stream";
3219  */
3220 function send_binary_content($data,$name,$type = "application/octet-stream")
3222   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
3223   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
3224   header("Cache-Control: no-cache");
3225   header("Pragma: no-cache");
3226   header("Cache-Control: post-check=0, pre-check=0");
3227   header("Content-type: ".$type."");
3229   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
3231   /* Strip name if it is a complete path */
3232   if (preg_match ("/\//", $name)) {
3233         $name= basename($name);
3234   }
3235   
3236   /* force download dialog */
3237   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
3238     header('Content-Disposition: filename="'.$name.'"');
3239   } else {
3240     header('Content-Disposition: attachment; filename="'.$name.'"');
3241   }
3243   echo $data;
3244   exit();
3248 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
3250   if(is_string($str)){
3251     return(htmlentities($str,$type,$charset));
3252   }elseif(is_array($str)){
3253     foreach($str as $name => $value){
3254       $str[$name] = reverse_html_entities($value,$type,$charset);
3255     }
3256   }
3257   return($str);
3261 /*! \brief Encode special string characters so we can use the string in \
3262            HTML output, without breaking quotes.
3263     \param string The String we want to encode.
3264     \return string The encoded String
3265  */
3266 function xmlentities($str)
3267
3268   if(is_string($str)){
3270     static $asc2uni= array();
3271     if (!count($asc2uni)){
3272       for($i=128;$i<256;$i++){
3273     #    $asc2uni[chr($i)] = "&#x".dechex($i).";";
3274       }
3275     }
3277     $str = str_replace("&", "&amp;", $str);
3278     $str = str_replace("<", "&lt;", $str);
3279     $str = str_replace(">", "&gt;", $str);
3280     $str = str_replace("'", "&apos;", $str);
3281     $str = str_replace("\"", "&quot;", $str);
3282     $str = str_replace("\r", "", $str);
3283     $str = strtr($str,$asc2uni);
3284     return $str;
3285   }elseif(is_array($str)){
3286     foreach($str as $name => $value){
3287       $str[$name] = xmlentities($value);
3288     }
3289   }
3290   return($str);
3294 /*! \brief  Updates all accessTo attributes from a given value to a new one.
3295             For example if a host is renamed.
3296     \param  String  $from The source accessTo name.
3297     \param  String  $to   The destination accessTo name.
3298 */
3299 function update_accessTo($from,$to)
3301   global $config;
3302   $ldap = $config->get_ldap_link();
3303   $ldap->cd($config->current['BASE']);
3304   $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
3305   while($attrs = $ldap->fetch()){
3306     $new_attrs = array("accessTo" => array());
3307     $dn = $attrs['dn'];
3308     for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
3309       $new_attrs['objectClass'][] =  $attrs['objectClass'][$i];
3310     }
3311     for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
3312       if($attrs['accessTo'][$i] == $from){
3313         if(!empty($to)){
3314           $new_attrs['accessTo'][] =  $to;
3315         }
3316       }else{
3317         $new_attrs['accessTo'][] =  $attrs['accessTo'][$i]; 
3318       }
3319     }
3320     $ldap->cd($dn);
3321     $ldap->modify($new_attrs);
3322     if (!$ldap->success()){
3323       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
3324     }
3325     new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
3326   }
3330 /*! \brief Returns a random char */
3331 function get_random_char () {
3332      $randno = rand (0, 63);
3333      if ($randno < 12) {
3334          return (chr ($randno + 46)); // Digits, '/' and '.'
3335      } else if ($randno < 38) {
3336          return (chr ($randno + 53)); // Uppercase
3337      } else {
3338          return (chr ($randno + 59)); // Lowercase
3339      }
3343 function cred_encrypt($input, $password) {
3345   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3346   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3348   return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
3353 function cred_decrypt($input,$password) {
3354   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3355   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3357   return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
3361 function get_object_info()
3363   return(session::get('objectinfo'));
3367 function set_object_info($str = "")
3369   session::set('objectinfo',$str);
3373 function isIpInNet($ip, $net, $mask) {
3374    // Move to long ints
3375    $ip= ip2long($ip);
3376    $net= ip2long($net);
3377    $mask= ip2long($mask);
3379    // Mask given IP with mask. If it returns "net", we're in...
3380    $res= $ip & $mask;
3382    return ($res == $net);
3386 function get_next_id($attrib, $dn)
3388   global $config;
3390   switch ($config->get_cfg_value("idAllocationMethod", "traditional")){
3391     case "pool":
3392       return get_next_id_pool($attrib);
3393     case "traditional":
3394       return get_next_id_traditional($attrib, $dn);
3395   }
3397   msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("unknown idAllocation method!"), ERROR_DIALOG);
3398   return null;
3402 function get_next_id_pool($attrib) {
3403   global $config;
3405   /* Fill informational values */
3406   $min= $config->get_cfg_value("${attrib}PoolMin", 10000);
3407   $max= $config->get_cfg_value("${attrib}PoolMax", 40000);
3409   /* Sanity check */
3410   if ($min >= $max) {
3411     msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." ".sprintf(_("%sPoolMin >= %sPoolMax!"), $attrib), ERROR_DIALOG);
3412     return null;
3413   }
3415   /* ID to skip */
3416   $ldap= $config->get_ldap_link();
3417   $id= null;
3419   /* Try to allocate the ID several times before failing */
3420   $tries= 3;
3421   while ($tries--) {
3423     /* Look for ID map entry */
3424     $ldap->cd ($config->current['BASE']);
3425     $ldap->search ("(&(objectClass=sambaUnixIdPool)($attrib=*))", array("$attrib"));
3427     /* If it does not exist, create one with these defaults */
3428     if ($ldap->count() == 0) {
3429       /* Fill informational values */
3430       $minUserId= $config->get_cfg_value("uidPoolMin", 10000);
3431       $minGroupId= $config->get_cfg_value("gidPoolMin", 10000);
3433       /* Add as default */
3434       $attrs= array("objectClass" => array("organizationalUnit", "sambaUnixIdPool"));
3435       $attrs["ou"]= "idmap";
3436       $attrs["uidNumber"]= $minUserId;
3437       $attrs["gidNumber"]= $minGroupId;
3438       $ldap->cd("ou=idmap,".$config->current['BASE']);
3439       $ldap->add($attrs);
3440       if ($ldap->error != "Success") {
3441         msg_dialog::display(_("Error"), _("Cannot create sambaUnixIdPool entry!"), ERROR_DIALOG);
3442         return null;
3443       }
3444       $tries++;
3445       continue;
3446     }
3447     /* Bail out if it's not unique */
3448     if ($ldap->count() != 1) {
3449       msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("sambaUnixIdPool is not unique!"), ERROR_DIALOG);
3450       return null;
3451     }
3453     /* Store old attrib and generate new */
3454     $attrs= $ldap->fetch();
3455     $dn= $ldap->getDN();
3456     $oldAttr= $attrs[$attrib][0];
3457     $newAttr= $oldAttr + 1;
3459     /* Sanity check */
3460     if ($newAttr >= $max) {
3461       msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("no ID available!"), ERROR_DIALOG);
3462       return null;
3463     }
3464     if ($newAttr < $min) {
3465       msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("no ID available!"), ERROR_DIALOG);
3466       return null;
3467     }
3469     #FIXME: PHP is not able to do a modification of "del: .../add: ...", so this
3470     #       is completely unsafe in the moment.
3471     #/* Remove old attr, add new attr */
3472     #$attrs= array($attrib => $oldAttr);
3473     #$ldap->rm($attrs, $dn);
3474     #if ($ldap->error != "Success") {
3475     #  continue;
3476     #}
3477     $ldap->cd($dn);
3478     $ldap->modify(array($attrib => $newAttr));
3479     if ($ldap->error != "Success") {
3480       msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." ".$ldap->get_error(), ERROR_DIALOG);
3481       return null;
3482     } else {
3483       return $oldAttr;
3484     }
3485   }
3487   /* Bail out if we had problems getting the next id */
3488   if (!$tries) {
3489     msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("maximum tries exceeded!"), ERROR_DIALOG);
3490   }
3492   return $id;
3496 function get_next_id_traditional($attrib, $dn)
3498   global $config;
3500   $ids= array();
3501   $ldap= $config->get_ldap_link();
3503   $ldap->cd ($config->current['BASE']);
3504   if (preg_match('/gidNumber/i', $attrib)){
3505     $oc= "posixGroup";
3506   } else {
3507     $oc= "posixAccount";
3508   }
3509   $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
3511   /* Get list of ids */
3512   while ($attrs= $ldap->fetch()){
3513     $ids[]= (int)$attrs["$attrib"][0];
3514   }
3516   /* Add the nobody id */
3517   $ids[]= 65534;
3519   /* get the ranges */
3520   $tmp = array('0'=> 1000);
3521   if (preg_match('/posixAccount/', $oc) && $config->get_cfg_value("uidNumberBase") != ""){
3522     $tmp= explode('-',$config->get_cfg_value("uidNumberBase"));
3523   } elseif($config->get_cfg_value("gidNumberBase") != ""){
3524     $tmp= explode('-',$config->get_cfg_value("gidNumberBase"));
3525   }
3527   /* Set hwm to max if not set - for backward compatibility */
3528   $lwm= $tmp[0];
3529   if (isset($tmp[1])){
3530     $hwm= $tmp[1];
3531   } else {
3532     $hwm= pow(2,32);
3533   }
3534   /* Find out next free id near to UID_BASE */
3535   if ($config->get_cfg_value("baseIdHook") == ""){
3536     $base= $lwm;
3537   } else {
3538     /* Call base hook */
3539     $base= get_base_from_hook($dn, $attrib);
3540   }
3541   for ($id= $base; $id++; $id < pow(2,32)){
3542     if (!in_array($id, $ids)){
3543       return ($id);
3544     }
3545   }
3547   /* Should not happen */
3548   if ($id == $hwm){
3549     msg_dialog::display(_("Error"), _("Cannot allocate a free ID!"), ERROR_DIALOG);
3550     exit;
3551   }
3555 /* Mark the occurance of a string with a span */
3556 function mark($needle, $haystack, $ignorecase= true)
3558   $result= "";
3560   while (preg_match('/^(.*)('.preg_quote($needle).')(.*)$/i', $haystack, $matches)) {
3561     $result.= $matches[1]."<span class='mark'>".$matches[2]."</span>";
3562     $haystack= $matches[3];
3563   }
3565   return $result.$haystack;
3568 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3569 ?>