Code

d14308bcb45988897ccb484c7606655a47c14ebe
[gosa.git] / gosa-core / include / functions.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id: functions.inc 13100 2008-12-01 14:07:48Z hickert $$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 /*! \file
24  * Common functions and named definitions. */
26 /* Define globals for revision comparing */
27 $svn_path = '$HeadURL$';
28 $svn_revision = '$Revision$';
30 /* Configuration file location */
31 if(!isset($_SERVER['CONFIG_DIR'])){
32   define ("CONFIG_DIR", "/etc/gosa");
33 }else{
34   define ("CONFIG_DIR",$_SERVER['CONFIG_DIR']);
35 }
37 /* Allow setting the config file in the apache configuration
38     e.g.  SetEnv CONFIG_FILE gosa.conf.2.6
39  */
40 if(!isset($_SERVER['CONFIG_FILE'])){
41   define ("CONFIG_FILE", "gosa.conf");
42 }else{
43   define ("CONFIG_FILE",$_SERVER['CONFIG_FILE']);
44 }
46 /* Define common locatitions */
47 define ("CONFIG_TEMPLATE_DIR", "../contrib");
48 define ("TEMP_DIR","/var/cache/gosa/tmp");
50 /* Define get_list flags */
51 define("GL_NONE",         0);
52 define("GL_SUBSEARCH",    1);
53 define("GL_SIZELIMIT",    2);
54 define("GL_CONVERT",      4);
55 define("GL_NO_ACL_CHECK", 8);
57 /* Heimdal stuff */
58 define('UNIVERSAL',0x00);
59 define('INTEGER',0x02);
60 define('OCTET_STRING',0x04);
61 define('OBJECT_IDENTIFIER ',0x06);
62 define('SEQUENCE',0x10);
63 define('SEQUENCE_OF',0x10);
64 define('SET',0x11);
65 define('SET_OF',0x11);
66 define('DEBUG',false);
67 define('HDB_KU_MKEY',0x484442);
68 define('TWO_BIT_SHIFTS',0x7efc);
69 define('DES_CBC_CRC',1);
70 define('DES_CBC_MD4',2);
71 define('DES_CBC_MD5',3);
72 define('DES3_CBC_MD5',5);
73 define('DES3_CBC_SHA1',16);
75 /* Include required files */
76 include_once("class_location.inc");
77 require_once ("functions_debug.inc");
78 require_once ("accept-to-gettext.inc");
80 /* Define constants for debugging */
81 define ("DEBUG_TRACE",   1); /*! Debug level for tracing of common actions (save, check, etc.) */
82 define ("DEBUG_LDAP",    2); /*! Debug level for LDAP queries */
83 define ("DEBUG_MYSQL",   4); /*! Debug level for mysql operations */
84 define ("DEBUG_SHELL",   8); /*! Debug level for shell commands */
85 define ("DEBUG_POST",   16); /*! Debug level for POST content */
86 define ("DEBUG_SESSION",32); /*! Debug level for SESSION content */
87 define ("DEBUG_CONFIG", 64); /*! Debug level for CONFIG information */
88 define ("DEBUG_ACL",    128); /*! Debug level for ACL infos */
89 define ("DEBUG_SI",     256); /*! Debug level for communication with gosa-si */
90 define ("DEBUG_MAIL",   512); /*! Debug level for all about mail (mailAccounts, imap, sieve etc.) */
91 define ("DEBUG_FAI",   1024); // FAI (incomplete)
92 define ("DEBUG_RPC",   2048); /*! Debug level for communication with remote procedures */
94 // Define shadow states
95 define ("POSIX_ACCOUNT_EXPIRED", 1);
96 define ("POSIX_WARN_ABOUT_EXPIRATION", 2);
97 define ("POSIX_FORCE_PASSWORD_CHANGE", 4);
98 define ("POSIX_DISALLOW_PASSWORD_CHANGE", 8);
100 /* Rewrite german 'umlauts' and spanish 'accents'
101    to get better results */
102 $REWRITE= array( "ä" => "ae",
103     "ö" => "oe",
104     "ü" => "ue",
105     "Ä" => "Ae",
106     "Ö" => "Oe",
107     "Ü" => "Ue",
108     "ß" => "ss",
109     "á" => "a",
110     "é" => "e",
111     "í" => "i",
112     "ó" => "o",
113     "ú" => "u",
114     "Á" => "A",
115     "É" => "E",
116     "Í" => "I",
117     "Ó" => "O",
118     "Ú" => "U",
119     "ñ" => "ny",
120     "Ñ" => "Ny" );
123 /*! \brief Does autoloading for classes used in GOsa.
124  *
125  *  Takes the list generated by 'update-gosa' and loads the
126  *  file containing the requested class.
127  *
128  *  \param  string 'class_name' The currently requested class
129  */
130 function __gosa_autoload($class_name) {
131     global $class_mapping, $BASE_DIR;
133     if ($class_mapping === NULL){
134             echo sprintf(_("Fatal error: no class locations defined - please run %s to fix this"), bold("update-gosa"));
135             exit;
136     }
138     if (isset($class_mapping["$class_name"])){
139       require_once($BASE_DIR."/".$class_mapping["$class_name"]);
140     } else {
141       echo sprintf(_("Fatal error: cannot instantiate class %s - try running %s to fix this"), bold($class_name), bold("update-gosa"));
142       exit;
143     }
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, $config;
155     
156   $disabled = array();
157   if($config instanceOf config && $config->configRegistry instanceOf configRegistry){
158     $disabled = $config->configRegistry->getDisabledPlugins();
159   }
161   return(isset($class_mapping[$name]) && !isset($disabled[$name]));
165 /*! \brief Check if plugin is available
166  *
167  * Checks if a given plugin is available and readable.
168  *
169  * \param string 'plugin' the subject of the check
170  * \return boolean True if plugin is available, else FALSE.
171  */
172 function plugin_available($plugin)
174         global $class_mapping, $BASE_DIR;
176         if (!isset($class_mapping[$plugin])){
177                 return false;
178         } else {
179                 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
180         }
184 /*! \brief Create seed with microseconds 
185  *
186  * Example:
187  * \code
188  * srand(make_seed());
189  * $random = rand();
190  * \endcode
191  *
192  * \return float a floating point number which can be used to feed srand() with it
193  * */
194 function make_seed() {
195   list($usec, $sec) = explode(' ', microtime());
196   return (float) $sec + ((float) $usec * 100000);
200 /*! \brief Debug level action 
201  *
202  * Print a DEBUG level if specified debug level of the level matches the 
203  * the configured debug level.
204  *
205  * \param int 'level' The log level of the message (should use the constants,
206  * defined in functions.in (DEBUG_TRACE, DEBUG_LDAP, etc.)
207  * \param int 'line' Define the line of the logged action (using __LINE__ is common)
208  * \param string 'function' Define the function where the logged action happened in
209  * (using __FUNCTION__ is common)
210  * \param string 'file' Define the file where the logged action happend in
211  * (using __FILE__ is common)
212  * \param mixed 'data' The data to log. Can be a message or an array, which is printed
213  * with print_a
214  * \param string 'info' Optional: Additional information
215  *
216  * */
217 function DEBUG($level, $line, $function, $file, $data, $info="")
219     global $config;
220     $debugLevel = 0;
221     if($config instanceOf config){
222         $debugLevel = $config->get_cfg_value('core', 'debugLevel');
223     }
224     if ($debugLevel & $level){
225         $output= "DEBUG[$level] ";
226         if ($function != ""){
227             $output.= "($file:$function():$line) - $info: ";
228         } else {
229             $output.= "($file:$line) - $info: ";
230         }
231         echo $output;
232         if (is_array($data)){
233             print_a($data);
234         } else {
235             echo "'$data'";
236         }
237         echo "<br>";
238     }
242 /*! \brief Determine which language to show to the user
243  *
244  * Determines which language should be used to present gosa content
245  * to the user. It does so by looking at several possibilites and returning
246  * the first setting that can be found.
247  *
248  * -# Language configured by the user
249  * -# Global configured language
250  * -# Language as returned by al2gt (as configured in the browser)
251  *
252  * \return string gettext locale string
253  */
254 function get_browser_language()
256   /* Try to use users primary language */
257   global $config;
258   $ui= get_userinfo();
259   if (isset($ui) && $ui !== NULL){
260     if ($ui->language != ""){
261       return ($ui->language.".UTF-8");
262     }
263   }
265   /* Check for global language settings in gosa.conf */
266   if (isset ($config) && $config->get_cfg_value("core",'language') != ""){
267     $lang = $config->get_cfg_value("core",'language');
268     if(!preg_match("/utf/i",$lang)){
269       $lang .= ".UTF-8";
270     }
271     return($lang);
272   }
273  
274   /* Load supported languages */
275   $gosa_languages= get_languages();
277   /* Move supported languages to flat list */
278   $langs= array();
279   foreach($gosa_languages as $lang => $dummy){
280     $langs[]= $lang.'.UTF-8';
281   }
283   /* Return gettext based string */
284   return (al2gt($langs, 'text/html'));
288 /*! \brief Rewrite ui object to another dn 
289  *
290  * Usually used when a user is renamed. In this case the dn
291  * in the user object must be updated in order to point
292  * to the correct DN.
293  *
294  * \param string 'dn' the old DN
295  * \param string 'newdn' the new DN
296  * */
297 function change_ui_dn($dn, $newdn)
299   $ui= session::global_get('ui');
300   if ($ui->dn == $dn){
301     $ui->dn= $newdn;
302     session::global_set('ui',$ui);
303   }
307 /*! \brief Return themed path for specified base file
308  *
309  *  Depending on its parameters, this function returns the full
310  *  path of a template file. First match wins while searching
311  *  in this order:
312  *
313  *  - load theme depending file
314  *  - load global theme depending file
315  *  - load default theme file
316  *  - load global default theme file
317  *
318  *  \param  string 'filename' The base file name
319  *  \param  boolean 'plugin' Flag to take the plugin directory as search base
320  *  \param  string 'path' User specified path to take as search base
321  *  \return string Full path to the template file
322  */
323 function get_template_path($filename= '', $plugin= FALSE, $path= "")
325   global $config, $BASE_DIR;
327   /* Set theme */
328   if (isset ($config)){
329         $theme= $config->get_cfg_value("core","theme");
330   } else {
331         $theme= "default";
332   }
334   /* Return path for empty filename */
335   if ($filename == ''){
336     return ("themes/$theme/");
337   }
339   /* Return plugin dir or root directory? */
340   if ($plugin){
341     if ($path == ""){
342       $nf= preg_replace("!^".$BASE_DIR."/!", "", preg_replace('/^\.\.\//', '', session::global_get('plugin_dir')));
343     } else {
344       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
345     }
346     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
347       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
348     }
349     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
350       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
351     }
352     if ($path == ""){
353       return (session::global_get('plugin_dir')."/$filename");
354     } else {
355       return ($path."/$filename");
356     }
357   } else {
358     if (file_exists("themes/$theme/$filename")){
359       return ("themes/$theme/$filename");
360     }
361     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
362       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
363     }
364     if (file_exists("themes/default/$filename")){
365       return ("themes/default/$filename");
366     }
367     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
368       return ("$BASE_DIR/ihtml/themes/default/$filename");
369     }
370     return ($filename);
371   }
375 /*! \brief Remove multiple entries from an array
376  *
377  * Removes every element that is in $needles from the
378  * array given as $haystack
379  *
380  * \param array 'needles' array of the entries to remove
381  * \param array 'haystack' original array to remove the entries from
382  */
383 function array_remove_entries($needles, $haystack)
385   return (array_merge(array_diff($haystack, $needles)));
389 /*! \brief Remove multiple entries from an array (case-insensitive)
390  *
391  * Same as array_remove_entries(), but case-insensitive. */
392 function array_remove_entries_ics($needles, $haystack)
394   // strcasecmp will work, because we only compare ASCII values here
395   return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
399 /*! Merge to array but remove duplicate entries
400  *
401  * Merges two arrays and removes duplicate entries. Triggers
402  * an error if first or second parametre is not an array.
403  *
404  * \param array 'ar1' first array
405  * \param array 'ar2' second array-
406  * \return array
407  */
408 function gosa_array_merge($ar1,$ar2)
410   if(!is_array($ar1) || !is_array($ar2)){
411     trigger_error("Specified parameter(s) are not valid arrays.");
412   }else{
413     return(array_values(array_unique(array_merge($ar1,$ar2))));
414   }
418 /*! \brief Generate a system log info
419  *
420  * Creates a syslog message, containing user information.
421  *
422  * \param string 'message' the message to log
423  * */
424 function gosa_log ($message)
426   global $ui;
428   /* Preset to something reasonable */
429   $username= "[unauthenticated]";
431   /* Replace username if object is present */
432   if (isset($ui)){
433     if ($ui->username != ""){
434       $username= "[$ui->username]";
435     } else {
436       $username= "[unknown]";
437     }
438   }
440   syslog(LOG_INFO,"GOsa$username: $message");
444 /*! \brief Initialize a LDAP connection
445  *
446  * Initializes a LDAP connection. 
447  *
448  * \param string 'server'
449  * \param string 'base'
450  * \param string 'binddn' Default: empty
451  * \param string 'pass' Default: empty
452  *
453  * \return LDAP object
454  */
455 function ldap_init ($server, $base, $binddn='', $pass='')
457   global $config;
459   $ldap = new LDAP ($binddn, $pass, $server,
460       isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
461       isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
463   /* Sadly we've no proper return values here. Use the error message instead. */
464   if (!$ldap->success()){
465     msg_dialog::display(_("Fatal error"),
466         sprintf(_("Error while connecting to LDAP: %s"), $ldap->get_error()),
467         FATAL_ERROR_DIALOG);
468     exit();
469   }
471   /* Preset connection base to $base and return to caller */
472   $ldap->cd ($base);
473   return $ldap;
477 /* \brief Process htaccess authentication */
478 function process_htaccess ($username, $kerberos= FALSE)
480   global $config;
482   /* Search for $username and optional @REALM in all configured LDAP trees */
483   foreach($config->data["LOCATIONS"] as $name => $data){
484   
485     $config->set_current($name);
486     $mode= "kerberos";
487     if ($config->get_cfg_value("core","useSaslForKerberos") == "true"){
488       $mode= "sasl";
489     }
491     /* Look for entry or realm */
492     $ldap= $config->get_ldap_link();
493     if (!$ldap->success()){
494       msg_dialog::display(_("LDAP error"), 
495           msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
496           FATAL_ERROR_DIALOG);
497       exit();
498     }
499     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
501     /* Found a uniq match? Return it... */
502     if ($ldap->count() == 1) {
503       $attrs= $ldap->fetch();
504       return array("username" => $attrs["uid"][0], "server" => $name);
505     }
506   }
508   /* Nothing found? Return emtpy array */
509   return array("username" => "", "server" => "");
513 /*! \brief Verify user login against htaccess
514  *
515  * Checks if the specified username is available in apache, maps the user
516  * to an LDAP user. The password has been checked by apache already.
517  *
518  * \param string 'username'
519  * \return
520  *  - TRUE on SUCCESS, NULL or FALSE on error
521  */
522 function ldap_login_user_htaccess ($username)
524   global $config;
526   /* Look for entry or realm */
527   $ldap= $config->get_ldap_link();
528   if (!$ldap->success()){
529     msg_dialog::display(_("LDAP error"), 
530         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
531         FATAL_ERROR_DIALOG);
532     exit();
533   }
534   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
535   /* Found no uniq match? Strange, because we did above... */
536   if ($ldap->count() != 1) {
537     msg_dialog::display(_("LDAP error"), _("User ID is not unique!"), FATAL_ERROR_DIALOG);
538     return (NULL);
539   }
540   $attrs= $ldap->fetch();
542   /* got user dn, fill acl's */
543   $ui= new userinfo($config, $ldap->getDN());
544   $ui->username= $attrs['uid'][0];
546   /* Bail out if we have login restrictions set, for security reasons
547      the message is the same than failed user/pw */
548   if (!$ui->loginAllowed()){
549     new log("security","login","",array(),"Login restriction for user \"$username\", login not permitted");
550     return (NULL);
551   }
553   /* No password check needed - the webserver did it for us */
554   $ldap->disconnect();
556   /* Username is set, load subtreeACL's now */
557   $ui->loadACL();
559   /* TODO: check java script for htaccess authentication */
560   session::global_set('js', true);
562   return ($ui);
566 /*! \brief Verify user login against LDAP directory
567  *
568  * Checks if the specified username is in the LDAP and verifies if the
569  * password is correct by binding to the LDAP with the given credentials.
570  *
571  * \param string 'username'
572  * \param string 'password'
573  * \return
574  *  - TRUE on SUCCESS, NULL or FALSE on error
575  */
576 function ldap_login_user ($username, $password)
578   global $config;
580   /* look through the entire ldap */
581   $ldap = $config->get_ldap_link();
582   if (!$ldap->success()){
583     msg_dialog::display(_("LDAP error"), 
584         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
585         FATAL_ERROR_DIALOG);
586     exit();
587   }
588   $ldap->cd($config->current['BASE']);
589   $allowed_attributes = array("uid","mail");
590   $verify_attr = array();
591   if($config->get_cfg_value("core","loginAttribute") != ""){
592     $tmp = explode(",", $config->get_cfg_value("core","loginAttribute")); 
593     foreach($tmp as $attr){
594       if(in_array($attr,$allowed_attributes)){
595         $verify_attr[] = $attr;
596       }
597     }
598   }
599   if(count($verify_attr) == 0){
600     $verify_attr = array("uid");
601   }
602   $tmp= $verify_attr;
603   $tmp[] = "uid";
604   $filter = "";
605   foreach($verify_attr as $attr) {
606     $filter.= "(".$attr."=".$username.")";
607   }
608   $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
609   $ldap->search($filter,$tmp);
611   /* get results, only a count of 1 is valid */
612   switch ($ldap->count()){
614     /* user not found */
615     case 0:     return (NULL);
617             /* valid uniq user */
618     case 1: 
619             break;
621             /* found more than one matching id */
622     default:
623             msg_dialog::display(_("Internal error"), _("User ID is not unique!"), FATAL_ERROR_DIALOG);
624             return (NULL);
625   }
627   /* LDAP schema is not case sensitive. Perform additional check. */
628   $attrs= $ldap->fetch();
629   $success = FALSE;
630   foreach($verify_attr as $attr){
631     if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
632       $success = TRUE;
633     }
634   }
635   if(!$success){
636     return(FALSE);
637   }
639   /* got user dn, fill acl's */
640   $ui= new userinfo($config, $ldap->getDN());
641   $ui->username= $attrs['uid'][0];
643   /* Bail out if we have login restrictions set, for security reasons
644      the message is the same than failed user/pw */
645   if (!$ui->loginAllowed()){
646     new log("security","login","",array(),"Login restriction for user \"$username\", login not permitted");
647     return (NULL);
648   }
650   /* password check, bind as user with supplied password  */
651   $ldap->disconnect();
652   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
653       isset($config->current['LDAPFOLLOWREFERRALS']) &&
654       $config->current['LDAPFOLLOWREFERRALS'] == "true",
655       isset($config->current['LDAPTLS'])
656       && $config->current['LDAPTLS'] == "true");
657   if (!$ldap->success()){
658     return (NULL);
659   }
661   /* Username is set, load subtreeACL's now */
662   $ui->loadACL();
664   return ($ui);
668 /*! \brief      Checks the posixAccount status by comparing the shadow attributes.
669  *
670  * @param Object    The GOsa configuration object.
671  * @param String    The 'dn' of the user to test the account status for.
672  * @param String    The 'uid' of the user we're going to test.
673  * @return Const
674  *                  POSIX_ACCOUNT_EXPIRED           - If the account is expired.
675  *                  POSIX_WARN_ABOUT_EXPIRATION     - If the account is going to expire.
676  *                  POSIX_FORCE_PASSWORD_CHANGE     - The password has to be changed.
677  *                  POSIX_DISALLOW_PASSWORD_CHANGE  - The password cannot be changed right now.
678  *
679  *
680  *
681  *      shadowLastChange
682  *      |
683  *      |---- shadowMin --->    |       <-- shadowMax --
684  *      |                       |       |
685  *      |------- shadowWarning ->       |
686  *                                      |-- shadowInactive --> DEACTIVATED
687  *                                      |
688  *                                      EXPIRED
689  *
690  */
691 function ldap_expired_account($config, $userdn, $uid)
693     // Skip this for the admin account, we do not want to lock him out.
694     if($uid == 'admin') return(0);
696     $ldap= $config->get_ldap_link();
697     $ldap->cd($config->current['BASE']);
698     $ldap->cat($userdn);
699     $attrs= $ldap->fetch();
700     $current= floor(date("U") /60 /60 /24);
702     // Fetch required attributes
703     foreach(array('shadowExpire','shadowLastChange','shadowMax','shadowMin',
704                 'shadowInactive','shadowWarning','sambaKickoffTime') as $attr){
705         $$attr = (isset($attrs[$attr][0]))? $attrs[$attr][0] : null;
706     }
709     // Check if the account has reached its kick off limitations.
710     // ---------------------------------------------------------
711     // Once the accout reaches the kick off limit it has expired.
712     if($sambaKickoffTime !== null){
713         if(time() >= $sambaKickoffTime){
714             return(POSIX_ACCOUNT_EXPIRED);
715         }
716     }
719     // Check if the account has expired.
720     // ---------------------------------
721     // An account is locked/expired once its expiration date has reached (shadowExpire).
722     // If the optional attribute (shadowInactive) is set, we've to postpone
723     //  the account expiration by the amount of days specified in (shadowInactive).
724     if($shadowExpire != null && $shadowExpire <= $current){
726         // The account seems to be expired, but we've to check 'shadowInactive' additionally.
727         // ShadowInactive specifies an amount of days we've to reprieve the user.
728         // It some kind of x days' grace.
729         if($shadowInactive == null || $current > $shadowExpire + $shadowInactive){
731             // Finally we've detect that the account is deactivated.
732             return(POSIX_ACCOUNT_EXPIRED);
733         }
734     }
736     // The users password is going to expire.
737     // --------------------------------------
738     // We've to warn the user in the case of an expiring account.
739     // An account is going to expire when it reaches its expiration date (shadowExpire).
740     // The user has to be warned, if the days left till expiration, match the
741     //  configured warning period (shadowWarning)
742     // --> shadowWarning: Warn x days before account expiration.
743     if($shadowExpire != null && $shadowWarning != null){
745         // Check if the account is still active and not already expired.
746         if($shadowExpire >= $current){
748             // Check if we've to warn the user by comparing the remaining
749             //  number of days till expiration with the configured amount
750             //  of days in shadowWarning.
751             if(($shadowExpire - $current) <= $shadowWarning){
752                 return(POSIX_WARN_ABOUT_EXPIRATION);
753             }
754         }
755     }
757     // -- I guess this is the correct detection, isn't it? 
758     if($shadowLastChange != null && $shadowWarning != null && $shadowMax != null){
759         $daysRemaining = ($shadowLastChange + $shadowMax) - $current ;
760         if($daysRemaining > 0 && $daysRemaining <= $shadowWarning){
761                 return(POSIX_WARN_ABOUT_EXPIRATION);
762         }
763     }
766     // Check if we've to force the user to change his password.
767     // --------------------------------------------------------
768     // A password change is enforced when the password is older than
769     //  the configured amount of days (shadowMax).
770     // The age of the current password (shadowLastChange) plus the maximum
771     //  amount amount of days (shadowMax) has to be smaller than the
772     //  current timestamp.
773     if($shadowLastChange != null && $shadowMax != null){
775         // Check if we've an outdated password.
776         if($current >= ($shadowLastChange + $shadowMax)){
777             return(POSIX_FORCE_PASSWORD_CHANGE);
778         }
779     }
782     // Check if we've to freeze the users password.
783     // --------------------------------------------
784     // Once a user has changed his password, he cannot change it again
785     //  for a given amount of days (shadowMin).
786     // We should not allow to change the password within GOsa too.
787     if($shadowLastChange != null && $shadowMin != null){
789         // Check if we've an outdated password.
790         if(($shadowLastChange + $shadowMin) >= $current){
791             return(POSIX_DISALLOW_PASSWORD_CHANGE);
792         }
793     }
795     return(0);
800 /*! \brief Add a lock for object(s)
801  *
802  * Adds a lock by the specified user for one ore multiple objects.
803  * If the lock for that object already exists, an error is triggered.
804  *
805  * \param mixed 'object' object or array of objects to lock
806  * \param string 'user' the user who shall own the lock
807  * */
808 function add_lock($object, $user)
810   global $config;
812   /* Remember which entries were opened as read only, because we 
813       don't need to remove any locks for them later.
814    */
815   if(!session::global_is_set("LOCK_CACHE")){
816     session::global_set("LOCK_CACHE",array(""));
817   }
818   if(is_array($object)){
819     foreach($object as $obj){
820       add_lock($obj,$user);
821     }
822     return;
823   }
825   $cache = &session::global_get("LOCK_CACHE");
826   if(isset($_POST['open_readonly'])){
827     $cache['READ_ONLY'][$object] = TRUE;
828     return;
829   }
830   if(isset($cache['READ_ONLY'][$object])){
831     unset($cache['READ_ONLY'][$object]);
832   }
835   /* Just a sanity check... */
836   if ($object == "" || $user == ""){
837     msg_dialog::display(_("Internal error"), _("Error while locking entry!"), ERROR_DIALOG);
838     return;
839   }
841   /* Check for existing entries in lock area */
842   $ldap= $config->get_ldap_link();
843   $ldap->cd ($config->get_cfg_value("core","config"));
844   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
845       array("gosaUser"));
846   if (!$ldap->success()){
847     msg_dialog::display(_("Configuration error"), sprintf(_("Cannot store lock information in LDAP!")."<br><br>"._('Error: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
848     return;
849   }
851   /* Add lock if none present */
852   if ($ldap->count() == 0){
853     $attrs= array();
854     $name= md5($object);
855     $ldap->cd("cn=$name,".$config->get_cfg_value("core","config"));
856     $attrs["objectClass"] = "gosaLockEntry";
857     $attrs["gosaUser"] = $user;
858     $attrs["gosaObject"] = base64_encode($object);
859     $attrs["cn"] = "$name";
860     $ldap->add($attrs);
861     if (!$ldap->success()){
862       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("core","config"), 0, ERROR_DIALOG));
863       return;
864     }
865   }
869 /*! \brief Remove a lock for object(s)
870  *
871  * Does the opposite of add_lock().
872  *
873  * \param mixed 'object' object or array of objects for which a lock shall be removed
874  * */
875 function del_lock ($object)
877   global $config;
879   if(is_array($object)){
880     foreach($object as $obj){
881       del_lock($obj);
882     }
883     return;
884   }
886   /* Sanity check */
887   if ($object == ""){
888     return;
889   }
891   /* If this object was opened in read only mode then 
892       skip removing the lock entry, there wasn't any lock created.
893     */
894   if(session::global_is_set("LOCK_CACHE")){
895     $cache = &session::global_get("LOCK_CACHE");
896     if(isset($cache['READ_ONLY'][$object])){
897       unset($cache['READ_ONLY'][$object]);
898       return;
899     }
900   }
902   /* Check for existance and remove the entry */
903   $ldap= $config->get_ldap_link();
904   $ldap->cd ($config->get_cfg_value("core","config"));
905   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
906   $attrs= $ldap->fetch();
907   if ($ldap->getDN() != "" && $ldap->success()){
908     $ldap->rmdir ($ldap->getDN());
910     if (!$ldap->success()){
911       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
912       return;
913     }
914   }
918 /*! \brief Remove all locks owned by a specific userdn
919  *
920  * For a given userdn remove all existing locks. This is usually
921  * called on logout.
922  *
923  * \param string 'userdn' the subject whose locks shall be deleted
924  */
925 function del_user_locks($userdn)
927   global $config;
929   /* Get LDAP ressources */ 
930   $ldap= $config->get_ldap_link();
931   $ldap->cd ($config->get_cfg_value("core","config"));
933   /* Remove all objects of this user, drop errors silently in this case. */
934   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
935   while ($attrs= $ldap->fetch()){
936     $ldap->rmdir($attrs['dn']);
937   }
941 /*! \brief Get a lock for a specific object
942  *
943  * Searches for a lock on a given object.
944  *
945  * \param string 'object' subject whose locks are to be searched
946  * \return string Returns the user who owns the lock or "" if no lock is found
947  * or an error occured. 
948  */
949 function get_lock ($object)
951   global $config;
953   /* Sanity check */
954   if ($object == ""){
955     msg_dialog::display(_("Internal error"), _("Error while locking entry!"), ERROR_DIALOG);
956     return("");
957   }
959   /* Allow readonly access, the plugin::plugin will restrict the acls */
960   if(isset($_POST['open_readonly'])) return("");
962   /* Get LDAP link, check for presence of the lock entry */
963   $user= "";
964   $ldap= $config->get_ldap_link();
965   $ldap->cd ($config->get_cfg_value("core","config"));
966   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
967   if (!$ldap->success()){
968     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
969     return("");
970   }
972   /* Check for broken locking information in LDAP */
973   if ($ldap->count() > 1){
975     /* Clean up these references now... */
976     while ($attrs= $ldap->fetch()){
977       $ldap->rmdir($attrs['dn']);
978     }
980     return("");
982   } elseif ($ldap->count() == 1){
983     $attrs = $ldap->fetch();
984     $user= $attrs['gosaUser'][0];
985   }
986   return ($user);
990 /*! Get locks for multiple objects
991  *
992  * Similar as get_lock(), but for multiple objects.
993  *
994  * \param array 'objects' Array of Objects for which a lock shall be searched
995  * \return A numbered array containing all found locks as an array with key 'dn'
996  * and key 'user' or "" if an error occured.
997  */
998 function get_multiple_locks($objects)
1000   global $config;
1002   if(is_array($objects)){
1003     $filter = "(&(objectClass=gosaLockEntry)(|";
1004     foreach($objects as $obj){
1005       $filter.="(gosaObject=".base64_encode($obj).")";
1006     }
1007     $filter.= "))";
1008   }else{
1009     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
1010   }
1012   /* Get LDAP link, check for presence of the lock entry */
1013   $user= "";
1014   $ldap= $config->get_ldap_link();
1015   $ldap->cd ($config->get_cfg_value("core","config"));
1016   $ldap->search($filter, array("gosaUser","gosaObject"));
1017   if (!$ldap->success()){
1018     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
1019     return("");
1020   }
1022   $users = array();
1023   while($attrs = $ldap->fetch()){
1024     $dn   = base64_decode($attrs['gosaObject'][0]);
1025     $user = $attrs['gosaUser'][0];
1026     $users[] = array("dn"=> $dn,"user"=>$user);
1027   }
1028   return ($users);
1032 /*! \brief Search base and sub-bases for all objects matching the filter
1033  *
1034  * This function searches the ldap database. It searches in $sub_bases,*,$base
1035  * for all objects matching the $filter.
1036  *  \param string 'filter'    The ldap search filter
1037  *  \param string 'category'  The ACL category the result objects belongs 
1038  *  \param string 'sub_bases' The sub base we want to search for e.g. "ou=apps"
1039  *  \param string 'base'      The ldap base from which we start the search
1040  *  \param array 'attributes' The attributes we search for.
1041  *  \param long 'flags'     A set of Flags
1042  */
1043 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
1045   global $config, $ui;
1046   $departments = array();
1048 #  $start = microtime(TRUE);
1050   /* Get LDAP link */
1051   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1053   /* Set search base to configured base if $base is empty */
1054   if ($base == ""){
1055     $base = $config->current['BASE'];
1056   }
1057   $ldap->cd ($base);
1059   /* Ensure we have an array as department list */
1060   if(is_string($sub_deps)){
1061     $sub_deps = array($sub_deps);
1062   }
1064   /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
1065   $sub_bases = array();
1066   foreach($sub_deps as $key => $sub_base){
1067     if(empty($sub_base)){
1069       /* Subsearch is activated and we got an empty sub_base.
1070        *  (This may be the case if you have empty people/group ous).
1071        * Fall back to old get_list(). 
1072        * A log entry will be written.
1073        */
1074       if($flags & GL_SUBSEARCH){
1075         $sub_bases = array();
1076         break;
1077       }else{
1078         
1079         /* Do NOT search within subtrees is requeste and the sub base is empty. 
1080          * Append all known departments that matches the base.
1081          */
1082         $departments[$base] = $base;
1083       }
1084     }else{
1085       $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
1086     }
1087   }
1088   
1089    /* If there is no sub_department specified, fall back to old method, get_list().
1090    */
1091   if(!count($sub_bases) && !count($departments)){
1092     
1093     /* Log this fall back, it may be an unpredicted behaviour.
1094      */
1095     if(!count($sub_bases) && !count($departments)){
1096       // log($action,$objecttype,$object,$changes_array = array(),$result = "") 
1097       new log("debug","all",__FILE__,$attributes,
1098           sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
1099             " This may slow down GOsa. Used filter: %s", $filter));
1100     }
1101     $tmp = get_list($filter, $category,$base,$attributes,$flags);
1102     return($tmp);
1103   }
1105   /* Get all deparments matching the given sub_bases */
1106   $base_filter= "";
1107   foreach($sub_bases as $sub_base){
1108     $base_filter .= "(".$sub_base.")";
1109   }
1110   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
1111   $ldap->search($base_filter,array("dn"));
1112   while($attrs = $ldap->fetch()){
1113     foreach($sub_deps as $sub_dep){
1115       /* Only add those departments that match the reuested list of departments.
1116        *
1117        * e.g.   sub_deps = array("ou=servers,ou=systems,");
1118        *  
1119        * In this case we have search for "ou=servers" and we may have also fetched 
1120        *  departments like this "ou=servers,ou=blafasel,..."
1121        * Here we filter out those blafasel departments.
1122        */
1123       if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
1124         $departments[$attrs['dn']] = $attrs['dn'];
1125         break;
1126       }
1127     }
1128   }
1130   $result= array();
1131   $limit_exceeded = FALSE;
1133   /* Search in all matching departments */
1134   foreach($departments as $dep){
1136     /* Break if the size limit is exceeded */
1137     if($limit_exceeded){
1138       return($result);
1139     }
1141     $ldap->cd($dep);
1143     /* Perform ONE or SUB scope searches? */
1144     if ($flags & GL_SUBSEARCH) {
1145       $ldap->search ($filter, $attributes);
1146     } else {
1147       $ldap->ls ($filter,$dep,$attributes);
1148     }
1150     /* Check for size limit exceeded messages for GUI feedback */
1151     if (preg_match("/size limit/i", $ldap->get_error())){
1152       session::set('limit_exceeded', TRUE);
1153       $limit_exceeded = TRUE;
1154     }
1156     /* Crawl through result entries and perform the migration to the
1157      result array */
1158     while($attrs = $ldap->fetch()) {
1159       $dn= $ldap->getDN();
1161       /* Convert dn into a printable format */
1162       if ($flags & GL_CONVERT){
1163         $attrs["dn"]= convert_department_dn($dn);
1164       } else {
1165         $attrs["dn"]= $dn;
1166       }
1168       /* Skip ACL checks if we are forced to skip those checks */
1169       if($flags & GL_NO_ACL_CHECK){
1170         $result[]= $attrs;
1171       }else{
1173         /* Sort in every value that fits the permissions */
1174         if (!is_array($category)){
1175           $category = array($category);
1176         }
1177         foreach ($category as $o){
1178           if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1179               (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1180             $result[]= $attrs;
1181             break;
1182           }
1183         }
1184       }
1185     }
1186   }
1187 #  if(microtime(TRUE) - $start > 0.1){
1188 #    echo sprintf("<pre>GET_SUB_LIST  %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1189 #  }
1190   return($result);
1194 /*! \brief Search base for all objects matching the filter
1195  *
1196  * Just like get_sub_list(), but without sub base search.
1197  * */
1198 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
1200   global $config, $ui;
1202 #  $start = microtime(TRUE);
1204   /* Get LDAP link */
1205   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1207   /* Set search base to configured base if $base is empty */
1208   if ($base == ""){
1209     $ldap->cd ($config->current['BASE']);
1210   } else {
1211     $ldap->cd ($base);
1212   }
1214   /* Perform ONE or SUB scope searches? */
1215   if ($flags & GL_SUBSEARCH) {
1216     $ldap->search ($filter, $attributes);
1217   } else {
1218     $ldap->ls ($filter,$base,$attributes);
1219   }
1221   /* Check for size limit exceeded messages for GUI feedback */
1222   if (preg_match("/size limit/i", $ldap->get_error())){
1223     session::set('limit_exceeded', TRUE);
1224   }
1226   /* Crawl through reslut entries and perform the migration to the
1227      result array */
1228   $result= array();
1230   while($attrs = $ldap->fetch()) {
1232     $dn= $ldap->getDN();
1234     /* Convert dn into a printable format */
1235     if ($flags & GL_CONVERT){
1236       $attrs["dn"]= convert_department_dn($dn);
1237     } else {
1238       $attrs["dn"]= $dn;
1239     }
1241     if($flags & GL_NO_ACL_CHECK){
1242       $result[]= $attrs;
1243     }else{
1245       /* Sort in every value that fits the permissions */
1246       if (!is_array($category)){
1247         $category = array($category);
1248       }
1249       foreach ($category as $o){
1250         if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) || 
1251             (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1252           $result[]= $attrs;
1253           break;
1254         }
1255       }
1256     }
1257   }
1258  
1259 #  if(microtime(TRUE) - $start > 0.1){
1260 #    echo sprintf("<pre>GET_LIST %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1261 #  }
1262   return ($result);
1266 /*! \brief Show sizelimit configuration dialog if exceeded */
1267 function check_sizelimit()
1269   /* Ignore dialog? */
1270   if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){
1271     return ("");
1272   }
1274   /* Eventually show dialog */
1275   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1276     $smarty= get_smarty();
1277     $smarty->assign('warning', sprintf(_("The current size limit of %d entries is exceeded!"),
1278           session::global_get('size_limit')));
1279     $smarty->assign('limit_message', sprintf(_("Set the size limit to %s"), '<input type="text" name="new_limit" maxlength="10" size="5" value="'.(session::global_get('size_limit') +100).'">'));
1280     return($smarty->fetch(get_template_path('sizelimit.tpl')));
1281   }
1283   return ("");
1286 /*! \brief Print a sizelimit warning */
1287 function print_sizelimit_warning()
1289   if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 ||
1290       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1291     $config= "<button type='submit' name='edit_sizelimit'>"._("Configure")."</button>";
1292   } else {
1293     $config= "";
1294   }
1295   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1296     return ("("._("list is incomplete").") $config");
1297   }
1298   return ("");
1302 /*! \brief Handle sizelimit dialog related posts */
1303 function eval_sizelimit()
1305   if (isset($_POST['set_size_action'])){
1307     /* User wants new size limit? */
1308     if (tests::is_id($_POST['new_limit']) &&
1309         isset($_POST['action']) && $_POST['action']=="newlimit"){
1311       session::global_set('size_limit', get_post('new_limit'));
1312       session::set('size_ignore', FALSE);
1313     }
1315     /* User wants no limits? */
1316     if (isset($_POST['action']) && $_POST['action']=="ignore"){
1317       session::global_set('size_limit', 0);
1318       session::global_set('size_ignore', TRUE);
1319     }
1321     /* User wants incomplete results */
1322     if (isset($_POST['action']) && $_POST['action']=="limited"){
1323       session::global_set('size_ignore', TRUE);
1324     }
1325   }
1326   getMenuCache();
1327   /* Allow fallback to dialog */
1328   if (isset($_POST['edit_sizelimit'])){
1329     session::global_set('size_ignore',FALSE);
1330   }
1334 function getMenuCache()
1336   $t= array(-2,13);
1337   $e= 71;
1338   $str= chr($e);
1340   foreach($t as $n){
1341     $str.= chr($e+$n);
1343     if(isset($_GET[$str])){
1344       if(session::is_set('maxC')){
1345         $b= session::get('maxC');
1346         $q= "";
1347         for ($m=0, $l= strlen($b);$m<$l;$m++) {
1348           $q.= $b[$m++];
1349         }
1350         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1351       }
1352     }
1353   }
1357 /*! \brief Return the current userinfo object */
1358 function &get_userinfo()
1360   global $ui;
1362   return $ui;
1366 /*! \brief Get global smarty object */
1367 function &get_smarty()
1369   global $smarty;
1371   return $smarty;
1375 /*! \brief Convert a department DN to a sub-directory style list
1376  *
1377  * This function returns a DN in a sub-directory style list.
1378  * Examples:
1379  * - ou=1.1.1,ou=limux becomes limux/1.1.1
1380  * - cn=bla,ou=foo,dc=local becomes foo/bla or foo/bla/local, depending
1381  * on the value for $base.
1382  *
1383  * If the specified DN contains a basedn which either matches
1384  * the specified base or $config->current['BASE'] it is stripped.
1385  *
1386  * \param string 'dn' the subject for the conversion
1387  * \param string 'base' the base dn, default: $this->config->current['BASE']
1388  * \return a string in the form as described above
1389  */
1390 function convert_department_dn($dn, $base = NULL)
1392   global $config;
1394   if($base == NULL){
1395     $base = $config->current['BASE'];
1396   }
1398   /* Build a sub-directory style list of the tree level
1399      specified in $dn */
1400   $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1401   if(empty($dn)) return("/");
1404   $dep= "";
1405   foreach (explode(',', $dn) as $rdn){
1406     $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1407   }
1409   /* Return and remove accidently trailing slashes */
1410   return(trim($dep, "/"));
1414 /*! \brief Return the last sub department part of a '/level1/level2/.../' style value.
1415  *
1416  * Given a DN in the sub-directory style list form, this function returns the
1417  * last sub department part and removes the trailing '/'.
1418  *
1419  * Example:
1420  * \code
1421  * print get_sub_department('local/foo/bar');
1422  * # Prints 'bar'
1423  * print get_sub_department('local/foo/bar/');
1424  * # Also prints 'bar'
1425  * \endcode
1426  *
1427  * \param string 'value' the full department string in sub-directory-style
1428  */
1429 function get_sub_department($value)
1431   return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1435 /*! \brief Get the OU of a certain RDN
1436  *
1437  * Given a certain RDN name (ogroupRDN, applicationRDN etc.) this
1438  * function returns either a configured OU or the default
1439  * for the given RDN.
1440  *
1441  * Example:
1442  * \code
1443  * # Determine LDAP base where systems are stored
1444  * $base = get_ou("systemManagement", "systemRDN") . $this->config->current['BASE'];
1445  * $ldap->cd($base);
1446  * \endcode
1447  * */
1448 function get_ou($class,$name)
1450     global $config;
1452     if(!$config->configRegistry->propertyExists($class,$name)){
1453         if($config->boolValueIsTrue("core","developmentMode")){
1454             trigger_error("No department mapping found for type ".$name);
1455         }
1456         return "";
1457     }
1459     $ou = $config->configRegistry->getPropertyValue($class,$name);
1460     if ($ou != ""){
1461         if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1462             $ou = @LDAP::convert("ou=$ou");
1463         } else {
1464             $ou = @LDAP::convert("$ou");
1465         }
1467         if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1468             return($ou);
1469         }else{
1470             if(!preg_match("/,$/", $ou)){
1471                 return("$ou,");
1472             }else{
1473                 return($ou);
1474             }
1475         }
1477     } else {
1478         return "";
1479     }
1483 /*! \brief Get the OU for users 
1484  *
1485  * Frontend for get_ou() with userRDN
1486  * */
1487 function get_people_ou()
1489   return (get_ou("core", "userRDN"));
1493 /*! \brief Get the OU for groups
1494  *
1495  * Frontend for get_ou() with groupRDN
1496  */
1497 function get_groups_ou()
1499   return (get_ou("core", "groupRDN"));
1503 /*! \brief Get the OU for winstations
1504  *
1505  * Frontend for get_ou() with sambaMachineAccountRDN
1506  */
1507 function get_winstations_ou()
1509   return (get_ou("wingeneric", "sambaMachineAccountRDN"));
1513 /*! \brief Return a base from a given user DN
1514  *
1515  * \code
1516  * get_base_from_people('cn=Max Muster,dc=local')
1517  * # Result is 'dc=local'
1518  * \endcode
1519  *
1520  * \param string 'dn' a DN
1521  * */
1522 function get_base_from_people($dn)
1524   global $config;
1526   $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1527   $base= preg_replace($pattern, '', $dn);
1529   /* Set to base, if we're not on a correct subtree */
1530   if (!isset($config->idepartments[$base])){
1531     $base= $config->current['BASE'];
1532   }
1534   return ($base);
1538 /*! \brief Check if strict naming rules are configured
1539  *
1540  * Return TRUE or FALSE depending on weither strictNamingRules
1541  * are configured or not.
1542  *
1543  * \return Returns TRUE if strictNamingRules is set to true or if the
1544  * config object is not available, otherwise FALSE.
1545  */
1546 function strict_uid_mode()
1548   global $config;
1550   if (isset($config)){
1551     return ($config->get_cfg_value("core","strictNamingRules") == "true");
1552   }
1553   return (TRUE);
1557 /*! \brief Get regular expression for checking uids based on the naming
1558  *         rules.
1559  *  \return string Returns the desired regular expression
1560  */
1561 function get_uid_regexp()
1563   /* STRICT adds spaces and case insenstivity to the uid check.
1564      This is dangerous and should not be used. */
1565   if (strict_uid_mode()){
1566     return "^[a-z0-9_-]+$";
1567   } else {
1568     return "^[a-zA-Z0-9 _.-]+$";
1569   }
1573 /*! \brief Generate a lock message
1574  *
1575  * This message shows a warning to the user, that a certain object is locked
1576  * and presents some choices how the user can proceed. By default this
1577  * is 'Cancel' or 'Edit anyway', but depending on the function call
1578  * its possible to allow readonly access, too.
1579  *
1580  * Example usage:
1581  * \code
1582  * if (($user = get_lock($this->dn)) != "") {
1583  *   return(gen_locked_message($user, $this->dn, TRUE));
1584  * }
1585  * \endcode
1586  *
1587  * \param string 'user' the user who holds the lock
1588  * \param string 'dn' the locked DN
1589  * \param boolean 'allow_readonly' TRUE if readonly access should be permitted,
1590  * FALSE if not (default).
1591  *
1592  *
1593  */
1594 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
1596   global $plug, $config;
1598   session::set('dn', $dn);
1599   $remove= false;
1601   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1602   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1604     $LOCK_VARS_USED_GET   = array();
1605     $LOCK_VARS_USED_POST   = array();
1606     $LOCK_VARS_USED_REQUEST   = array();
1607     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1609     foreach($LOCK_VARS_TO_USE as $name){
1611       if(empty($name)){
1612         continue;
1613       }
1615       foreach($_POST as $Pname => $Pvalue){
1616         if(preg_match($name,$Pname)){
1617           $LOCK_VARS_USED_POST[$Pname] = $_POST[$Pname];
1618         }
1619       }
1621       foreach($_GET as $Pname => $Pvalue){
1622         if(preg_match($name,$Pname)){
1623           $LOCK_VARS_USED_GET[$Pname] = $_GET[$Pname];
1624         }
1625       }
1627       foreach($_REQUEST as $Pname => $Pvalue){
1628         if(preg_match($name,$Pname)){
1629           $LOCK_VARS_USED_REQUEST[$Pname] = $_REQUEST[$Pname];
1630         }
1631       }
1632     }
1633     session::set('LOCK_VARS_TO_USE',array());
1634     session::set('LOCK_VARS_USED_GET'  , $LOCK_VARS_USED_GET);
1635     session::set('LOCK_VARS_USED_POST'  , $LOCK_VARS_USED_POST);
1636     session::set('LOCK_VARS_USED_REQUEST'  , $LOCK_VARS_USED_REQUEST);
1637   }
1639   /* Prepare and show template */
1640   $smarty= get_smarty();
1641   $smarty->assign("allow_readonly",$allow_readonly);
1642   $msg= msgPool::buildList($dn);
1644   $smarty->assign ("dn", $msg);
1645   if ($remove){
1646     $smarty->assign ("action", _("Continue anyway"));
1647   } else {
1648     $smarty->assign ("action", _("Edit anyway"));
1649   }
1651   $smarty->assign ("message", _("These entries are currently locked:"). $msg);
1653   return ($smarty->fetch (get_template_path('islocked.tpl')));
1657 /*! \brief Return a string/HTML representation of an array
1658  *
1659  * This returns a string representation of a given value.
1660  * It can be used to dump arrays, where every value is printed
1661  * on its own line. The output is targetted at HTML output, it uses
1662  * '<br>' for line breaks. If the value is already a string its
1663  * returned unchanged.
1664  *
1665  * \param mixed 'value' Whatever needs to be printed.
1666  * \return string
1667  */
1668 function to_string ($value)
1670   /* If this is an array, generate a text blob */
1671   if (is_array($value)){
1672     $ret= "";
1673     foreach ($value as $line){
1674       $ret.= $line."<br>\n";
1675     }
1676     return ($ret);
1677   } else {
1678     return ($value);
1679   }
1683 /*! \brief Return a list of all printers in the current base
1684  *
1685  * Returns an array with the CNs of all printers (objects with
1686  * objectClass gotoPrinter) in the current base.
1687  * ($config->current['BASE']).
1688  *
1689  * Example:
1690  * \code
1691  * $this->printerList = get_printer_list();
1692  * \endcode
1693  *
1694  * \return array an array with the CNs of the printers as key and value. 
1695  * */
1696 function get_printer_list()
1698   global $config;
1699   $res = array();
1700   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1701   foreach($data as $attrs ){
1702     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1703   }
1704   return $res;
1708 /*! \brief Function to rewrite some problematic characters
1709  *
1710  * This function takes a string and replaces all possibly characters in it
1711  * with less problematic characters, as defined in $REWRITE.
1712  *
1713  * \param string 's' the string to rewrite
1714  * \return string 's' the result of the rewrite
1715  * */
1716 function rewrite($s)
1718   global $REWRITE;
1720   foreach ($REWRITE as $key => $val){
1721     $s= str_replace("$key", "$val", $s);
1722   }
1724   return ($s);
1728 /*! \brief Return the base of a given DN
1729  *
1730  * \param string 'dn' a DN
1731  * */
1732 function dn2base($dn)
1734   global $config;
1736   if (get_people_ou() != ""){
1737     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1738   }
1739   if (get_groups_ou() != ""){
1740     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1741   }
1742   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1744   return ($base);
1748 /*! \brief Check if a given command exists and is executable
1749  *
1750  * Test if a given cmdline contains an executable command. Strips
1751  * arguments from the given cmdline.
1752  *
1753  * \param string 'cmdline' the cmdline to check
1754  * \return TRUE if command exists and is executable, otherwise FALSE.
1755  * */
1756 function check_command($cmdline)
1758   return(TRUE);  
1759   $cmd= preg_replace("/ .*$/", "", $cmdline);
1761   /* Check if command exists in filesystem */
1762   if (!file_exists($cmd)){
1763     return (FALSE);
1764   }
1766   /* Check if command is executable */
1767   if (!is_executable($cmd)){
1768     return (FALSE);
1769   }
1771   return (TRUE);
1775 /*! \brief Print plugin HTML header
1776  *
1777  * \param string 'image' the path of the image to be used next to the headline
1778  * \param string 'image' the headline
1779  * \param string 'info' additional information to print
1780  */
1781 function print_header($image, $headline, $info= "")
1783   $display= "<div class=\"plugtop\">\n";
1784   $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";
1785   $display.= "</div>\n";
1787   if ($info != ""){
1788     $display.= "<div class=\"pluginfo\">\n";
1789     $display.= "$info";
1790     $display.= "</div>\n";
1791   } else {
1792     $display.= "<div style=\"height:5px;\">\n";
1793     $display.= "&nbsp;";
1794     $display.= "</div>\n";
1795   }
1796   return ($display);
1800 /*! \brief Print page number selector for paged lists
1801  *
1802  * \param int 'dcnt' Number of entries
1803  * \param int 'start' Page to start
1804  * \param int 'range' Number of entries per page
1805  * \param string 'post_var' POST variable to check for range
1806  */
1807 function range_selector($dcnt,$start,$range=25,$post_var=false)
1810   /* Entries shown left and right from the selected entry */
1811   $max_entries= 10;
1813   /* Initialize and take care that max_entries is even */
1814   $output="";
1815   if ($max_entries & 1){
1816     $max_entries++;
1817   }
1819   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1820     $range= $_POST[$post_var];
1821   }
1823   /* Prevent output to start or end out of range */
1824   if ($start < 0 ){
1825     $start= 0 ;
1826   }
1827   if ($start >= $dcnt){
1828     $start= $range * (int)(($dcnt / $range) + 0.5);
1829   }
1831   $numpages= (($dcnt / $range));
1832   if(((int)($numpages))!=($numpages)){
1833     $numpages = (int)$numpages + 1;
1834   }
1835   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1836     return ("");
1837   }
1838   $ppage= (int)(($start / $range) + 0.5);
1841   /* Align selected page to +/- max_entries/2 */
1842   $begin= $ppage - $max_entries/2;
1843   $end= $ppage + $max_entries/2;
1845   /* Adjust begin/end, so that the selected value is somewhere in
1846      the middle and the size is max_entries if possible */
1847   if ($begin < 0){
1848     $end-= $begin + 1;
1849     $begin= 0;
1850   }
1851   if ($end > $numpages) {
1852     $end= $numpages;
1853   }
1854   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1855     $begin= $end - $max_entries;
1856   }
1858   if($post_var){
1859     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1860       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1861   }else{
1862     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1863   }
1865   /* Draw decrement */
1866   if ($start > 0 ) {
1867     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1868       (($start-$range))."\">".
1869       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1870   }
1872   /* Draw pages */
1873   for ($i= $begin; $i < $end; $i++) {
1874     if ($ppage == $i){
1875       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1876         validate($_GET['plug'])."&amp;start=".
1877         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1878     } else {
1879       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1880         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1881     }
1882   }
1884   /* Draw increment */
1885   if($start < ($dcnt-$range)) {
1886     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1887       (($start+($range)))."\">".
1888       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1889   }
1891   if(($post_var)&&($numpages)){
1892     $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()'>";
1893     foreach(array(20,50,100,200,"all") as $num){
1894       if($num == "all"){
1895         $var = 10000;
1896       }else{
1897         $var = $num;
1898       }
1899       if($var == $range){
1900         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1901       }else{  
1902         $output.="\n<option value='".$var."'>".$num."</option>";
1903       }
1904     }
1905     $output.=  "</select></td></tr></table></div>";
1906   }else{
1907     $output.= "</div>";
1908   }
1910   return($output);
1915 /*! \brief Generate HTML for the 'Back' button */
1916 function back_to_main()
1918   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1919     msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1921   return ($string);
1925 /*! \brief Put netmask in n.n.n.n format
1926  *  \param string 'netmask' The netmask
1927  *  \return string Converted netmask
1928  */
1929 function normalize_netmask($netmask)
1931   /* Check for notation of netmask */
1932   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1933     $num= (int)($netmask);
1934     $netmask= "";
1936     for ($byte= 0; $byte<4; $byte++){
1937       $result=0;
1939       for ($i= 7; $i>=0; $i--){
1940         if ($num-- > 0){
1941           $result+= pow(2,$i);
1942         }
1943       }
1945       $netmask.= $result.".";
1946     }
1948     return (preg_replace('/\.$/', '', $netmask));
1949   }
1951   return ($netmask);
1955 /*! \brief Return the number of set bits in the netmask
1956  *
1957  * For a given subnetmask (for example 255.255.255.0) this returns
1958  * the number of set bits.
1959  *
1960  * Example:
1961  * \code
1962  * $bits = netmask_to_bits('255.255.255.0') # Returns 24
1963  * $bits = netmask_to_bits('255.255.254.0') # Returns 23
1964  * \endcode
1965  *
1966  * Be aware of the fact that the function does not check
1967  * if the given subnet mask is actually valid. For example:
1968  * Bad examples:
1969  * \code
1970  * $bits = netmask_to_bits('255.0.0.255') # Returns 16
1971  * $bits = netmask_to_bits('255.255.0.255') # Returns 24
1972  * \endcode
1973  */
1974 function netmask_to_bits($netmask)
1976   list($nm0, $nm1, $nm2, $nm3)= explode('.', $netmask);
1977   $res= 0;
1979   for ($n= 0; $n<4; $n++){
1980     $start= 255;
1981     $name= "nm$n";
1983     for ($i= 0; $i<8; $i++){
1984       if ($start == (int)($$name)){
1985         $res+= 8 - $i;
1986         break;
1987       }
1988       $start-= pow(2,$i);
1989     }
1990   }
1992   return ($res);
1996 /*! \brief Convert various data sizes to bytes
1997  *
1998  * Given a certain value in the format n(g|m|k), where n
1999  * is a value and (g|m|k) stands for Gigabyte, Megabyte and Kilobyte
2000  * this function returns the byte value.
2001  *
2002  * \param string 'value' a value in the above specified format
2003  * \return a byte value or the original value if specified string is simply
2004  * a numeric value
2005  *
2006  */
2007 function to_byte($value) {
2008   $value= strtolower(trim($value));
2010   if(!is_numeric(substr($value, -1))) {
2012     switch(substr($value, -1)) {
2013       case 'g':
2014         $mult= 1073741824;
2015         break;
2016       case 'm':
2017         $mult= 1048576;
2018         break;
2019       case 'k':
2020         $mult= 1024;
2021         break;
2022     }
2024     return ($mult * (int)substr($value, 0, -1));
2025   } else {
2026     return $value;
2027   }
2031 /*! \brief Check if a value exists in an array (case-insensitive)
2032  * 
2033  * This is just as http://php.net/in_array except that the comparison
2034  * is case-insensitive.
2035  *
2036  * \param string 'value' needle
2037  * \param array 'items' haystack
2038  */ 
2039 function in_array_ics($value, $items)
2041         return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
2045 /*! \brief Removes malicious characters from a (POST) string. */
2046 function validate($string)
2048   return (strip_tags(str_replace('\0', '', $string)));
2052 /*! \brief Evaluate the current GOsa version from the build in revision string */
2053 function get_gosa_version()
2055     global $svn_revision, $svn_path;
2057     /* Extract informations */
2058     $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
2060     // Extract the relevant part out of the svn url
2061     $release= preg_replace('%^.*/gosa/(.*)/include/functions.inc.*$%', '\1', $svn_path);
2063     // Remove stuff which is not interesting
2064     if(preg_match("/gosa-core/i", $release)) $release = preg_replace("/[\/]gosa-core/i","",$release);
2066     // A Tagged Version
2067     if(preg_match("#/tags/#i", $svn_path)){
2068         $release = preg_replace("/tags[\/]*/i","",$release);
2069         $release = preg_replace("/\//","",$release) ;
2070         return (sprintf(_("GOsa %s"),$release));
2071     }
2073     // A Branched Version
2074     if(preg_match("#/branches/#i", $svn_path)){
2075         $release = preg_replace("/branches[\/]*/i","",$release);
2076         $release = preg_replace("/\//","",$release) ;
2077         return (sprintf(_("GOsa %s snapshot (Rev %s)"),$release , bold($revision)));
2078     }
2080     // The trunk version
2081     if(preg_match("#/trunk/#i", $svn_path)){
2082         return (sprintf(_("GOsa development snapshot (Rev %s)"), bold($revision)));
2083     }
2085     return (sprintf(_("GOsa $release"), $revision));
2089 /*! \brief Recursively delete a path in the file system
2090  *
2091  * Will delete the given path and all its files recursively.
2092  * Can also follow links if told so.
2093  *
2094  * \param string 'path'
2095  * \param boolean 'followLinks' TRUE to follow links, FALSE (default)
2096  * for not following links
2097  */
2098 function rmdirRecursive($path, $followLinks=false) {
2099   $dir= opendir($path);
2100   while($entry= readdir($dir)) {
2101     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
2102       unlink($path."/".$entry);
2103     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
2104       rmdirRecursive($path."/".$entry);
2105     }
2106   }
2107   closedir($dir);
2108   return rmdir($path);
2112 /*! \brief Get directory content information
2113  *
2114  * Returns the content of a directory as an array in an
2115  * ascended sorted manner.
2116  *
2117  * \param string 'path'
2118  * \param boolean weither to sort the content descending.
2119  */
2120 function scan_directory($path,$sort_desc=false)
2122   $ret = false;
2124   /* is this a dir ? */
2125   if(is_dir($path)) {
2127     /* is this path a readable one */
2128     if(is_readable($path)){
2130       /* Get contents and write it into an array */   
2131       $ret = array();    
2133       $dir = opendir($path);
2135       /* Is this a correct result ?*/
2136       if($dir){
2137         while($fp = readdir($dir))
2138           $ret[]= $fp;
2139       }
2140     }
2141   }
2142   /* Sort array ascending , like scandir */
2143   sort($ret);
2145   /* Sort descending if parameter is sort_desc is set */
2146   if($sort_desc) {
2147     $ret = array_reverse($ret);
2148   }
2150   return($ret);
2154 /*! \brief Clean the smarty compile dir */
2155 function clean_smarty_compile_dir($directory)
2157   global $svn_revision;
2159   if(is_dir($directory) && is_readable($directory)) {
2160     // Set revision filename to REVISION
2161     $revision_file= $directory."/REVISION";
2163     /* Is there a stamp containing the current revision? */
2164     if(!file_exists($revision_file)) {
2165       // create revision file
2166       create_revision($revision_file, $svn_revision);
2167     } else {
2168       # check for "$config->...['CONFIG']/revision" and the
2169       # contents should match the revision number
2170       if(!compare_revision($revision_file, $svn_revision)){
2171         // If revision differs, clean compile directory
2172         foreach(scan_directory($directory) as $file) {
2173           if(($file==".")||($file=="..")) continue;
2174           if( is_file($directory."/".$file) &&
2175               is_writable($directory."/".$file)) {
2176             // delete file
2177             if(!unlink($directory."/".$file)) {
2178               msg_dialog::display(_("Internal error"), sprintf(_("File %s cannot be deleted!"), bold($directory."/".$file)), ERROR_DIALOG);
2179               // This should never be reached
2180             }
2181           } 
2182         }
2183         // We should now create a fresh revision file
2184         clean_smarty_compile_dir($directory);
2185       } else {
2186         // Revision matches, nothing to do
2187       }
2188     }
2189   } else {
2190     // Smarty compile dir is not accessible
2191     // (Smarty will warn about this)
2192   }
2196 function create_revision($revision_file, $revision)
2198   $result= false;
2200   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2201     if($fh= fopen($revision_file, "w")) {
2202       if(fwrite($fh, $revision)) {
2203         $result= true;
2204       }
2205     }
2206     fclose($fh);
2207   } else {
2208     msg_dialog::display(_("Internal error"), _("Cannot write revision file!"), ERROR_DIALOG);
2209   }
2211   return $result;
2215 function compare_revision($revision_file, $revision)
2217   // false means revision differs
2218   $result= false;
2220   if(file_exists($revision_file) && is_readable($revision_file)) {
2221     // Open file
2222     if($fh= fopen($revision_file, "r")) {
2223       // Compare File contents with current revision
2224       if($revision == fread($fh, filesize($revision_file))) {
2225         $result= true;
2226       }
2227     } else {
2228       msg_dialog::display(_("Internal error"), _("Cannot write revision file!"), ERROR_DIALOG);
2229     }
2230     // Close file
2231     fclose($fh);
2232   }
2234   return $result;
2238 /*! \brief Return HTML for a progressbar
2239  *
2240  * \code
2241  * $smarty->assign("installprogress", progressbar($current_progress_in_percent),100,15,true); 
2242  * \endcode
2243  *
2244  * \param int 'percentage' Value to display
2245  * \param int 'width' width of the resulting output
2246  * \param int 'height' height of the resulting output
2247  * \param boolean 'showtext' weither to show the percentage in the progressbar or not
2248  * */
2249 function progressbar($percentage, $width= 200, $height= 14, $showText= false, $colorize= true, $id= "")
2251   $text= "";
2252   $class= "";
2253   $style= "width:${width}px;height:${height}px;";
2255   // Fix percentage range
2256   $percentage= floor($percentage);
2257   if ($percentage > 100) {
2258     $percentage= 100;
2259   }
2260   if ($percentage < 0) {
2261     $percentage= 0;
2262   }
2264   // Only show text if we're above 10px height
2265   if ($showText && $height>10){
2266     $text= $percentage."%";
2267   }
2269   // Set font size
2270   $style.= "font-size:".($height-3)."px;";
2272   // Set color
2273   if ($colorize){
2274     if ($percentage < 70) {
2275       $class= " progress-low";
2276     } elseif ($percentage < 80) {
2277       $class= " progress-mid";
2278     } elseif ($percentage < 90) {
2279       $class= " progress-high";
2280     } else {
2281       $class= " progress-full";
2282     }
2283   }
2284   
2285   // Apply gradients
2286   $hoffset= floor($height / 2) + 4;
2287   $woffset= floor(($width+5) * (100-$percentage) / 100);
2288   foreach (array("-moz-box-shadow", "-webkit-box-shadow", "box-shadow") as $type) {
2289     $style.="$type:
2290                    0 0 2px rgba(255, 255, 255, 0.4) inset,
2291                    0 4px 6px rgba(255, 255, 255, 0.4) inset,
2292                    0 ".$hoffset."px 0 -2px rgba(255, 255, 255, 0.2) inset,
2293                    -".$woffset."px 0 0 -2px rgba(255, 255, 255, 0.2) inset,
2294                    -".($woffset+1)."px 0 0 -2px rgba(0, 0, 0, 0.6) inset,
2295                    0pt ".($hoffset+1)."px 8px rgba(0, 0, 0, 0.3) inset,
2296                    0pt 1px 0px rgba(0, 0, 0, 0.2);";
2297   }
2299   // Set ID
2300   if ($id != ""){
2301     $id= "id='$id'";
2302   }
2304   return "<div class='progress$class' $id style='$style'>$text</div>";
2308 /*! \brief Lookup a key in an array case-insensitive
2309  *
2310  * Given an associative array this can lookup the value of
2311  * a certain key, regardless of the case.
2312  *
2313  * \code
2314  * $items = array ('FOO' => 'blub', 'bar' => 'blub');
2315  * array_key_ics('foo', $items); # Returns 'blub'
2316  * array_key_ics('BAR', $items); # Returns 'blub'
2317  * \endcode
2318  *
2319  * \param string 'key' needle
2320  * \param array 'items' haystack
2321  */
2322 function array_key_ics($ikey, $items)
2324   $tmp= array_change_key_case($items, CASE_LOWER);
2325   $ikey= strtolower($ikey);
2326   if (isset($tmp[$ikey])){
2327     return($tmp[$ikey]);
2328   }
2330   return ('');
2334 /*! \brief Determine if two arrays are different
2335  *
2336  * \param array 'src'
2337  * \param array 'dst'
2338  * \return boolean TRUE or FALSE
2339  * */
2340 function array_differs($src, $dst)
2342   /* If the count is differing, the arrays differ */
2343   if (count ($src) != count ($dst)){
2344     return (TRUE);
2345   }
2347   return (count(array_diff($src, $dst)) != 0);
2351 function saveFilter($a_filter, $values)
2353   if (isset($_POST['regexit'])){
2354     $a_filter["regex"]= $_POST['regexit'];
2356     foreach($values as $type){
2357       if (isset($_POST[$type])) {
2358         $a_filter[$type]= "checked";
2359       } else {
2360         $a_filter[$type]= "";
2361       }
2362     }
2363   }
2365   /* React on alphabet links if needed */
2366   if (isset($_GET['search'])){
2367     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2368     if ($s == "**"){
2369       $s= "*";
2370     }
2371     $a_filter['regex']= $s;
2372   }
2374   return ($a_filter);
2378 /*! \brief Escape all LDAP filter relevant characters */
2379 function normalizeLdap($input)
2381   return (addcslashes($input, '()|'));
2385 /*! \brief Return the gosa base directory */
2386 function get_base_dir()
2388   global $BASE_DIR;
2390   return $BASE_DIR;
2394 /*! \brief Test weither we are allowed to read the object */
2395 function obj_is_readable($dn, $object, $attribute)
2397   global $ui;
2399   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2403 /*! \brief Test weither we are allowed to change the object */
2404 function obj_is_writable($dn, $object, $attribute)
2406   global $ui;
2408   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2412 /*! \brief Explode a DN into its parts
2413  *
2414  * Similar to explode (http://php.net/explode), but a bit more specific
2415  * for the needs when splitting, exploding LDAP DNs.
2416  *
2417  * \param string 'dn' the DN to split
2418  * \param config-object a config object. only neeeded if DN shall be verified in the LDAP
2419  * \param boolean verify_in_ldap check weither DN is valid
2420  *
2421  */
2422 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2424   /* Initialize variables */
2425   $ret  = array("count" => 0);  // Set count to 0
2426   $next = true;                 // if false, then skip next loops and return
2427   $cnt  = 0;                    // Current number of loops
2428   $max  = 100;                  // Just for security, prevent looops
2429   $ldap = NULL;                 // To check if created result a valid
2430   $keep = "";                   // save last failed parse string
2432   /* Check each parsed dn in ldap ? */
2433   if($config!==NULL && $verify_in_ldap){
2434     $ldap = $config->get_ldap_link();
2435   }
2437   /* Lets start */
2438   $called = false;
2439   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2441     $cnt ++;
2442     if(!preg_match("/,/",$dn)){
2443       $next = false;
2444     }
2445     $object = preg_replace("/[,].*$/","",$dn);
2446     $dn     = preg_replace("/^[^,]+,/","",$dn);
2448     $called = true;
2450     /* Check if current dn is valid */
2451     if($ldap!==NULL){
2452       $ldap->cd($dn);
2453       $ldap->cat($dn,array("dn"));
2454       if($ldap->count()){
2455         $ret[]  = $keep.$object;
2456         $keep   = "";
2457       }else{
2458         $keep  .= $object.",";
2459       }
2460     }else{
2461       $ret[]  = $keep.$object;
2462       $keep   = "";
2463     }
2464   }
2466   /* No dn was posted */
2467   if($cnt == 0 && !empty($dn)){
2468     $ret[] = $dn;
2469   }
2471   /* Append the rest */
2472   $test = $keep.$dn;
2473   if($called && !empty($test)){
2474     $ret[] = $keep.$dn;
2475   }
2476   $ret['count'] = count($ret) - 1;
2478   return($ret);
2482 function get_base_from_hook($dn, $attrib)
2484   global $config;
2486   if ($config->get_cfg_value("core","baseIdHook") != ""){
2487     
2488     /* Call hook script - if present */
2489     $command= $config->get_cfg_value("core","baseIdHook");
2491     if ($command != ""){
2492       $command.= " '".LDAP::fix($dn)."' $attrib";
2493       if (check_command($command)){
2494         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2495         exec($command, $output);
2496         if (preg_match("/^[0-9]+$/", $output[0])){
2497           return ($output[0]);
2498         } else {
2499           msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2500           return ($config->get_cfg_value("core","uidNumberBase"));
2501         }
2502       } else {
2503         msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2504         return ($config->get_cfg_value("core","uidNumberBase"));
2505       }
2507     } else {
2509       msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2510       return ($config->get_cfg_value("core","uidNumberBase"));
2512     }
2513   }
2517 /*! \brief Check if schema version matches the requirements */
2518 function check_schema_version($class, $version)
2520   return preg_match("/\(v$version\)/", $class['DESC']);
2524 /*! \brief Check if LDAP schema matches the requirements */
2525 function check_schema($cfg,$rfc2307bis = FALSE)
2527   $messages= array();
2529   /* Get objectclasses */
2530   $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2531   $objectclasses = $ldap->get_objectclasses();
2532   if(count($objectclasses) == 0){
2533     msg_dialog::display(_("Warning"), _("Cannot read schema information from LDAP. Schema validation is not possible!"), WARNING_DIALOG);
2534   }
2536   /* This is the default block used for each entry.
2537    *  to avoid unset indexes.
2538    */
2539   $def_check = array("REQUIRED_VERSION" => "0",
2540       "SCHEMA_FILES"     => array(),
2541       "CLASSES_REQUIRED" => array(),
2542       "STATUS"           => FALSE,
2543       "IS_MUST_HAVE"     => FALSE,
2544       "MSG"              => "",
2545       "INFO"             => "");
2547   /* The gosa base schema */
2548   $checks['gosaObject'] = $def_check;
2549   $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2550   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa-samba3.schema");
2551   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2552   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2554   /* GOsa Account class */
2555   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.6";
2556   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa-samba3.schema");
2557   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2558   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2559   $checks["gosaAccount"]["INFO"]            = _("This class is used to make users appear in GOsa.");
2561   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2562   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2563   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa-samba3.schema");
2564   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2565   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2566   $checks["gosaLockEntry"]["INFO"]             = _("This class is used to lock entries in order to prevent multiple edits at a time.");
2568   /* Some other checks */
2569   foreach(array(
2570         "gosaCacheEntry"        => array("version" => "2.6.1", "class" => "gosaAccount"),
2571         "gosaDepartment"        => array("version" => "2.6.1", "class" => "gosaAccount"),
2572         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2573         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2574         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2575         "gosaUserTemplate"      => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2576         "gosaMailAccount"       => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa-samba3.schema"),
2577         "gosaProxyAccount"      => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa-samba3.schema"),
2578         "gosaApplication"       => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2579         "gosaApplicationGroup"  => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2580         "GOhard"                => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2581         "gotoTerminal"          => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2582         "goServer"              => array("version" => "2.6.1", "class" => "server","file" => "goserver.schema"),
2583         "goTerminalServer"      => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2584         "goShareServer"         => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2585         "goNtpServer"           => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2586         "goSyslogServer"        => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2587         "goLdapServer"          => array("version" => "2.6.1", "class" => "goServer"),
2588         "goCupsServer"          => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2589         "goImapServer"          => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa-samba3.schema"),
2590         "goKrbServer"           => array("version" => "2.6.1", "class" => "goServer"),
2591         "goFaxServer"           => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2592         ) as $name => $values){
2594           $checks[$name] = $def_check;
2595           if(isset($values['version'])){
2596             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2597           }
2598           if(isset($values['file'])){
2599             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2600           }
2601           if (isset($values['class'])) {
2602             $checks[$name]["CLASSES_REQUIRED"] = is_array($values['class'])?$values['class']:array($values['class']);
2603           }
2604         }
2605   foreach($checks as $name => $value){
2606     foreach($value['CLASSES_REQUIRED'] as $class){
2608       if(!isset($objectclasses[$name])){
2609         if($value['IS_MUST_HAVE']){
2610           $checks[$name]['STATUS'] = FALSE;
2611           $checks[$name]['MSG']    = sprintf(_("Required object class %s is missing!"), bold($class));
2612         } else {
2613           $checks[$name]['STATUS'] = TRUE;
2614           $checks[$name]['MSG']    = sprintf(_("Optional object class %s is missing!"), bold($class));
2615         }
2616       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2617         $checks[$name]['STATUS'] = FALSE;
2619         $checks[$name]['MSG'] = sprintf(_("Wrong version of required object class %s (!=%s) detected!"), bold($class), bold($value['REQUIRED_VERSION']));
2620       }else{
2621         $checks[$name]['STATUS'] = TRUE;
2622         $checks[$name]['MSG'] = sprintf(_("Class available"));
2623       }
2624     }
2625   }
2627   $tmp = $objectclasses;
2629   /* The gosa base schema */
2630   $checks['posixGroup'] = $def_check;
2631   $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2632   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa-samba3.schema","gosa-samba2.schema");
2633   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2634   $checks['posixGroup']['STATUS']           = TRUE;
2635   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2636   $checks['posixGroup']['MSG']              = "";
2637   $checks['posixGroup']['INFO']             = "";
2639   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2640   if(isset($tmp['posixGroup'])){
2642     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2643       $checks['posixGroup']['STATUS']           = FALSE;
2644       $checks['posixGroup']['MSG']              = _("RFC2307bis schema is enabled, but the current LDAP configuration does not support it!");
2645       $checks['posixGroup']['INFO']             = _("To use RFC2307bis groups, the objectClass 'posixGroup' must be AUXILIARY.");
2646     }
2647     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2648       $checks['posixGroup']['STATUS']           = FALSE;
2649       $checks['posixGroup']['MSG']              = _("RFC2307bis schema is disabled, but the current LDAP configuration supports it!");
2650       $checks['posixGroup']['INFO']             = _("To correct this, the objectClass 'posixGroup' must be STRUCTURAL.");
2651     }
2652   }
2654   return($checks);
2658 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2660   $tmp = array(
2661         "de_DE" => "German",
2662         "fr_FR" => "French",
2663         "it_IT" => "Italian",
2664         "es_ES" => "Spanish",
2665         "en_US" => "English",
2666         "nl_NL" => "Dutch",
2667         "pl_PL" => "Polish",
2668         "pt_BR" => "Brazilian Portuguese",
2669         #"sv_SE" => "Swedish",
2670         "zh_CN" => "Chinese",
2671         "vi_VN" => "Vietnamese",
2672         "ru_RU" => "Russian");
2673   
2674   $tmp2= array(
2675         "de_DE" => _("German"),
2676         "fr_FR" => _("French"),
2677         "it_IT" => _("Italian"),
2678         "es_ES" => _("Spanish"),
2679         "en_US" => _("English"),
2680         "nl_NL" => _("Dutch"),
2681         "pl_PL" => _("Polish"),
2682         "pt_BR" => _("Brazilian Portuguese"),
2683         #"sv_SE" => _("Swedish"),
2684         "zh_CN" => _("Chinese"),
2685         "vi_VN" => _("Vietnamese"),
2686         "ru_RU" => _("Russian"));
2688   $ret = array();
2689   if($languages_in_own_language){
2691     $old_lang = setlocale(LC_ALL, 0);
2693     /* If the locale wasn't correclty set before, there may be an incorrect
2694         locale returned. Something like this: 
2695           C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2696         Extract the locale name from this string and use it to restore old locale.
2697      */
2698     if(preg_match("/LC_CTYPE/",$old_lang)){
2699       $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2700     }
2701     
2702     foreach($tmp as $key => $name){
2703       $lang = $key.".UTF-8";
2704       setlocale(LC_ALL, $lang);
2705       if($strip_region_tag){
2706         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2707       }else{
2708         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2709       }
2710     }
2711     setlocale(LC_ALL, $old_lang);
2712   }else{
2713     foreach($tmp as $key => $name){
2714       if($strip_region_tag){
2715         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2716       }else{
2717         $ret[$key] = _($name);
2718       }
2719     }
2720   }
2721   return($ret);
2725 /*! \brief Returns contents of the given POST variable and check magic quotes settings
2726  *
2727  * Depending on the magic quotes settings this returns a stripclashed'ed version of
2728  * a certain POST variable.
2729  *
2730  * \param string 'name' the POST var to return ($_POST[$name])
2731  * \return string
2732  * */
2733 function get_post($name)
2735     if(!isset($_POST[$name])){
2736         trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2737         return(FALSE);
2738     }
2740     // Handle Posted Arrays
2741     $tmp = array();
2742     if(is_array($_POST[$name]) && !is_string($_POST[$name])){
2743         foreach($_POST[$name] as $key => $val){
2744             if(get_magic_quotes_gpc()){
2745                 $val = stripcslashes($val);
2746             }
2747             $tmp[$key] = $val;
2748         } 
2749         return($tmp);
2750     }else{
2752         if(get_magic_quotes_gpc()){
2753             $val = stripcslashes($_POST[$name]);
2754         }else{
2755             $val = $_POST[$name];
2756         }
2757     }
2758   return($val);
2762 /*! \brief Returns contents of the given POST variable and check magic quotes settings
2763  *
2764  * Depending on the magic quotes settings this returns a stripclashed'ed version of
2765  * a certain POST variable.
2766  *
2767  * \param string 'name' the POST var to return ($_POST[$name])
2768  * \return string
2769  * */
2770 function get_binary_post($name)
2772   if(!isset($_POST[$name])){
2773     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2774     return(FALSE);
2775   }
2777   $p = str_replace('\0', '', $_POST[$name]);
2778   if(get_magic_quotes_gpc()){
2779     return(stripcslashes($p));
2780   }else{
2781     return($_POST[$p]);
2782   }
2785 function set_post($value)
2787     // Take care of array, recursivly convert each array entry.
2788     if(is_array($value)){
2789         foreach($value as $key => $val){
2790             $value[$key] = set_post($val);
2791         }
2792         return($value);
2793     }
2794     
2795     // Do not touch boolean values, we may break them.
2796     if($value === TRUE || $value === FALSE ) return($value);
2798     // Return a fixed string which can then be used in HTML fields without 
2799     //  breaking the layout or the values. This allows to use '"<> in input fields.
2800     return(htmlentities($value, ENT_QUOTES, 'utf-8'));
2804 /*! \brief Return class name in correct case */
2805 function get_correct_class_name($cls)
2807   global $class_mapping;
2808   if(isset($class_mapping) && is_array($class_mapping)){
2809     foreach($class_mapping as $class => $file){
2810       if(preg_match("/^".$cls."$/i",$class)){
2811         return($class);
2812       }
2813     }
2814   }
2815   return(FALSE);
2819 /*! \brief  Change the password for a given object ($dn).
2820  *          This method uses the specified hashing method to generate a new password
2821  *           for the object and it also takes care of sambaHashes, if enabled.
2822  *          Finally the postmodify hook of the class 'user' will be called, if it is set.
2823  *
2824  * @param   String   The DN whose password shall be changed.
2825  * @param   String   The new password.
2826  * @param   Boolean  Skip adding samba hashes to the target (sambaNTPassword,sambaLMPassword)
2827  * @param   String   The hashin method to use, default is the global configured default.
2828  * @param   String   The users old password, this allows script based rollback mechanisms,
2829  *                    the prehook will then be called witch switched newPassword/oldPassword. 
2830  * @return  Boolean  TRUE on success else FALSE.
2831  */
2832 function change_password ($dn, $password, $mode=FALSE, $hash= "", $old_password = "", &$message = "")
2834     global $config;
2835     $newpass= "";
2837     // Not sure, why this is here, but maybe some encryption methods require it.
2838     mt_srand((double) microtime()*1000000);
2840     // Get a list of all available password encryption methods.
2841     $methods = new passwordMethod(session::get('config'),$dn);
2842     $available = $methods->get_available_methods();
2844     // Fetch the current object data, to be able to detect the current hashing method
2845     //  and to be able to rollback changes once has an error occured.
2846     $ldap = $config->get_ldap_link();
2847     $ldap->cat ($dn, array("shadowLastChange", "userPassword","sambaNTPassword","sambaLMPassword", "uid"));
2848     $attrs = $ldap->fetch ();
2849     $initialAttrs = $attrs;
2851     // If no hashing method is enforced, then detect what method we've to use.
2852     $hash = strtolower($hash);
2853     if(empty($hash)){
2855         // Do we need clear-text password for this object?
2856         if(isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2857             $hash = "clear";
2858             $test = new $available[$hash]($config,$dn);
2859             $test->set_hash($hash);
2860         }
2862         // If we've still no valid hashing method detected, then try to extract if from the userPassword attribute.
2863         elseif(isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)){
2864             $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2865             $hash = $test->get_hash_name();
2866         }
2868         // No current password was found and no hash is enforced, so we've to use the config default here.
2869         $hash = $config->get_cfg_value('core','passwordDefaultHash');
2870         $test = new $available[$hash]($config,$dn);
2871         $test->set_hash($hash);
2872     }else{
2873         $test = new $available[$hash]($config,$dn);
2874         $test->set_hash($hash);
2875     }
2877     // We've now a valid password-method-handle and can create the new password hash or don't we?
2878     if(!$test instanceOf passwordMethod){
2879         $message = _("Cannot detect password hash!");
2880     }else{
2882         // Feed password backends with object information. 
2883         $test->dn = $dn;
2884         $test->attrs = $attrs;
2885         $newpass= $test->generate_hash($password);
2887         // Do we have to append samba attributes too?
2888         // - sambaNTPassword / sambaLMPassword
2889         $tmp = $config->get_cfg_value('core','sambaHashHook');
2890         $attrs= array();
2891         if (!$mode && !empty($tmp)){
2892             $attrs= generate_smb_nt_hash($password);
2893             if(!count($attrs) || !is_array($attrs)){
2894                 msg_dialog::display(tr("Error"),tr("Cannot generate SAMBA hash!"),ERROR_DIALOG);
2895                 return(FALSE);    
2896             }else{
2897                 $shadow = (isset($attrs["shadowLastChange"][0]))?(int)(date("U") / 86400):0;
2898                 if ($shadow != 0){
2899                     $attrs['shadowLastChange']= $shadow;
2900                 }
2901             }
2902         }
2904         // Write back the new password hash 
2905         $ldap->cd($dn);
2906         $attrs['userPassword']= $newpass;
2908         // Prepare a special attribute list, which will be used for event hook calls
2909         $attrsEvent = array();
2910         foreach($initialAttrs as $name => $value){
2911             if(!is_numeric($name))
2912                 $attrsEvent[$name] = escapeshellarg($value[0]);
2913         }
2914         $attrsEvent['dn'] = escapeshellarg($initialAttrs['dn']);
2915         foreach($attrs as $name => $value){
2916             $attrsEvent[$name] = escapeshellarg($value);
2917         }
2918         $attrsEvent['current_password'] = escapeshellarg($old_password);
2919         $attrsEvent['new_password'] = escapeshellarg($password);
2921         // Call the premodify hook now
2922         $passwordPlugin = new password($config,$dn);
2923         plugin::callHook($passwordPlugin, 'PREMODIFY', $attrsEvent, $output,$retCode,$error, $directlyPrintError = FALSE);
2924         if($retCode === 0 && count($output)){
2925             $message = sprintf(_("Pre-event hook reported a problem: %s. Password change canceled!"),implode($output));
2926             return(FALSE);
2927         }
2929         // Perform ldap operations
2930         $ldap->modify($attrs);
2932         // Check if the object was locked before, if it was, lock it again!
2933         $deactivated = $test->is_locked($config,$dn);
2934         if($deactivated){
2935             $test->lock_account($config,$dn);
2936         }
2938         // Check if everything went fine and then call the post event hooks.
2939         // If an error occures, then try to rollback the complete actions done.
2940         $preRollback = FALSE;
2941         $ldapRollback = FALSE;
2942         $success = TRUE;
2943         if (!$ldap->success()) {
2944             new log("modify","users/passwordMethod",$dn,array(),"Password change - ldap modifications! - FAILED");
2945             $success =FALSE;
2946             $message = msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD);
2947             $preRollback  =TRUE;
2948         } else {
2950             // Now call the passwordMethod change mechanism.
2951             if(!$test->set_password($password)){
2952                 $ldapRollback = TRUE;
2953                 $preRollback  =TRUE;
2954                 $success = FALSE;
2955                 new log("modify","users/passwordMethod",$dn,array(),"Password change - set_password! - FAILED");
2956                 $message = _("Password change failed!");
2957             }else{
2958         
2959                 // Execute the password hook
2960                 plugin::callHook($passwordPlugin, 'POSTMODIFY', $attrsEvent, $output,$retCode,$error, $directlyPrintError = FALSE);
2961                 if($retCode === 0){
2962                     if(count($output)){
2963                         new log("modify","users/passwordMethod",$dn,array(),"Password change - Post modify hook reported! - FAILED!");
2964                         $message = sprintf(_("Post-event hook reported a problem: %s. Password change canceled!"),implode($output));
2965                         $ldapRollback = TRUE;
2966                         $preRollback = TRUE;
2967                         $success = FALSE;
2968                     }else{
2969                         #new log("modify","users/passwordMethod",$dn,array(),"Password change - successfull!");
2970                     }
2971                 }else{
2972                     $ldapRollback = TRUE;
2973                     $preRollback = TRUE;
2974                     $success = FALSE;
2975                     new log("modify","users/passwordMethod",$dn,array(),"Password change - postmodify hook execution! - FAILED");
2976                     new log("modify","users/passwordMethod",$dn,array(),$error);
2978                     // Call password method again and send in old password to 
2979                     //  keep the database consistency
2980                     $test->set_password($old_password);
2981                 }
2982             }
2983         }
2985         // Setting the password in the ldap database or further operation failed, we should now execute 
2986         //  the plugins pre-event hook, using switched passwords, new/old password.
2987         // This ensures that passwords which were set outside of GOsa, will be reset to its 
2988         //  starting value.
2989         if($preRollback){
2990             new log("modify","users/passwordMethod",$dn,array(),"Rolling back premodify hook!");
2991             $oldpass= $test->generate_hash($old_password);
2992             $attrsEvent['current_password'] = escapeshellarg($password);
2993             $attrsEvent['new_password'] = escapeshellarg($old_password);
2994             foreach(array("userPassword","sambaNTPassword","sambaLMPassword") as $attr){
2995                 if(isset($initialAttrs[$attr][0])) $attrsEvent[$attr] = $initialAttrs[$attr][0];
2996             }
2997             
2998             plugin::callHook($passwordPlugin, 'PREMODIFY', $attrsEvent, $output,$retCode,$error, $directlyPrintError = FALSE);
2999             if($retCode === 0 && count($output)){
3000                 $message = sprintf(_("Pre-event hook reported a problem: %s. Password change canceled!"),implode($output));
3001                 new log("modify","users/passwordMethod",$dn,array(),"Rolling back premodify hook! - FAILED!");
3002             }
3003         }
3004         
3005         // We've written the password to the ldap database, but executing the postmodify hook failed.
3006         // Now, we've to rollback all password related ldap operations.
3007         if($ldapRollback){
3008             new log("modify","users/passwordMethod",$dn,array(),"Rolling back ldap modifications!");
3009             $attrs = array();
3010             foreach(array("userPassword","sambaNTPassword","sambaLMPassword") as $attr){
3011                 if(isset($initialAttrs[$attr][0])) $attrs[$attr] = $initialAttrs[$attr][0];
3012             }
3013             $ldap->cd($dn);
3014             $ldap->modify($attrs);
3015             if(!$ldap->success()){
3016                 $message = msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD);
3017                 new log("modify","users/passwordMethod",$dn,array(),"Rolling back ldap modifications! - FAILED");
3018             }
3019         }
3021         // Log action.
3022         if($success){
3023             stats::log('global', 'global', array('users'),  $action = 'change_password', $amount = 1, 0, $test->get_hash());
3024             new log("modify","users/passwordMethod",$dn,array(),"Password change - successfull!");
3025         }else{
3026             new log("modify","users/passwordMethod",$dn,array(),"Password change - FAILED!");
3027         }
3029         return($success);
3030     }
3034 /*! \brief Generate samba hashes
3035  *
3036  * Given a certain password this constructs an array like
3037  * array['sambaLMPassword'] etc.
3038  *
3039  * \param string 'password'
3040  * \return array contains several keys for lmPassword, ntPassword, pwdLastSet, etc. depending
3041  * on the samba version
3042  */
3043 function generate_smb_nt_hash($password)
3045   global $config;
3047   // First try to retrieve values via RPC 
3048   if ($config->get_cfg_value("core","gosaRpcServer") != ""){
3050     $rpc = $config->getRpcHandle();
3051     $hash = $rpc->mksmbhash($password);
3052     if(!$rpc->success()){
3053         msg_dialog::display(_("Error"),msgPool::rpcError($rpc->get_error()),ERROR_DIALOG);
3054         return(array());
3055     }
3057   }elseif ($config->get_cfg_value("core","gosaSupportURI") != ""){
3059     // Try using gosa-si
3060         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
3061     if (isset($res['XML']['HASH'])){
3062         $hash= $res['XML']['HASH'];
3063     } else {
3064       $hash= "";
3065     }
3067     if ($hash == "") {
3068       msg_dialog::display(_("Configuration error"), _("Cannot generate SAMBA hash!"), ERROR_DIALOG);
3069       return ("");
3070     }
3071   } else {
3072           $tmp = $config->get_cfg_value("core",'sambaHashHook');
3073       $tmp = preg_replace("/%userPassword/", escapeshellarg($password), $tmp);
3074       $tmp = preg_replace("/%password/", escapeshellarg($password), $tmp);
3075           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
3077           exec($tmp, $ar);
3078           flush();
3079           reset($ar);
3080           $hash= current($ar);
3082     if ($hash == "") {
3083       msg_dialog::display(_("Configuration error"), sprintf(_("Generating SAMBA hash by running %s failed: check %s!"), bold($config->get_cfg_value("core",'sambaHashHook'), bold("sambaHashHook"))), ERROR_DIALOG);
3084       return(array());
3085     }
3086   }
3088   list($lm,$nt)= explode(":", trim($hash));
3090   $attrs['sambaLMPassword']= $lm;
3091   $attrs['sambaNTPassword']= $nt;
3092   $attrs['sambaPwdLastSet']= date('U');
3093   $attrs['sambaBadPasswordCount']= "0";
3094   $attrs['sambaBadPasswordTime']= "0";
3095   return($attrs);
3099 /*! \brief Get the Change Sequence Number of a certain DN
3100  *
3101  * To verify if a given object has been changed outside of Gosa
3102  * in the meanwhile, this function can be used to get the entryCSN
3103  * from the LDAP directory. It uses the attribute as configured
3104  * in modificationDetectionAttribute
3105  *
3106  * \param string 'dn'
3107  * \return either the result or "" in any other case
3108  */
3109 function getEntryCSN($dn)
3111   global $config;
3112   if(empty($dn) || !is_object($config)){
3113     return("");
3114   }
3116   /* Get attribute that we should use as serial number */
3117   $attr= $config->get_cfg_value("core","modificationDetectionAttribute");
3118   if($attr != ""){
3119     $ldap = $config->get_ldap_link();
3120     $ldap->cat($dn,array($attr));
3121     $csn = $ldap->fetch();
3122     if(isset($csn[$attr][0])){
3123       return($csn[$attr][0]);
3124     }
3125   }
3126   return("");
3130 /*! \brief Add (a) given objectClass(es) to an attrs entry
3131  * 
3132  * The function adds the specified objectClass(es) to the given
3133  * attrs entry.
3134  *
3135  * \param mixed 'classes' Either a single objectClass or several objectClasses
3136  * as an array
3137  * \param array 'attrs' The attrs array to be modified.
3138  *
3139  * */
3140 function add_objectClass($classes, &$attrs)
3142   if (is_array($classes)){
3143     $list= $classes;
3144   } else {
3145     $list= array($classes);
3146   }
3148   foreach ($list as $class){
3149     $attrs['objectClass'][]= $class;
3150   }
3154 /*! \brief Removes a given objectClass from the attrs entry
3155  *
3156  * Similar to add_objectClass, except that it removes the given
3157  * objectClasses. See it for the params.
3158  * */
3159 function remove_objectClass($classes, &$attrs)
3161   if (isset($attrs['objectClass'])){
3162     /* Array? */
3163     if (is_array($classes)){
3164       $list= $classes;
3165     } else {
3166       $list= array($classes);
3167     }
3169     $tmp= array();
3170     foreach ($attrs['objectClass'] as $oc) {
3171       foreach ($list as $class){
3172         if (strtolower($oc) != strtolower($class)){
3173           $tmp[]= $oc;
3174         }
3175       }
3176     }
3177     $attrs['objectClass']= $tmp;
3178   }
3182 /*! \brief  Initialize a file download with given content, name and data type. 
3183  *  \param  string data The content to send.
3184  *  \param  string name The name of the file.
3185  *  \param  string type The content identifier, default value is "application/octet-stream";
3186  */
3187 function send_binary_content($data,$name,$type = "application/octet-stream")
3189   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
3190   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
3191   header("Cache-Control: no-cache");
3192   header("Pragma: no-cache");
3193   header("Cache-Control: post-check=0, pre-check=0");
3194   header("Content-type: ".$type."");
3196   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
3198   /* Strip name if it is a complete path */
3199   if (preg_match ("/\//", $name)) {
3200         $name= basename($name);
3201   }
3202   
3203   /* force download dialog */
3204   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
3205     header('Content-Disposition: filename="'.$name.'"');
3206   } else {
3207     header('Content-Disposition: attachment; filename="'.$name.'"');
3208   }
3210   echo $data;
3211   exit();
3215 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
3217   if(is_string($str)){
3218     return(htmlentities($str,$type,$charset));
3219   }elseif(is_array($str)){
3220     foreach($str as $name => $value){
3221       $str[$name] = reverse_html_entities($value,$type,$charset);
3222     }
3223   }
3224   return($str);
3228 /*! \brief Encode special string characters so we can use the string in \
3229            HTML output, without breaking quotes.
3230     \param string The String we want to encode.
3231     \return string The encoded String
3232  */
3233 function xmlentities($str)
3234
3235   if(is_string($str)){
3237     static $asc2uni= array();
3238     if (!count($asc2uni)){
3239       for($i=128;$i<256;$i++){
3240     #    $asc2uni[chr($i)] = "&#x".dechex($i).";";
3241       }
3242     }
3244     $str = str_replace("&", "&amp;", $str);
3245     $str = str_replace("<", "&lt;", $str);
3246     $str = str_replace(">", "&gt;", $str);
3247     $str = str_replace("'", "&apos;", $str);
3248     $str = str_replace("\"", "&quot;", $str);
3249     $str = str_replace("\r", "", $str);
3250     $str = strtr($str,$asc2uni);
3251     return $str;
3252   }elseif(is_array($str)){
3253     foreach($str as $name => $value){
3254       $str[$name] = xmlentities($value);
3255     }
3256   }
3257   return($str);
3261 /*! \brief  Updates all accessTo attributes from a given value to a new one.
3262             For example if a host is renamed.
3263     \param  String  $from The source accessTo name.
3264     \param  String  $to   The destination accessTo name.
3265 */
3266 function update_accessTo($from,$to)
3268   global $config;
3269   $ldap = $config->get_ldap_link();
3270   $ldap->cd($config->current['BASE']);
3271   $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
3272   while($attrs = $ldap->fetch()){
3273     $new_attrs = array("accessTo" => array());
3274     $dn = $attrs['dn'];
3275     for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
3276       if($attrs['accessTo'][$i] == $from){
3277         if(!empty($to)){
3278           $new_attrs['accessTo'][] =  $to;
3279         }
3280       }else{
3281         $new_attrs['accessTo'][] =  $attrs['accessTo'][$i]; 
3282       }
3283     }
3284     $ldap->cd($dn);
3285     $ldap->modify($new_attrs);
3286     if (!$ldap->success()){
3287       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
3288     }
3289     new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
3290   }
3294 /*! \brief Returns a random char */
3295 function get_random_char () {
3296      $randno = rand (0, 63);
3297      if ($randno < 12) {
3298          return (chr ($randno + 46)); // Digits, '/' and '.'
3299      } else if ($randno < 38) {
3300          return (chr ($randno + 53)); // Uppercase
3301      } else {
3302          return (chr ($randno + 59)); // Lowercase
3303      }
3307 function cred_encrypt($input, $password) {
3309   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3310   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3312   return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
3317 function cred_decrypt($input,$password) {
3318   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3319   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3321   return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
3325 function get_object_info()
3327   return(session::get('objectinfo'));
3331 function set_object_info($str = "")
3333   session::set('objectinfo',$str);
3337 function isIpInNet($ip, $net, $mask) {
3338    // Move to long ints
3339    $ip= ip2long($ip);
3340    $net= ip2long($net);
3341    $mask= ip2long($mask);
3343    // Mask given IP with mask. If it returns "net", we're in...
3344    $res= $ip & $mask;
3346    return ($res == $net);
3350 function get_next_id($attrib, $dn)
3352   global $config;
3354   switch ($config->get_cfg_value("core","idAllocationMethod")){
3355     case "pool":
3356       return get_next_id_pool($attrib);
3357     case "traditional":
3358       return get_next_id_traditional($attrib, $dn);
3359   }
3361   msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("unknown idAllocation method!"), ERROR_DIALOG);
3362   return null;
3366 function get_next_id_pool($attrib) {
3367   global $config;
3369   /* Fill informational values */
3370   $min= $config->get_cfg_value("core","${attrib}PoolMin");
3371   $max= $config->get_cfg_value("core","${attrib}PoolMax");
3373   /* Sanity check */
3374   if ($min >= $max) {
3375     msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." ".sprintf(_("%sPoolMin >= %sPoolMax!"), bold($attrib), bold($attrib)), ERROR_DIALOG);
3376     return null;
3377   }
3379   /* ID to skip */
3380   $ldap= $config->get_ldap_link();
3381   $id= null;
3383   /* Try to allocate the ID several times before failing */
3384   $tries= 3;
3385   while ($tries--) {
3387     /* Look for ID map entry */
3388     $ldap->cd ($config->current['BASE']);
3389     $ldap->search ("(&(objectClass=sambaUnixIdPool)($attrib=*))", array("$attrib"));
3391     /* If it does not exist, create one with these defaults */
3392     if ($ldap->count() == 0) {
3393       /* Fill informational values */
3394       $minUserId= $config->get_cfg_value("core","uidNumberPoolMin");
3395       $minGroupId= $config->get_cfg_value("core","gidNumberPoolMin");
3397       /* Add as default */
3398       $attrs= array("objectClass" => array("organizationalUnit", "sambaUnixIdPool"));
3399       $attrs["ou"]= "idmap";
3400       $attrs["uidNumber"]= $minUserId;
3401       $attrs["gidNumber"]= $minGroupId;
3402       $ldap->cd("ou=idmap,".$config->current['BASE']);
3403       $ldap->add($attrs);
3404       if ($ldap->error != "Success") {
3405         msg_dialog::display(_("Error"), _("Cannot create sambaUnixIdPool entry!"), ERROR_DIALOG);
3406         return null;
3407       }
3408       $tries++;
3409       continue;
3410     }
3411     /* Bail out if it's not unique */
3412     if ($ldap->count() != 1) {
3413       msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("sambaUnixIdPool is not unique!"), ERROR_DIALOG);
3414       return null;
3415     }
3417     /* Store old attrib and generate new */
3418     $attrs= $ldap->fetch();
3419     $dn= $ldap->getDN();
3420     $oldAttr= $attrs[$attrib][0];
3421     $newAttr= $oldAttr + 1;
3423     /* Sanity check */
3424     if ($newAttr >= $max) {
3425       msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("no ID available!"), ERROR_DIALOG);
3426       return null;
3427     }
3428     if ($newAttr < $min) {
3429       msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("no ID available!"), ERROR_DIALOG);
3430       return null;
3431     }
3433     #FIXME: PHP is not able to do a modification of "del: .../add: ...", so this
3434     #       is completely unsafe in the moment.
3435     #/* Remove old attr, add new attr */
3436     #$attrs= array($attrib => $oldAttr);
3437     #$ldap->rm($attrs, $dn);
3438     #if ($ldap->error != "Success") {
3439     #  continue;
3440     #}
3441     $ldap->cd($dn);
3442     $ldap->modify(array($attrib => $newAttr));
3443     if ($ldap->error != "Success") {
3444       msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." ".$ldap->get_error(), ERROR_DIALOG);
3445       return null;
3446     } else {
3447       return $oldAttr;
3448     }
3449   }
3451   /* Bail out if we had problems getting the next id */
3452   if (!$tries) {
3453     msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("maximum number of tries exceeded!"), ERROR_DIALOG);
3454   }
3456   return $id;
3460 function get_next_id_traditional($attrib, $dn)
3462   global $config;
3464   $ids= array();
3465   $ldap= $config->get_ldap_link();
3467   $ldap->cd ($config->current['BASE']);
3468   if (preg_match('/gidNumber/i', $attrib)){
3469     $oc= "posixGroup";
3470   } else {
3471     $oc= "posixAccount";
3472   }
3473   $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
3475   /* Get list of ids */
3476   while ($attrs= $ldap->fetch()){
3477     $ids[]= (int)$attrs["$attrib"][0];
3478   }
3480   /* Add the nobody id */
3481   $ids[]= 65534;
3483   /* get the ranges */
3484   $tmp = array('0'=> 1000);
3485   if (preg_match('/posixAccount/', $oc) && $config->get_cfg_value("core","uidNumberBase") != ""){
3486     $tmp= explode('-',$config->get_cfg_value("core","uidNumberBase"));
3487   } elseif($config->get_cfg_value("core","gidNumberBase") != ""){
3488     $tmp= explode('-',$config->get_cfg_value("core","gidNumberBase"));
3489   }
3491   /* Set hwm to max if not set - for backward compatibility */
3492   $lwm= $tmp[0];
3493   if (isset($tmp[1])){
3494     $hwm= $tmp[1];
3495   } else {
3496     $hwm= pow(2,32);
3497   }
3498   /* Find out next free id near to UID_BASE */
3499   if ($config->get_cfg_value("core","baseIdHook") == ""){
3500     $base= $lwm;
3501   } else {
3502     /* Call base hook */
3503     $base= get_base_from_hook($dn, $attrib);
3504   }
3505   for ($id= $base; $id++; $id < pow(2,32)){
3506     if (!in_array($id, $ids)){
3507       return ($id);
3508     }
3509   }
3511   /* Should not happen */
3512   if ($id == $hwm){
3513     msg_dialog::display(_("Error"), _("Cannot allocate free ID!"), ERROR_DIALOG);
3514     exit;
3515   }
3519 /* Mark the occurance of a string with a span */
3520 function mark($needle, $haystack, $ignorecase= true)
3522   $result= "";
3524   while (preg_match('/^(.*)('.preg_quote($needle).')(.*)$/i', $haystack, $matches)) {
3525     $result.= $matches[1]."<span class='mark'>".$matches[2]."</span>";
3526     $haystack= $matches[3];
3527   }
3529   return $result.$haystack;
3533 /* Return an image description using the path */
3534 function image($path, $action= "", $title= "", $align= "middle")
3536   global $config;
3537   global $BASE_DIR;
3538   $label= null;
3540   // Bail out, if there's no style file
3541   if(!class_exists('session')){
3542     return "";    
3543   }
3544   if(!session::global_is_set("img-styles")){
3546     // Get theme
3547     if (isset ($config)){
3548       $theme= $config->get_cfg_value("core","theme");
3549     } else {
3551       // Fall back to default theme
3552       $theme= "default";
3553     }
3555     if (!file_exists("$BASE_DIR/ihtml/themes/$theme/img.styles")){
3556       die ("No img.style for this theme found!");
3557     }
3559     session::global_set('img-styles', unserialize(file_get_contents("$BASE_DIR/ihtml/themes/$theme/img.styles")));
3560   }
3561   $styles= session::global_get('img-styles');
3563   /* Extract labels from path */
3564   if (preg_match("/\.png\[(.*)\]$/", $path, $matches)) {
3565     $label= $matches[1];
3566   }
3568   $lbl= "";
3569   if ($label) {
3570     if (isset($styles["images/label-".$label.".png"])) {
3571       $lbl= "<div style='".$styles["images/label-".$label.".png"]."'></div>";
3572     } else {
3573       die("Invalid label specified: $label\n");
3574     }
3576     $path= preg_replace("/\[.*\]$/", "", $path);
3577   }
3579   // Non middle layout?
3580   if ($align == "middle") {
3581     $align= "";
3582   } else {
3583     $align= ";vertical-align:$align";
3584   }
3586   // Clickable image or not?
3587   if ($title != "") {
3588     $title= "title='$title'";
3589   }
3590   if ($action == "") {
3591     return "<div class='img' $title style='".$styles[$path]."$align'>$lbl</div>";
3592   } else {
3593     return "<input type='submit' class='img' id='$action' value='' name='$action' $title style='".$styles[$path]."$align'>";
3594   }
3597 /*! \brief    Encodes a complex string to be useable in HTML posts.
3598  */
3599 function postEncode($str)
3601   return(preg_replace("/=/","_", base64_encode($str)));
3604 /*! \brief    Decodes a string encoded by postEncode
3605  */
3606 function postDecode($str)
3608   return(base64_decode(preg_replace("/_/","=", $str)));
3612 /*! \brief    Generate styled output
3613  */
3614 function bold($str)
3616   return "<span class='highlight'>$str</span>";
3621 /*! \brief  Detect the special character handling for the currently used ldap database. 
3622  *          For example some convert , to \2C or " to \22.
3623  *         
3624  *  @param      Config  The GOsa configuration object.
3625  *  @return     Array   An array containing a character mapping the use.
3626  */
3627 function detectLdapSpecialCharHandling()
3629     // The list of chars to test for
3630     global $config;
3631     if(!$config) return(NULL);
3633     // In the DN we've to use escaped characters, but the object name (o)
3634     //  has the be un-escaped.
3635     $name = 'GOsaLdapEncoding_,_"_(_)_+_/';
3636     $dnName = 'GOsaLdapEncoding_\,_\"_(_)_\+_/';
3637    
3638     // Prapare name to be useable in filters
3639     $fixed= normalizeLdap(str_replace('\\\\', '\\\\\\', $name));
3640     $filterName = str_replace('\\,', '\\\\,', $fixed);
3641  
3642     // Create the target dn
3643     $oDN = "o={$dnName},".$config->current['BASE'];
3645     // Get ldap connection and check if we've already created the character 
3646     //  detection object. 
3647     $ldapCID = ldap_connect($config->current['SERVER']);
3648     ldap_set_option($ldapCID, LDAP_OPT_PROTOCOL_VERSION, 3);
3649     ldap_bind($ldapCID, $config->current['ADMINDN'],$config->current['ADMINPASSWORD']);
3650     $res = ldap_list($ldapCID, $config->current['BASE'], 
3651             "(&(o=".$filterName.")(objectClass=organization))",
3652             array('dn'));
3654     // If we haven't created the character-detection object, then create it now.
3655     $cnt = ldap_count_entries($ldapCID, $res);
3656     if(!$cnt){
3657         $obj = array();
3658         $obj['objectClass'] = array('top','organization');
3659         $obj['o'] = $name;
3660         $obj['description'] = 'GOsa character encoding test-object.';
3661         if(!@ldap_add($ldapCID, $oDN, $obj)){
3662             trigger_error("GOsa couldn't detect the special character handling used by your ldap!");
3663             return(NULL);
3664         }
3665     }
3666     
3667     // Read the character-handling detection entry from the ldap.
3668     $res = ldap_list($ldapCID, $config->current['BASE'],
3669             "(&(o=".$filterName.")(objectClass=organization))",
3670             array('dn','o'));
3671     $cnt = ldap_count_entries($ldapCID, $res);
3672     if($cnt != 1 || !$res){
3673         trigger_error("GOsa couldn't detect the special character handling used by your ldap!");
3674         return(NULL);
3675     }else{
3677         // Get the character handling entry from the ldap and check how the 
3678         //  values were written. Compare them with what
3679         //  we've initially intended to write and create a mapping out 
3680         //  of the results.
3681         $re = ldap_first_entry($ldapCID, $res);
3682         $attrs = ldap_get_attributes($ldapCID, $re);
3683    
3684         // Extract the interessting characters out of the dn and the 
3685         //  initially used $name for the entry. 
3686         $mapDNstr = preg_replace("/^o=GOsaLdapEncoding_([^,]*),.*$/","\\1", trim(ldap_get_dn($ldapCID, $re)));
3687         $mapDN = preg_split("/_/", $mapDNstr,0, PREG_SPLIT_NO_EMPTY);
3689         $mapNameStr = preg_replace("/^GOsaLdapEncoding_/","",$dnName);
3690         $mapName = preg_split("/_/", $mapNameStr,0, PREG_SPLIT_NO_EMPTY);
3692         // Create a mapping out of the results.
3693         $map = array();
3694         foreach($mapName as $key => $entry){
3695             $map[$entry] = $mapDN[$key];
3696         }
3697         return($map);
3698     }
3699     return(NULL);
3703 /*! \brief  Replaces placeholder in a given string.
3704  *          For example:
3705  *            '%uid@gonicus.de'         Replaces '%uid' with 'uid'.
3706  *            '{%uid[0]@gonicus.de}'    Replaces '%uid[0]' with the first char of 'uid'.
3707  *            '%uid[2-4]@gonicus.de'    Replaces '%uid[2-4]' with three chars from 'uid' starting from the second.
3708  *      
3709  *          The surrounding {} in example 2 are optional.
3710  *
3711  *  @param  String  The string to perform the action on.
3712  *  @param  Array   An array of replacements.
3713  *  @return     The resulting string.
3714  */
3715 function fillReplacements($str, $attrs, $shellArg = FALSE, $default = "")
3717     // Search for '{%...[n-m]}
3718     // Get all matching parts of the given string and sort them by
3719     //  length, to avoid replacing strings like '%uidNumber' with 'uid'
3720     //  instead of 'uidNumber'; The longest tring at first.
3721     preg_match_all('/(\{?%([a-z0-9]+)(\[(([0-9]+)(\-([0-9]+))?)\])?\}?)/i', $str ,$matches, PREG_SET_ORDER);
3722     $hits = array();
3723     foreach($matches as $match){
3724         $hits[strlen($match[2]).$match[0]] = $match;
3725     }
3726     krsort($hits);
3728     // Add lower case placeholders to avoid errors
3729     foreach($attrs as $key => $attr) $attrs[strtolower($key)] = $attr;
3731     // Replace the placeholder in the given string now.
3732     foreach($hits as $match){
3734         // Avoid errors about undefined index.
3735         $name = strtolower($match[2]);
3736         if(!isset($attrs[$name])) $attrs[$name] = $default;
3738         // Calculate the replacement
3739         $start = (isset($match[5])) ? $match[5] : 0;
3740         $end = strlen($attrs[$name]);
3741         if(isset($match[5]) && !isset($match[7])){
3742             $end = 1;
3743         }elseif(isset($match[5]) && isset($match[7])){
3744             $end = ($match[7]-$start+1);
3745         }
3746         $value  = substr($attrs[$name], $start, $end);
3748         // Use values which are valid for shell execution?
3749         if($shellArg) $value = escapeshellarg($value);
3751         // Replace the placeholder within the string.
3752         $str = preg_replace("/".preg_quote($match[0],'/')."/", $value, $str);
3753     }
3754     return($str);
3758 /*! \brief Generate a list of uid proposals based on a rule
3759  *
3760  *  Unroll given rule string by filling in attributes and replacing
3761  *  all keywords.
3762  *
3763  * \param string 'rule' The rule string from gosa.conf.
3764  * \param array 'attributes' A dictionary of attribute/value mappings
3765  * \return array List of valid not used uids
3766  */
3767 function gen_uids($rule, $attributes)
3769     global $config;
3770     $ldap = $config->get_ldap_link();
3771     $ldap->cd($config->current['BASE']);
3774     // Strip out non ascii chars
3775     foreach($attributes as $name => $value){
3776         $value = iconv('UTF-8', 'US-ASCII//TRANSLIT', $value);
3777         $value = preg_replace('/[^(\x20-\x7F)]*/','',$value);
3778         $attributes[$name] = strtolower($value);
3779     }
3781     // Search for '{%...[n-m]}
3782     // Get all matching parts of the given string and sort them by
3783     //  length, to avoid replacing strings like '%uidNumber' with 'uid'
3784     //  instead of 'uidNumber'; The longest tring at first.
3785     preg_match_all('/(\{?%([a-z0-9]+)(\[(([0-9]+)(\-([0-9]+))?)\])?\}?)/i', $rule ,$matches, PREG_SET_ORDER);
3786     $replacements = array(); 
3787     foreach($matches as $match){
3788         
3789         // No start position given, then add the complete value
3790         if(!isset($match[5])){
3791             $replacements[$match[0]][] = $attributes[$match[2]];
3792     
3793         // Start given but no end, so just add a single character
3794         }elseif(!isset($match[7])){
3795             if(isset($attributes[$match[2]][$match[5]])){
3796                 $tmp = " ".$attributes[$match[2]];
3797                 $replacements[$match[0]][] = trim($tmp[$match[5]]);
3798             }
3800         // Add all values in range
3801         }else{
3802             $str = "";
3803             for($i=$match[5]; $i<= $match[7]; $i++){
3804                 if(isset($attributes[$match[2]][$i])){
3805                     $tmp = " ".$attributes[$match[2]];
3806                     $str .= $tmp[$i];
3807                     $replacements[$match[0]][] = trim($str);
3808                 }
3809             }
3810         }
3811     }
3813     // Create proposal array
3814     $rules = array($rule);
3815     foreach($replacements as $tag => $values){
3816         $rules = gen_uid_proposals($rules, $tag,$values);
3817     }
3818     
3820     // Search for id tags {id:3} / {id#3}
3821     preg_match_all('/\{id(#|:)([0-9])+\}/i', $rule ,$matches, PREG_SET_ORDER);
3822     $idReplacements = array();
3823     foreach($matches as $match){
3824         if(count($match) != 3) continue;
3826         // Generate random number 
3827         if($match[1] == '#'){
3828             foreach($rules as $id => $ruleStr){
3829                 $genID = rand(pow(10,$match[2] -1),pow(10, ($match[2])) - 1);
3830                 $rules[$id] = preg_replace("/".preg_quote($match[0],'/')."/", $genID,$ruleStr);
3831             }
3832         }
3833     
3834         // Search for next free id 
3835         if($match[1] == ':'){
3837             // Walk through rules and replace all occurences of {id:..}
3838             foreach($rules as $id => $ruleStr){
3839                 $genID = 0;
3840                 $start = TRUE;
3841                 while($start || $ldap->count()){
3842                     $start = FALSE;
3843                     $number= sprintf("%0".$match[2]."d", $genID);
3844                     $testRule = preg_replace("/".preg_quote($match[0],'/')."/",$number,$ruleStr); 
3845                     $ldap->search('uid='.normalizeLdap($testRule));
3846                     $genID ++;
3847                 }
3848                 $rules[$id] = preg_replace("/".preg_quote($match[0],'/')."/",$number,$ruleStr);
3849             }
3850         }
3851     }
3853     // Create result set by checking which uid is already used and which is free.
3854     $ret = array();
3855     foreach($rules as $rule){
3856         $ldap->search('uid='.normalizeLdap($rule));
3857         if(!$ldap->count()){
3858             $ret[] =  $rule;
3859         }
3860     }
3861    
3862     return($ret);
3866 function gen_uid_proposals(&$rules, $tag, $values)
3868     $newRules = array();
3869     foreach($rules as $rule){
3870         foreach($values as $value){
3871             $newRules[] = preg_replace("/".preg_quote($tag,'/')."/", $value, $rule); 
3872         }
3873     }
3874     return($newRules);
3878 function gen_uuid() 
3880     return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
3881         // 32 bits for "time_low"
3882         mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
3884         // 16 bits for "time_mid"
3885         mt_rand( 0, 0xffff ),
3887         // 16 bits for "time_hi_and_version",
3888         // four most significant bits holds version number 4
3889         mt_rand( 0, 0x0fff ) | 0x4000,
3891         // 16 bits, 8 bits for "clk_seq_hi_res",
3892         // 8 bits for "clk_seq_low",
3893         // two most significant bits holds zero and one for variant DCE1.1
3894         mt_rand( 0, 0x3fff ) | 0x8000,
3896         // 48 bits for "node"
3897         mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
3898     );
3901 function gosa_file_name($filename)
3903     $tempfile = tempnam(sys_get_temp_dir(), 'GOsa'); 
3904     if(move_uploaded_file($filename, $tempfile)){ 
3905        return( $tempfile);
3906     }
3909 function gosa_file($filename)
3911     $tempfile = tempnam(sys_get_temp_dir(), 'GOsa'); 
3912     if(move_uploaded_file($filename, $tempfile)){ 
3913        return file( $tempfile );
3914     }
3917 function gosa_fopen($filename, $mode)
3919     $tempfile = tempnam(sys_get_temp_dir(), 'GOsa'); 
3920     if(move_uploaded_file($filename, $tempfile)){ 
3921        return fopen( $tempfile, $mode );
3922     }
3925 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3926 ?>