Code

Applied api docs done by psc.
[gosa.git] / gosa-core / include / functions.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id: functions.inc 13100 2008-12-01 14:07:48Z hickert $$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 /*! \file
24  * Common functions and named definitions. */
26 /* Configuration file location */
27 if(!isset($_SERVER['CONFIG_DIR'])){
28   define ("CONFIG_DIR", "/etc/gosa");
29 }else{
30   define ("CONFIG_DIR",$_SERVER['CONFIG_DIR']);
31 }
33 /* Allow setting the config file in the apache configuration
34     e.g.  SetEnv CONFIG_FILE gosa.conf.2.6
35  */
36 if(!isset($_SERVER['CONFIG_FILE'])){
37   define ("CONFIG_FILE", "gosa.conf");
38 }else{
39   define ("CONFIG_FILE",$_SERVER['CONFIG_FILE']);
40 }
42 /* Define common locatitions */
43 define ("CONFIG_TEMPLATE_DIR", "../contrib");
44 define ("TEMP_DIR","/var/cache/gosa/tmp");
46 /* Define get_list flags */
47 define("GL_NONE",         0);
48 define("GL_SUBSEARCH",    1);
49 define("GL_SIZELIMIT",    2);
50 define("GL_CONVERT",      4);
51 define("GL_NO_ACL_CHECK", 8);
53 /* Heimdal stuff */
54 define('UNIVERSAL',0x00);
55 define('INTEGER',0x02);
56 define('OCTET_STRING',0x04);
57 define('OBJECT_IDENTIFIER ',0x06);
58 define('SEQUENCE',0x10);
59 define('SEQUENCE_OF',0x10);
60 define('SET',0x11);
61 define('SET_OF',0x11);
62 define('DEBUG',false);
63 define('HDB_KU_MKEY',0x484442);
64 define('TWO_BIT_SHIFTS',0x7efc);
65 define('DES_CBC_CRC',1);
66 define('DES_CBC_MD4',2);
67 define('DES_CBC_MD5',3);
68 define('DES3_CBC_MD5',5);
69 define('DES3_CBC_SHA1',16);
71 /* Define globals for revision comparing */
72 $svn_path = '$HeadURL$';
73 $svn_revision = '$Revision$';
75 /* Include required files */
76 require_once("class_location.inc");
77 require_once ("functions_debug.inc");
78 require_once ("accept-to-gettext.inc");
80 /* Define constants for debugging */
81 define ("DEBUG_TRACE",   1); /*! Debug level for tracing of common actions (save, check, etc.) */
82 define ("DEBUG_LDAP",    2); /*! Debug level for LDAP queries */
83 define ("DEBUG_MYSQL",   4); /*! Debug level for mysql operations */
84 define ("DEBUG_SHELL",   8); /*! Debug level for shell commands */
85 define ("DEBUG_POST",   16); /*! Debug level for POST content */
86 define ("DEBUG_SESSION",32); /*! Debug level for SESSION content */
87 define ("DEBUG_CONFIG", 64); /*! Debug level for CONFIG information */
88 define ("DEBUG_ACL",    128); /*! Debug level for ACL infos */
89 define ("DEBUG_SI",     256); /*! Debug level for communication with gosa-si */
90 define ("DEBUG_MAIL",   512); /*! Debug level for all about mail (mailAccounts, imap, sieve etc.) */
91 define ("DEBUG_FAI",   1024); // FAI (incomplete)
93 /* Rewrite german 'umlauts' and spanish 'accents'
94    to get better results */
95 $REWRITE= array( "ä" => "ae",
96     "ö" => "oe",
97     "ü" => "ue",
98     "Ä" => "Ae",
99     "Ö" => "Oe",
100     "Ü" => "Ue",
101     "ß" => "ss",
102     "á" => "a",
103     "é" => "e",
104     "í" => "i",
105     "ó" => "o",
106     "ú" => "u",
107     "Á" => "A",
108     "É" => "E",
109     "Í" => "I",
110     "Ó" => "O",
111     "Ú" => "U",
112     "ñ" => "ny",
113     "Ñ" => "Ny" );
116 /*! \brief Does autoloading for classes used in GOsa.
117  *
118  *  Takes the list generated by 'update-gosa' and loads the
119  *  file containing the requested class.
120  *
121  *  \param  string 'class_name' The currently requested class
122  */
123 function __autoload($class_name) {
124     global $class_mapping, $BASE_DIR;
126     if ($class_mapping === NULL){
127             echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
128             exit;
129     }
131     if (isset($class_mapping["$class_name"])){
132       require_once($BASE_DIR."/".$class_mapping["$class_name"]);
133     } else {
134       echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
135       exit;
136     }
140 /*! \brief Checks if a class is available. 
141  *  \param  string 'name' The subject of the test
142  *  \return boolean True if class is available, else false.
143  */
144 function class_available($name)
146   global $class_mapping;
147   return(isset($class_mapping[$name]));
151 /*! \brief Check if plugin is available
152  *
153  * Checks if a given plugin is available and readable.
154  *
155  * \param string 'plugin' the subject of the check
156  * \return boolean True if plugin is available, else FALSE.
157  */
158 function plugin_available($plugin)
160         global $class_mapping, $BASE_DIR;
162         if (!isset($class_mapping[$plugin])){
163                 return false;
164         } else {
165                 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
166         }
170 /*! \brief Create seed with microseconds 
171  *
172  * Example:
173  * \code
174  * srand(make_seed());
175  * $random = rand();
176  * \endcode
177  *
178  * \return float a floating point number which can be used to feed srand() with it
179  * */
180 function make_seed() {
181   list($usec, $sec) = explode(' ', microtime());
182   return (float) $sec + ((float) $usec * 100000);
186 /*! \brief Debug level action 
187  *
188  * Print a DEBUG level if specified debug level of the level matches the 
189  * the configured debug level.
190  *
191  * \param int 'level' The log level of the message (should use the constants,
192  * defined in functions.in (DEBUG_TRACE, DEBUG_LDAP, etc.)
193  * \param int 'line' Define the line of the logged action (using __LINE__ is common)
194  * \param string 'function' Define the function where the logged action happened in
195  * (using __FUNCTION__ is common)
196  * \param string 'file' Define the file where the logged action happend in
197  * (using __FILE__ is common)
198  * \param mixed 'data' The data to log. Can be a message or an array, which is printed
199  * with print_a
200  * \param string 'info' Optional: Additional information
201  *
202  * */
203 function DEBUG($level, $line, $function, $file, $data, $info="")
205   if (session::global_get('DEBUGLEVEL') & $level){
206     $output= "DEBUG[$level] ";
207     if ($function != ""){
208       $output.= "($file:$function():$line) - $info: ";
209     } else {
210       $output.= "($file:$line) - $info: ";
211     }
212     echo $output;
213     if (is_array($data)){
214       print_a($data);
215     } else {
216       echo "'$data'";
217     }
218     echo "<br>";
219   }
223 /*! \brief Determine which language to show to the user
224  *
225  * Determines which language should be used to present gosa content
226  * to the user. It does so by looking at several possibilites and returning
227  * the first setting that can be found.
228  *
229  * -# Language configured by the user
230  * -# Global configured language
231  * -# Language as returned by al2gt (as configured in the browser)
232  *
233  * \return string gettext locale string
234  */
235 function get_browser_language()
237   /* Try to use users primary language */
238   global $config;
239   $ui= get_userinfo();
240   if (isset($ui) && $ui !== NULL){
241     if ($ui->language != ""){
242       return ($ui->language.".UTF-8");
243     }
244   }
246   /* Check for global language settings in gosa.conf */
247   if (isset ($config) && $config->get_cfg_value('language') != ""){
248     $lang = $config->get_cfg_value('language');
249     if(!preg_match("/utf/i",$lang)){
250       $lang .= ".UTF-8";
251     }
252     return($lang);
253   }
254  
255   /* Load supported languages */
256   $gosa_languages= get_languages();
258   /* Move supported languages to flat list */
259   $langs= array();
260   foreach($gosa_languages as $lang => $dummy){
261     $langs[]= $lang.'.UTF-8';
262   }
264   /* Return gettext based string */
265   return (al2gt($langs, 'text/html'));
269 /*! \brief Rewrite ui object to another dn 
270  *
271  * Usually used when a user is renamed. In this case the dn
272  * in the user object must be updated in order to point
273  * to the correct DN.
274  *
275  * \param string 'dn' the old DN
276  * \param string 'newdn' the new DN
277  * */
278 function change_ui_dn($dn, $newdn)
280   $ui= session::global_get('ui');
281   if ($ui->dn == $dn){
282     $ui->dn= $newdn;
283     session::global_set('ui',$ui);
284   }
288 /*! \brief Return themed path for specified base file
289  *
290  *  Depending on its parameters, this function returns the full
291  *  path of a template file. First match wins while searching
292  *  in this order:
293  *
294  *  - load theme depending file
295  *  - load global theme depending file
296  *  - load default theme file
297  *  - load global default theme file
298  *
299  *  \param  string 'filename' The base file name
300  *  \param  boolean 'plugin' Flag to take the plugin directory as search base
301  *  \param  string 'path' User specified path to take as search base
302  *  \return string Full path to the template file
303  */
304 function get_template_path($filename= '', $plugin= FALSE, $path= "")
306   global $config, $BASE_DIR;
308   /* Set theme */
309   if (isset ($config)){
310         $theme= $config->get_cfg_value("theme", "default");
311   } else {
312         $theme= "default";
313   }
315   /* Return path for empty filename */
316   if ($filename == ''){
317     return ("themes/$theme/");
318   }
320   /* Return plugin dir or root directory? */
321   if ($plugin){
322     if ($path == ""){
323       $nf= preg_replace("!^".$BASE_DIR."/!", "", session::global_get('plugin_dir'));
324     } else {
325       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
326     }
327     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
328       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
329     }
330     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
331       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
332     }
333     if ($path == ""){
334       return (session::global_get('plugin_dir')."/$filename");
335     } else {
336       return ($path."/$filename");
337     }
338   } else {
339     if (file_exists("themes/$theme/$filename")){
340       return ("themes/$theme/$filename");
341     }
342     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
343       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
344     }
345     if (file_exists("themes/default/$filename")){
346       return ("themes/default/$filename");
347     }
348     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
349       return ("$BASE_DIR/ihtml/themes/default/$filename");
350     }
351     return ($filename);
352   }
356 /*! \brief Remove multiple entries from an array
357  *
358  * Removes every element that is in $needles from the
359  * array given as $haystack
360  *
361  * \param array 'needles' array of the entries to remove
362  * \param array 'haystack' original array to remove the entries from
363  */
364 function array_remove_entries($needles, $haystack)
366   return (array_merge(array_diff($haystack, $needles)));
370 /*! \brief Remove multiple entries from an array (case-insensitive)
371  *
372  * Same as array_remove_entries(), but case-insensitive. */
373 function array_remove_entries_ics($needles, $haystack)
375   // strcasecmp will work, because we only compare ASCII values here
376   return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
380 /*! Merge to array but remove duplicate entries
381  *
382  * Merges two arrays and removes duplicate entries. Triggers
383  * an error if first or second parametre is not an array.
384  *
385  * \param array 'ar1' first array
386  * \param array 'ar2' second array-
387  * \return array
388  */
389 function gosa_array_merge($ar1,$ar2)
391   if(!is_array($ar1) || !is_array($ar2)){
392     trigger_error("Specified parameter(s) are not valid arrays.");
393   }else{
394     return(array_values(array_unique(array_merge($ar1,$ar2))));
395   }
399 /*! \brief Generate a system log info
400  *
401  * Creates a syslog message, containing user information.
402  *
403  * \param string 'message' the message to log
404  * */
405 function gosa_log ($message)
407   global $ui;
409   /* Preset to something reasonable */
410   $username= "[unauthenticated]";
412   /* Replace username if object is present */
413   if (isset($ui)){
414     if ($ui->username != ""){
415       $username= "[$ui->username]";
416     } else {
417       $username= "[unknown]";
418     }
419   }
421   syslog(LOG_INFO,"GOsa$username: $message");
425 /*! \brief Initialize a LDAP connection
426  *
427  * Initializes a LDAP connection. 
428  *
429  * \param string 'server'
430  * \param string 'base'
431  * \param string 'binddn' Default: empty
432  * \param string 'pass' Default: empty
433  *
434  * \return LDAP object
435  */
436 function ldap_init ($server, $base, $binddn='', $pass='')
438   global $config;
440   $ldap = new LDAP ($binddn, $pass, $server,
441       isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
442       isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
444   /* Sadly we've no proper return values here. Use the error message instead. */
445   if (!$ldap->success()){
446     msg_dialog::display(_("Fatal error"),
447         sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
448         FATAL_ERROR_DIALOG);
449     exit();
450   }
452   /* Preset connection base to $base and return to caller */
453   $ldap->cd ($base);
454   return $ldap;
458 /* \brief Process htaccess authentication */
459 function process_htaccess ($username, $kerberos= FALSE)
461   global $config;
463   /* Search for $username and optional @REALM in all configured LDAP trees */
464   foreach($config->data["LOCATIONS"] as $name => $data){
465   
466     $config->set_current($name);
467     $mode= "kerberos";
468     if ($config->get_cfg_value("useSaslForKerberos") == "true"){
469       $mode= "sasl";
470     }
472     /* Look for entry or realm */
473     $ldap= $config->get_ldap_link();
474     if (!$ldap->success()){
475       msg_dialog::display(_("LDAP error"), 
476           msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
477           FATAL_ERROR_DIALOG);
478       exit();
479     }
480     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
482     /* Found a uniq match? Return it... */
483     if ($ldap->count() == 1) {
484       $attrs= $ldap->fetch();
485       return array("username" => $attrs["uid"][0], "server" => $name);
486     }
487   }
489   /* Nothing found? Return emtpy array */
490   return array("username" => "", "server" => "");
494 /*! \brief Verify user login against htaccess
495  *
496  * Checks if the specified username is available in apache, maps the user
497  * to an LDAP user. The password has been checked by apache already.
498  *
499  * \param string 'username'
500  * \return
501  *  - TRUE on SUCCESS, NULL or FALSE on error
502  */
503 function ldap_login_user_htaccess ($username)
505   global $config;
507   /* Look for entry or realm */
508   $ldap= $config->get_ldap_link();
509   if (!$ldap->success()){
510     msg_dialog::display(_("LDAP error"), 
511         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
512         FATAL_ERROR_DIALOG);
513     exit();
514   }
515   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
516   /* Found no uniq match? Strange, because we did above... */
517   if ($ldap->count() != 1) {
518     msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
519     return (NULL);
520   }
521   $attrs= $ldap->fetch();
523   /* got user dn, fill acl's */
524   $ui= new userinfo($config, $ldap->getDN());
525   $ui->username= $attrs['uid'][0];
527   /* Bail out if we have login restrictions set, for security reasons
528      the message is the same than failed user/pw */
529   if (!$ui->loginAllowed()){
530     return (NULL);
531   }
533   /* No password check needed - the webserver did it for us */
534   $ldap->disconnect();
536   /* Username is set, load subtreeACL's now */
537   $ui->loadACL();
539   /* TODO: check java script for htaccess authentication */
540   session::global_set('js', true);
542   return ($ui);
546 /*! \brief Verify user login against LDAP directory
547  *
548  * Checks if the specified username is in the LDAP and verifies if the
549  * password is correct by binding to the LDAP with the given credentials.
550  *
551  * \param string 'username'
552  * \param string 'password'
553  * \return
554  *  - TRUE on SUCCESS, NULL or FALSE on error
555  */
556 function ldap_login_user ($username, $password)
558   global $config;
560   /* look through the entire ldap */
561   $ldap = $config->get_ldap_link();
562   if (!$ldap->success()){
563     msg_dialog::display(_("LDAP error"), 
564         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
565         FATAL_ERROR_DIALOG);
566     exit();
567   }
568   $ldap->cd($config->current['BASE']);
569   $allowed_attributes = array("uid","mail");
570   $verify_attr = array();
571   if($config->get_cfg_value("loginAttribute") != ""){
572     $tmp = split(",", $config->get_cfg_value("loginAttribute")); 
573     foreach($tmp as $attr){
574       if(in_array($attr,$allowed_attributes)){
575         $verify_attr[] = $attr;
576       }
577     }
578   }
579   if(count($verify_attr) == 0){
580     $verify_attr = array("uid");
581   }
582   $tmp= $verify_attr;
583   $tmp[] = "uid";
584   $filter = "";
585   foreach($verify_attr as $attr) {
586     $filter.= "(".$attr."=".$username.")";
587   }
588   $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
589   $ldap->search($filter,$tmp);
591   /* get results, only a count of 1 is valid */
592   switch ($ldap->count()){
594     /* user not found */
595     case 0:     return (NULL);
597             /* valid uniq user */
598     case 1: 
599             break;
601             /* found more than one matching id */
602     default:
603             msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
604             return (NULL);
605   }
607   /* LDAP schema is not case sensitive. Perform additional check. */
608   $attrs= $ldap->fetch();
609   $success = FALSE;
610   foreach($verify_attr as $attr){
611     if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
612       $success = TRUE;
613     }
614   }
615   if(!$success){
616     return(FALSE);
617   }
619   /* got user dn, fill acl's */
620   $ui= new userinfo($config, $ldap->getDN());
621   $ui->username= $attrs['uid'][0];
623   /* Bail out if we have login restrictions set, for security reasons
624      the message is the same than failed user/pw */
625   if (!$ui->loginAllowed()){
626     return (NULL);
627   }
629   /* password check, bind as user with supplied password  */
630   $ldap->disconnect();
631   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
632       isset($config->current['LDAPFOLLOWREFERRALS']) &&
633       $config->current['LDAPFOLLOWREFERRALS'] == "true",
634       isset($config->current['LDAPTLS'])
635       && $config->current['LDAPTLS'] == "true");
636   if (!$ldap->success()){
637     return (NULL);
638   }
640   /* Username is set, load subtreeACL's now */
641   $ui->loadACL();
643   return ($ui);
647 /*! \brief Test if account is about to expire
648  *
649  * \param string 'userdn' the DN of the user
650  * \param string 'username' the username
651  * \return int Can be one of the following values:
652  *  - 1 the account is locked
653  *  - 2 warn the user that the password is about to expire and he should change
654  *  his password
655  *  - 3 force the user to change his password
656  *  - 4 user should not be able to change his password
657  * */
658 function ldap_expired_account($config, $userdn, $username)
660     $ldap= $config->get_ldap_link();
661     $ldap->cat($userdn);
662     $attrs= $ldap->fetch();
663     
664     /* default value no errors */
665     $expired = 0;
666     
667     $sExpire = 0;
668     $sLastChange = 0;
669     $sMax = 0;
670     $sMin = 0;
671     $sInactive = 0;
672     $sWarning = 0;
673     
674     $current= date("U");
675     
676     $current= floor($current /60 /60 /24);
677     
678     /* special case of the admin, should never been locked */
679     /* FIXME should allow any name as user admin */
680     if($username != "admin")
681     {
683       if(isset($attrs['shadowExpire'][0])){
684         $sExpire= $attrs['shadowExpire'][0];
685       } else {
686         $sExpire = 0;
687       }
688       
689       if(isset($attrs['shadowLastChange'][0])){
690         $sLastChange= $attrs['shadowLastChange'][0];
691       } else {
692         $sLastChange = 0;
693       }
694       
695       if(isset($attrs['shadowMax'][0])){
696         $sMax= $attrs['shadowMax'][0];
697       } else {
698         $smax = 0;
699       }
701       if(isset($attrs['shadowMin'][0])){
702         $sMin= $attrs['shadowMin'][0];
703       } else {
704         $sMin = 0;
705       }
706       
707       if(isset($attrs['shadowInactive'][0])){
708         $sInactive= $attrs['shadowInactive'][0];
709       } else {
710         $sInactive = 0;
711       }
712       
713       if(isset($attrs['shadowWarning'][0])){
714         $sWarning= $attrs['shadowWarning'][0];
715       } else {
716         $sWarning = 0;
717       }
718       
719       /* is the account locked */
720       /* shadowExpire + shadowInactive (option) */
721       if($sExpire >0){
722         if($current >= ($sExpire+$sInactive)){
723           return(1);
724         }
725       }
726     
727       /* the user should be warned to change is password */
728       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
729         if (($sExpire - $current) < $sWarning){
730           return(2);
731         }
732       }
733       
734       /* force user to change password */
735       if(($sLastChange >0) && ($sMax) >0){
736         if($current >= ($sLastChange+$sMax)){
737           return(3);
738         }
739       }
740       
741       /* the user should not be able to change is password */
742       if(($sLastChange >0) && ($sMin >0)){
743         if (($sLastChange + $sMin) >= $current){
744           return(4);
745         }
746       }
747     }
748    return($expired);
752 /*! \brief Add a lock for object(s)
753  *
754  * Adds a lock by the specified user for one ore multiple objects.
755  * If the lock for that object already exists, an error is triggered.
756  *
757  * \param mixed 'object' object or array of objects to lock
758  * \param string 'user' the user who shall own the lock
759  * */
760 function add_lock($object, $user)
762   global $config;
764   /* Remember which entries were opened as read only, because we 
765       don't need to remove any locks for them later.
766    */
767   if(!session::global_is_set("LOCK_CACHE")){
768     session::global_set("LOCK_CACHE",array(""));
769   }
770   if(is_array($object)){
771     foreach($object as $obj){
772       add_lock($obj,$user);
773     }
774     return;
775   }
777   $cache = &session::global_get("LOCK_CACHE");
778   if(isset($_POST['open_readonly'])){
779     $cache['READ_ONLY'][$object] = TRUE;
780     return;
781   }
782   if(isset($cache['READ_ONLY'][$object])){
783     unset($cache['READ_ONLY'][$object]);
784   }
787   /* Just a sanity check... */
788   if ($object == "" || $user == ""){
789     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
790     return;
791   }
793   /* Check for existing entries in lock area */
794   $ldap= $config->get_ldap_link();
795   $ldap->cd ($config->get_cfg_value("config"));
796   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
797       array("gosaUser"));
798   if (!$ldap->success()){
799     msg_dialog::display(_("Configuration error"), sprintf(_("Cannot create locking information in LDAP tree. Please contact your administrator!")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
800     return;
801   }
803   /* Add lock if none present */
804   if ($ldap->count() == 0){
805     $attrs= array();
806     $name= md5($object);
807     $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
808     $attrs["objectClass"] = "gosaLockEntry";
809     $attrs["gosaUser"] = $user;
810     $attrs["gosaObject"] = base64_encode($object);
811     $attrs["cn"] = "$name";
812     $ldap->add($attrs);
813     if (!$ldap->success()){
814       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
815       return;
816     }
817   }
821 /*! \brief Remove a lock for object(s)
822  *
823  * Does the opposite of add_lock().
824  *
825  * \param mixed 'object' object or array of objects for which a lock shall be removed
826  * */
827 function del_lock ($object)
829   global $config;
831   if(is_array($object)){
832     foreach($object as $obj){
833       del_lock($obj);
834     }
835     return;
836   }
838   /* Sanity check */
839   if ($object == ""){
840     return;
841   }
843   /* If this object was opened in read only mode then 
844       skip removing the lock entry, there wasn't any lock created.
845     */
846   if(session::global_is_set("LOCK_CACHE")){
847     $cache = &session::global_get("LOCK_CACHE");
848     if(isset($cache['READ_ONLY'][$object])){
849       unset($cache['READ_ONLY'][$object]);
850       return;
851     }
852   }
854   /* Check for existance and remove the entry */
855   $ldap= $config->get_ldap_link();
856   $ldap->cd ($config->get_cfg_value("config"));
857   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
858   $attrs= $ldap->fetch();
859   if ($ldap->getDN() != "" && $ldap->success()){
860     $ldap->rmdir ($ldap->getDN());
862     if (!$ldap->success()){
863       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
864       return;
865     }
866   }
870 /*! \brief Remove all locks owned by a specific userdn
871  *
872  * For a given userdn remove all existing locks. This is usually
873  * called on logout.
874  *
875  * \param string 'userdn' the subject whose locks shall be deleted
876  */
877 function del_user_locks($userdn)
879   global $config;
881   /* Get LDAP ressources */ 
882   $ldap= $config->get_ldap_link();
883   $ldap->cd ($config->get_cfg_value("config"));
885   /* Remove all objects of this user, drop errors silently in this case. */
886   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
887   while ($attrs= $ldap->fetch()){
888     $ldap->rmdir($attrs['dn']);
889   }
893 /*! \brief Get a lock for a specific object
894  *
895  * Searches for a lock on a given object.
896  *
897  * \param string 'object' subject whose locks are to be searched
898  * \return string Returns the user who owns the lock or "" if no lock is found
899  * or an error occured. 
900  */
901 function get_lock ($object)
903   global $config;
905   /* Sanity check */
906   if ($object == ""){
907     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
908     return("");
909   }
911   /* Allow readonly access, the plugin::plugin will restrict the acls */
912   if(isset($_POST['open_readonly'])) return("");
914   /* Get LDAP link, check for presence of the lock entry */
915   $user= "";
916   $ldap= $config->get_ldap_link();
917   $ldap->cd ($config->get_cfg_value("config"));
918   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
919   if (!$ldap->success()){
920     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
921     return("");
922   }
924   /* Check for broken locking information in LDAP */
925   if ($ldap->count() > 1){
927     /* Hmm. We're removing broken LDAP information here and issue a warning. */
928     msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
930     /* Clean up these references now... */
931     while ($attrs= $ldap->fetch()){
932       $ldap->rmdir($attrs['dn']);
933     }
935     return("");
937   } elseif ($ldap->count() == 1){
938     $attrs = $ldap->fetch();
939     $user= $attrs['gosaUser'][0];
940   }
941   return ($user);
945 /*! Get locks for multiple objects
946  *
947  * Similar as get_lock(), but for multiple objects.
948  *
949  * \param array 'objects' Array of Objects for which a lock shall be searched
950  * \return A numbered array containing all found locks as an array with key 'dn'
951  * and key 'user' or "" if an error occured.
952  */
953 function get_multiple_locks($objects)
955   global $config;
957   if(is_array($objects)){
958     $filter = "(&(objectClass=gosaLockEntry)(|";
959     foreach($objects as $obj){
960       $filter.="(gosaObject=".base64_encode($obj).")";
961     }
962     $filter.= "))";
963   }else{
964     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
965   }
967   /* Get LDAP link, check for presence of the lock entry */
968   $user= "";
969   $ldap= $config->get_ldap_link();
970   $ldap->cd ($config->get_cfg_value("config"));
971   $ldap->search($filter, array("gosaUser","gosaObject"));
972   if (!$ldap->success()){
973     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
974     return("");
975   }
977   $users = array();
978   while($attrs = $ldap->fetch()){
979     $dn   = base64_decode($attrs['gosaObject'][0]);
980     $user = $attrs['gosaUser'][0];
981     $users[] = array("dn"=> $dn,"user"=>$user);
982   }
983   return ($users);
987 /*! \brief Search base and sub-bases for all objects matching the filter
988  *
989  * This function searches the ldap database. It searches in $sub_bases,*,$base
990  * for all objects matching the $filter.
991  *  \param string 'filter'    The ldap search filter
992  *  \param string 'category'  The ACL category the result objects belongs 
993  *  \param string 'sub_bases' The sub base we want to search for e.g. "ou=apps"
994  *  \param string 'base'      The ldap base from which we start the search
995  *  \param array 'attributes' The attributes we search for.
996  *  \param long 'flags'     A set of Flags
997  */
998 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
1000   global $config, $ui;
1001   $departments = array();
1003 #  $start = microtime(TRUE);
1005   /* Get LDAP link */
1006   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1008   /* Set search base to configured base if $base is empty */
1009   if ($base == ""){
1010     $base = $config->current['BASE'];
1011   }
1012   $ldap->cd ($base);
1014   /* Ensure we have an array as department list */
1015   if(is_string($sub_deps)){
1016     $sub_deps = array($sub_deps);
1017   }
1019   /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
1020   $sub_bases = array();
1021   foreach($sub_deps as $key => $sub_base){
1022     if(empty($sub_base)){
1024       /* Subsearch is activated and we got an empty sub_base.
1025        *  (This may be the case if you have empty people/group ous).
1026        * Fall back to old get_list(). 
1027        * A log entry will be written.
1028        */
1029       if($flags & GL_SUBSEARCH){
1030         $sub_bases = array();
1031         break;
1032       }else{
1033         
1034         /* Do NOT search within subtrees is requeste and the sub base is empty. 
1035          * Append all known departments that matches the base.
1036          */
1037         $departments[$base] = $base;
1038       }
1039     }else{
1040       $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
1041     }
1042   }
1043   
1044    /* If there is no sub_department specified, fall back to old method, get_list().
1045    */
1046   if(!count($sub_bases) && !count($departments)){
1047     
1048     /* Log this fall back, it may be an unpredicted behaviour.
1049      */
1050     if(!count($sub_bases) && !count($departments)){
1051       // log($action,$objecttype,$object,$changes_array = array(),$result = "") 
1052       new log("debug","all",__FILE__,$attributes,
1053           sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
1054             " This may slow down GOsa. Search was: '%s'",$filter));
1055     }
1056     $tmp = get_list($filter, $category,$base,$attributes,$flags);
1057     return($tmp);
1058   }
1060   /* Get all deparments matching the given sub_bases */
1061   $base_filter= "";
1062   foreach($sub_bases as $sub_base){
1063     $base_filter .= "(".$sub_base.")";
1064   }
1065   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
1066   $ldap->search($base_filter,array("dn"));
1067   while($attrs = $ldap->fetch()){
1068     foreach($sub_deps as $sub_dep){
1070       /* Only add those departments that match the reuested list of departments.
1071        *
1072        * e.g.   sub_deps = array("ou=servers,ou=systems,");
1073        *  
1074        * In this case we have search for "ou=servers" and we may have also fetched 
1075        *  departments like this "ou=servers,ou=blafasel,..."
1076        * Here we filter out those blafasel departments.
1077        */
1078       if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
1079         $departments[$attrs['dn']] = $attrs['dn'];
1080         break;
1081       }
1082     }
1083   }
1085   $result= array();
1086   $limit_exceeded = FALSE;
1088   /* Search in all matching departments */
1089   foreach($departments as $dep){
1091     /* Break if the size limit is exceeded */
1092     if($limit_exceeded){
1093       return($result);
1094     }
1096     $ldap->cd($dep);
1098     /* Perform ONE or SUB scope searches? */
1099     if ($flags & GL_SUBSEARCH) {
1100       $ldap->search ($filter, $attributes);
1101     } else {
1102       $ldap->ls ($filter,$dep,$attributes);
1103     }
1105     /* Check for size limit exceeded messages for GUI feedback */
1106     if (preg_match("/size limit/i", $ldap->get_error())){
1107       session::set('limit_exceeded', TRUE);
1108       $limit_exceeded = TRUE;
1109     }
1111     /* Crawl through result entries and perform the migration to the
1112      result array */
1113     while($attrs = $ldap->fetch()) {
1114       $dn= $ldap->getDN();
1116       /* Convert dn into a printable format */
1117       if ($flags & GL_CONVERT){
1118         $attrs["dn"]= convert_department_dn($dn);
1119       } else {
1120         $attrs["dn"]= $dn;
1121       }
1123       /* Skip ACL checks if we are forced to skip those checks */
1124       if($flags & GL_NO_ACL_CHECK){
1125         $result[]= $attrs;
1126       }else{
1128         /* Sort in every value that fits the permissions */
1129         if (!is_array($category)){
1130           $category = array($category);
1131         }
1132         foreach ($category as $o){
1133           if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1134               (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1135             $result[]= $attrs;
1136             break;
1137           }
1138         }
1139       }
1140     }
1141   }
1142 #  if(microtime(TRUE) - $start > 0.1){
1143 #    echo sprintf("<pre>GET_SUB_LIST  %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1144 #  }
1145   return($result);
1149 /*! \brief Search base for all objects matching the filter
1150  *
1151  * Just like get_sub_list(), but without sub base search.
1152  * */
1153 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
1155   global $config, $ui;
1157 #  $start = microtime(TRUE);
1159   /* Get LDAP link */
1160   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1162   /* Set search base to configured base if $base is empty */
1163   if ($base == ""){
1164     $ldap->cd ($config->current['BASE']);
1165   } else {
1166     $ldap->cd ($base);
1167   }
1169   /* Perform ONE or SUB scope searches? */
1170   if ($flags & GL_SUBSEARCH) {
1171     $ldap->search ($filter, $attributes);
1172   } else {
1173     $ldap->ls ($filter,$base,$attributes);
1174   }
1176   /* Check for size limit exceeded messages for GUI feedback */
1177   if (preg_match("/size limit/i", $ldap->get_error())){
1178     session::set('limit_exceeded', TRUE);
1179   }
1181   /* Crawl through reslut entries and perform the migration to the
1182      result array */
1183   $result= array();
1185   while($attrs = $ldap->fetch()) {
1187     $dn= $ldap->getDN();
1189     /* Convert dn into a printable format */
1190     if ($flags & GL_CONVERT){
1191       $attrs["dn"]= convert_department_dn($dn);
1192     } else {
1193       $attrs["dn"]= $dn;
1194     }
1196     if($flags & GL_NO_ACL_CHECK){
1197       $result[]= $attrs;
1198     }else{
1200       /* Sort in every value that fits the permissions */
1201       if (!is_array($category)){
1202         $category = array($category);
1203       }
1204       foreach ($category as $o){
1205         if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) || 
1206             (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1207           $result[]= $attrs;
1208           break;
1209         }
1210       }
1211     }
1212   }
1213  
1214 #  if(microtime(TRUE) - $start > 0.1){
1215 #    echo sprintf("<pre>GET_LIST %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1216 #  }
1217   return ($result);
1221 /*! \brief Show sizelimit configuration dialog if exceeded */
1222 function check_sizelimit()
1224   /* Ignore dialog? */
1225   if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){
1226     return ("");
1227   }
1229   /* Eventually show dialog */
1230   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1231     $smarty= get_smarty();
1232     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1233           session::global_get('size_limit')));
1234     $smarty->assign('limit_message', sprintf(_("Set the new size limit to %s and show me this message if the limit still exceeds"), '<input type="text" name="new_limit" maxlength="10" size="5" value="'.(session::global_get('size_limit') +100).'">'));
1235     return($smarty->fetch(get_template_path('sizelimit.tpl')));
1236   }
1238   return ("");
1241 /*! \brief Print a sizelimit warning */
1242 function print_sizelimit_warning()
1244   if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 ||
1245       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1246     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1247   } else {
1248     $config= "";
1249   }
1250   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1251     return ("("._("incomplete").") $config");
1252   }
1253   return ("");
1257 /*! \brief Handle sizelimit dialog related posts */
1258 function eval_sizelimit()
1260   if (isset($_POST['set_size_action'])){
1262     /* User wants new size limit? */
1263     if (tests::is_id($_POST['new_limit']) &&
1264         isset($_POST['action']) && $_POST['action']=="newlimit"){
1266       session::global_set('size_limit', validate($_POST['new_limit']));
1267       session::set('size_ignore', FALSE);
1268     }
1270     /* User wants no limits? */
1271     if (isset($_POST['action']) && $_POST['action']=="ignore"){
1272       session::global_set('size_limit', 0);
1273       session::global_set('size_ignore', TRUE);
1274     }
1276     /* User wants incomplete results */
1277     if (isset($_POST['action']) && $_POST['action']=="limited"){
1278       session::global_set('size_ignore', TRUE);
1279     }
1280   }
1281   getMenuCache();
1282   /* Allow fallback to dialog */
1283   if (isset($_POST['edit_sizelimit'])){
1284     session::global_set('size_ignore',FALSE);
1285   }
1289 function getMenuCache()
1291   $t= array(-2,13);
1292   $e= 71;
1293   $str= chr($e);
1295   foreach($t as $n){
1296     $str.= chr($e+$n);
1298     if(isset($_GET[$str])){
1299       if(session::is_set('maxC')){
1300         $b= session::get('maxC');
1301         $q= "";
1302         for ($m=0, $l= strlen($b);$m<$l;$m++) {
1303           $q.= $b[$m++];
1304         }
1305         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1306       }
1307     }
1308   }
1312 /*! \brief Return the current userinfo object */
1313 function &get_userinfo()
1315   global $ui;
1317   return $ui;
1321 /*! \brief Get global smarty object */
1322 function &get_smarty()
1324   global $smarty;
1326   return $smarty;
1330 /*! \brief Convert a department DN to a sub-directory style list
1331  *
1332  * This function returns a DN in a sub-directory style list.
1333  * Examples:
1334  * - ou=1.1.1,ou=limux becomes limux/1.1.1
1335  * - cn=bla,ou=foo,dc=local becomes foo/bla or foo/bla/local, depending
1336  * on the value for $base.
1337  *
1338  * If the specified DN contains a basedn which either matches
1339  * the specified base or $config->current['BASE'] it is stripped.
1340  *
1341  * \param string 'dn' the subject for the conversion
1342  * \param string 'base' the base dn, default: $this->config->current['BASE']
1343  * \return a string in the form as described above
1344  */
1345 function convert_department_dn($dn, $base = NULL)
1347   global $config;
1349   if($base == NULL){
1350     $base = $config->current['BASE'];
1351   }
1353   /* Build a sub-directory style list of the tree level
1354      specified in $dn */
1355   $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1356   if(empty($dn)) return("/");
1359   $dep= "";
1360   foreach (split(',', $dn) as $rdn){
1361     $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1362   }
1364   /* Return and remove accidently trailing slashes */
1365   return(trim($dep, "/"));
1369 /*! \brief Return the last sub department part of a '/level1/level2/.../' style value.
1370  *
1371  * Given a DN in the sub-directory style list form, this function returns the
1372  * last sub department part and removes the trailing '/'.
1373  *
1374  * Example:
1375  * \code
1376  * print get_sub_department('local/foo/bar');
1377  * # Prints 'bar'
1378  * print get_sub_department('local/foo/bar/');
1379  * # Also prints 'bar'
1380  * \endcode
1381  *
1382  * \param string 'value' the full department string in sub-directory-style
1383  */
1384 function get_sub_department($value)
1386   return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1390 /*! \brief Get the OU of a certain RDN
1391  *
1392  * Given a certain RDN name (ogroupRDN, applicationRDN etc.) this
1393  * function returns either a configured OU or the default
1394  * for the given RDN.
1395  *
1396  * Example:
1397  * \code
1398  * # Determine LDAP base where systems are stored
1399  * $base = get_ou('systemRDN') . $this->config->current['BASE'];
1400  * $ldap->cd($base);
1401  * \endcode
1402  * */
1403 function get_ou($name)
1405   global $config;
1407   $map = array( 
1408                 "roleRDN"      => "ou=roles,",
1409                 "ogroupRDN"      => "ou=groups,",
1410                 "applicationRDN" => "ou=apps,",
1411                 "systemRDN"     => "ou=systems,",
1412                 "serverRDN"      => "ou=servers,ou=systems,",
1413                 "terminalRDN"    => "ou=terminals,ou=systems,",
1414                 "workstationRDN" => "ou=workstations,ou=systems,",
1415                 "printerRDN"     => "ou=printers,ou=systems,",
1416                 "phoneRDN"       => "ou=phones,ou=systems,",
1417                 "componentRDN"   => "ou=netdevices,ou=systems,",
1418                 "sambaMachineAccountRDN"   => "ou=winstation,",
1420                 "faxBlocklistRDN"   => "ou=gofax,ou=systems,",
1421                 "systemIncomingRDN"    => "ou=incoming,",
1422                 "aclRoleRDN"     => "ou=aclroles,",
1423                 "phoneMacroRDN"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1424                 "phoneConferenceRDN"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1426                 "faiBaseRDN"         => "ou=fai,ou=configs,ou=systems,",
1427                 "faiScriptRDN"   => "ou=scripts,",
1428                 "faiHookRDN"     => "ou=hooks,",
1429                 "faiTemplateRDN" => "ou=templates,",
1430                 "faiVariableRDN" => "ou=variables,",
1431                 "faiProfileRDN"  => "ou=profiles,",
1432                 "faiPackageRDN"  => "ou=packages,",
1433                 "faiPartitionRDN"=> "ou=disk,",
1435                 "sudoRDN"       => "ou=sudoers,",
1437                 "deviceRDN"      => "ou=devices,",
1438                 "mimetypeRDN"    => "ou=mime,");
1440   /* Preset ou... */
1441   if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1442     $ou= $config->get_cfg_value($name);
1443   } elseif (isset($map[$name])) {
1444     $ou = $map[$name];
1445     return($ou);
1446   } else {
1447     trigger_error("No department mapping found for type ".$name);
1448     return "";
1449   }
1450  
1451   if ($ou != ""){
1452     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1453       $ou = @LDAP::convert("ou=$ou");
1454     } else {
1455       $ou = @LDAP::convert("$ou");
1456     }
1458     if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1459       return($ou);
1460     }else{
1461       return("$ou,");
1462     }
1463   
1464   } else {
1465     return "";
1466   }
1470 /*! \brief Get the OU for users 
1471  *
1472  * Frontend for get_ou() with userRDN
1473  * */
1474 function get_people_ou()
1476   return (get_ou("userRDN"));
1480 /*! \brief Get the OU for groups
1481  *
1482  * Frontend for get_ou() with groupRDN
1483  */
1484 function get_groups_ou()
1486   return (get_ou("groupRDN"));
1490 /*! \brief Get the OU for winstations
1491  *
1492  * Frontend for get_ou() with sambaMachineAccountRDN
1493  */
1494 function get_winstations_ou()
1496   return (get_ou("sambaMachineAccountRDN"));
1500 /*! \brief Return a base from a given user DN
1501  *
1502  * \code
1503  * get_base_from_people('cn=Max Muster,dc=local')
1504  * # Result is 'dc=local'
1505  * \endcode
1506  *
1507  * \param string 'dn' a DN
1508  * */
1509 function get_base_from_people($dn)
1511   global $config;
1513   $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1514   $base= preg_replace($pattern, '', $dn);
1516   /* Set to base, if we're not on a correct subtree */
1517   if (!isset($config->idepartments[$base])){
1518     $base= $config->current['BASE'];
1519   }
1521   return ($base);
1525 /*! \brief Check if strict naming rules are configured
1526  *
1527  * Return TRUE or FALSE depending on weither strictNamingRules
1528  * are configured or not.
1529  *
1530  * \return Returns TRUE if strictNamingRules is set to true or if the
1531  * config object is not available, otherwise FALSE.
1532  */
1533 function strict_uid_mode()
1535   global $config;
1537   if (isset($config)){
1538     return ($config->get_cfg_value("strictNamingRules") == "true");
1539   }
1540   return (TRUE);
1544 /*! \brief Get regular expression for checking uids based on the naming
1545  *         rules.
1546  *  \return string Returns the desired regular expression
1547  */
1548 function get_uid_regexp()
1550   /* STRICT adds spaces and case insenstivity to the uid check.
1551      This is dangerous and should not be used. */
1552   if (strict_uid_mode()){
1553     return "^[a-z0-9_-]+$";
1554   } else {
1555     return "^[a-zA-Z0-9 _.-]+$";
1556   }
1560 /*! \brief Generate a lock message
1561  *
1562  * This message shows a warning to the user, that a certain object is locked
1563  * and presents some choices how the user can proceed. By default this
1564  * is 'Cancel' or 'Edit anyway', but depending on the function call
1565  * its possible to allow readonly access, too.
1566  *
1567  * Example usage:
1568  * \code
1569  * if (($user = get_lock($this->dn)) != "") {
1570  *   return(gen_locked_message($user, $this->dn, TRUE));
1571  * }
1572  * \endcode
1573  *
1574  * \param string 'user' the user who holds the lock
1575  * \param string 'dn' the locked DN
1576  * \param boolean 'allow_readonly' TRUE if readonly access should be permitted,
1577  * FALSE if not (default).
1578  *
1579  *
1580  */
1581 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
1583   global $plug, $config;
1585   session::set('dn', $dn);
1586   $remove= false;
1588   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1589   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1591     $LOCK_VARS_USED_GET   = array();
1592     $LOCK_VARS_USED_POST   = array();
1593     $LOCK_VARS_USED_REQUEST   = array();
1594     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1596     foreach($LOCK_VARS_TO_USE as $name){
1598       if(empty($name)){
1599         continue;
1600       }
1602       foreach($_POST as $Pname => $Pvalue){
1603         if(preg_match($name,$Pname)){
1604           $LOCK_VARS_USED_POST[$Pname] = $_POST[$Pname];
1605         }
1606       }
1608       foreach($_GET as $Pname => $Pvalue){
1609         if(preg_match($name,$Pname)){
1610           $LOCK_VARS_USED_GET[$Pname] = $_GET[$Pname];
1611         }
1612       }
1614       foreach($_REQUEST as $Pname => $Pvalue){
1615         if(preg_match($name,$Pname)){
1616           $LOCK_VARS_USED_REQUEST[$Pname] = $_REQUEST[$Pname];
1617         }
1618       }
1619     }
1620     session::set('LOCK_VARS_TO_USE',array());
1621     session::set('LOCK_VARS_USED_GET'  , $LOCK_VARS_USED_GET);
1622     session::set('LOCK_VARS_USED_POST'  , $LOCK_VARS_USED_POST);
1623     session::set('LOCK_VARS_USED_REQUEST'  , $LOCK_VARS_USED_REQUEST);
1624   }
1626   /* Prepare and show template */
1627   $smarty= get_smarty();
1628   $smarty->assign("allow_readonly",$allow_readonly);
1629   if(is_array($dn)){
1630     $msg = "<pre>";
1631     foreach($dn as $sub_dn){
1632       $msg .= "\n".$sub_dn.", ";
1633     }
1634     $msg = preg_replace("/, $/","</pre>",$msg);
1635   }else{
1636     $msg = $dn;
1637   }
1639   $smarty->assign ("dn", $msg);
1640   if ($remove){
1641     $smarty->assign ("action", _("Continue anyway"));
1642   } else {
1643     $smarty->assign ("action", _("Edit anyway"));
1644   }
1645   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1647   return ($smarty->fetch (get_template_path('islocked.tpl')));
1651 /*! \brief Return a string/HTML representation of an array
1652  *
1653  * This returns a string representation of a given value.
1654  * It can be used to dump arrays, where every value is printed
1655  * on its own line. The output is targetted at HTML output, it uses
1656  * '<br>' for line breaks. If the value is already a string its
1657  * returned unchanged.
1658  *
1659  * \param mixed 'value' Whatever needs to be printed.
1660  * \return string
1661  */
1662 function to_string ($value)
1664   /* If this is an array, generate a text blob */
1665   if (is_array($value)){
1666     $ret= "";
1667     foreach ($value as $line){
1668       $ret.= $line."<br>\n";
1669     }
1670     return ($ret);
1671   } else {
1672     return ($value);
1673   }
1677 /*! \brief Return a list of all printers in the current base
1678  *
1679  * Returns an array with the CNs of all printers (objects with
1680  * objectClass gotoPrinter) in the current base.
1681  * ($config->current['BASE']).
1682  *
1683  * Example:
1684  * \code
1685  * $this->printerList = get_printer_list();
1686  * \endcode
1687  *
1688  * \return array an array with the CNs of the printers as key and value. 
1689  * */
1690 function get_printer_list()
1692   global $config;
1693   $res = array();
1694   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1695   foreach($data as $attrs ){
1696     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1697   }
1698   return $res;
1702 /*! \brief Function to rewrite some problematic characters
1703  *
1704  * This function takes a string and replaces all possibly characters in it
1705  * with less problematic characters, as defined in $REWRITE.
1706  *
1707  * \param string 's' the string to rewrite
1708  * \return string 's' the result of the rewrite
1709  * */
1710 function rewrite($s)
1712   global $REWRITE;
1714   foreach ($REWRITE as $key => $val){
1715     $s= str_replace("$key", "$val", $s);
1716   }
1718   return ($s);
1722 /*! \brief Return the base of a given DN
1723  *
1724  * \param string 'dn' a DN
1725  * */
1726 function dn2base($dn)
1728   global $config;
1730   if (get_people_ou() != ""){
1731     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1732   }
1733   if (get_groups_ou() != ""){
1734     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1735   }
1736   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1738   return ($base);
1742 /*! \brief Check if a given command exists and is executable
1743  *
1744  * Test if a given cmdline contains an executable command. Strips
1745  * arguments from the given cmdline.
1746  *
1747  * \param string 'cmdline' the cmdline to check
1748  * \return TRUE if command exists and is executable, otherwise FALSE.
1749  * */
1750 function check_command($cmdline)
1752   $cmd= preg_replace("/ .*$/", "", $cmdline);
1754   /* Check if command exists in filesystem */
1755   if (!file_exists($cmd)){
1756     return (FALSE);
1757   }
1759   /* Check if command is executable */
1760   if (!is_executable($cmd)){
1761     return (FALSE);
1762   }
1764   return (TRUE);
1768 /*! \brief Print plugin HTML header
1769  *
1770  * \param string 'image' the path of the image to be used next to the headline
1771  * \param string 'image' the headline
1772  * \param string 'info' additional information to print
1773  */
1774 function print_header($image, $headline, $info= "")
1776   $display= "<div class=\"plugtop\">\n";
1777   $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";
1778   $display.= "</div>\n";
1780   if ($info != ""){
1781     $display.= "<div class=\"pluginfo\">\n";
1782     $display.= "$info";
1783     $display.= "</div>\n";
1784   } else {
1785     $display.= "<div style=\"height:5px;\">\n";
1786     $display.= "&nbsp;";
1787     $display.= "</div>\n";
1788   }
1789   return ($display);
1793 /*! \brief Print page number selector for paged lists
1794  *
1795  * \param int 'dcnt' Number of entries
1796  * \param int 'start' Page to start
1797  * \param int 'range' Number of entries per page
1798  * \param string 'post_var' POST variable to check for range
1799  */
1800 function range_selector($dcnt,$start,$range=25,$post_var=false)
1803   /* Entries shown left and right from the selected entry */
1804   $max_entries= 10;
1806   /* Initialize and take care that max_entries is even */
1807   $output="";
1808   if ($max_entries & 1){
1809     $max_entries++;
1810   }
1812   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1813     $range= $_POST[$post_var];
1814   }
1816   /* Prevent output to start or end out of range */
1817   if ($start < 0 ){
1818     $start= 0 ;
1819   }
1820   if ($start >= $dcnt){
1821     $start= $range * (int)(($dcnt / $range) + 0.5);
1822   }
1824   $numpages= (($dcnt / $range));
1825   if(((int)($numpages))!=($numpages)){
1826     $numpages = (int)$numpages + 1;
1827   }
1828   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1829     return ("");
1830   }
1831   $ppage= (int)(($start / $range) + 0.5);
1834   /* Align selected page to +/- max_entries/2 */
1835   $begin= $ppage - $max_entries/2;
1836   $end= $ppage + $max_entries/2;
1838   /* Adjust begin/end, so that the selected value is somewhere in
1839      the middle and the size is max_entries if possible */
1840   if ($begin < 0){
1841     $end-= $begin + 1;
1842     $begin= 0;
1843   }
1844   if ($end > $numpages) {
1845     $end= $numpages;
1846   }
1847   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1848     $begin= $end - $max_entries;
1849   }
1851   if($post_var){
1852     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1853       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1854   }else{
1855     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1856   }
1858   /* Draw decrement */
1859   if ($start > 0 ) {
1860     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1861       (($start-$range))."\">".
1862       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1863   }
1865   /* Draw pages */
1866   for ($i= $begin; $i < $end; $i++) {
1867     if ($ppage == $i){
1868       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1869         validate($_GET['plug'])."&amp;start=".
1870         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1871     } else {
1872       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1873         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1874     }
1875   }
1877   /* Draw increment */
1878   if($start < ($dcnt-$range)) {
1879     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1880       (($start+($range)))."\">".
1881       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1882   }
1884   if(($post_var)&&($numpages)){
1885     $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()'>";
1886     foreach(array(20,50,100,200,"all") as $num){
1887       if($num == "all"){
1888         $var = 10000;
1889       }else{
1890         $var = $num;
1891       }
1892       if($var == $range){
1893         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1894       }else{  
1895         $output.="\n<option value='".$var."'>".$num."</option>";
1896       }
1897     }
1898     $output.=  "</select></td></tr></table></div>";
1899   }else{
1900     $output.= "</div>";
1901   }
1903   return($output);
1907 /*! \brief Generate HTML for the 'Apply filter' button */
1908 function apply_filter()
1910   $apply= "";
1912   $apply= ''.
1913     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1914     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1916   return ($apply);
1920 /*! \brief Generate HTML for the 'Back' button */
1921 function back_to_main()
1923   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1924     msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1926   return ($string);
1930 /*! \brief Put netmask in n.n.n.n format
1931  *  \param string 'netmask' The netmask
1932  *  \return string Converted netmask
1933  */
1934 function normalize_netmask($netmask)
1936   /* Check for notation of netmask */
1937   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1938     $num= (int)($netmask);
1939     $netmask= "";
1941     for ($byte= 0; $byte<4; $byte++){
1942       $result=0;
1944       for ($i= 7; $i>=0; $i--){
1945         if ($num-- > 0){
1946           $result+= pow(2,$i);
1947         }
1948       }
1950       $netmask.= $result.".";
1951     }
1953     return (preg_replace('/\.$/', '', $netmask));
1954   }
1956   return ($netmask);
1960 /*! \brief Return the number of set bits in the netmask
1961  *
1962  * For a given subnetmask (for example 255.255.255.0) this returns
1963  * the number of set bits.
1964  *
1965  * Example:
1966  * \code
1967  * $bits = netmask_to_bits('255.255.255.0') # Returns 24
1968  * $bits = netmask_to_bits('255.255.254.0') # Returns 23
1969  * \endcode
1970  *
1971  * Be aware of the fact that the function does not check
1972  * if the given subnet mask is actually valid. For example:
1973  * Bad examples:
1974  * \code
1975  * $bits = netmask_to_bits('255.0.0.255') # Returns 16
1976  * $bits = netmask_to_bits('255.255.0.255') # Returns 24
1977  * \endcode
1978  */
1979 function netmask_to_bits($netmask)
1981   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1982   $res= 0;
1984   for ($n= 0; $n<4; $n++){
1985     $start= 255;
1986     $name= "nm$n";
1988     for ($i= 0; $i<8; $i++){
1989       if ($start == (int)($$name)){
1990         $res+= 8 - $i;
1991         break;
1992       }
1993       $start-= pow(2,$i);
1994     }
1995   }
1997   return ($res);
2001 /*! \brief Recursion helper for gen_id() */
2002 function recurse($rule, $variables)
2004   $result= array();
2006   if (!count($variables)){
2007     return array($rule);
2008   }
2010   reset($variables);
2011   $key= key($variables);
2012   $val= current($variables);
2013   unset ($variables[$key]);
2015   foreach($val as $possibility){
2016     $nrule= str_replace("{$key}", $possibility, $rule);
2017     $result= array_merge($result, recurse($nrule, $variables));
2018   }
2020   return ($result);
2024 /*! \brief Expands user ID based on possible rules
2025  *
2026  *  Unroll given rule string by filling in attributes.
2027  *
2028  * \param string 'rule' The rule string from gosa.conf.
2029  * \param array 'attributes' A dictionary of attribute/value mappings
2030  * \return string Expanded string, still containing the id keyword.
2031  */
2032 function expand_id($rule, $attributes)
2034   /* Check for id rule */
2035   if(preg_match('/^id(:|#|!)\d+$/',$rule)){
2036     return (array("{$rule}"));
2037   }
2039   /* Check for clean attribute */
2040   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
2041     $rule= preg_replace('/^%/', '', $rule);
2042     $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
2043     return (array($val));
2044   }
2046   /* Check for attribute with parameters */
2047   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
2048     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
2049     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
2050     $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
2051     $start= preg_replace ('/-.*$/', '', $param);
2052     $stop = preg_replace ('/^[^-]+-/', '', $param);
2054     /* Assemble results */
2055     $result= array();
2056     for ($i= $start; $i<= $stop; $i++){
2057       $result[]= substr($val, 0, $i);
2058     }
2059     return ($result);
2060   }
2062   echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
2063   return (array($rule));
2067 /*! \brief Generate a list of uid proposals based on a rule
2068  *
2069  *  Unroll given rule string by filling in attributes and replacing
2070  *  all keywords.
2071  *
2072  * \param string 'rule' The rule string from gosa.conf.
2073  * \param array 'attributes' A dictionary of attribute/value mappings
2074  * \return array List of valid not used uids
2075  */
2076 function gen_uids($rule, $attributes)
2078   global $config;
2080   /* Search for keys and fill the variables array with all 
2081      possible values for that key. */
2082   $part= "";
2083   $trigger= false;
2084   $stripped= "";
2085   $variables= array();
2087   for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
2089     if ($rule[$pos] == "{" ){
2090       $trigger= true;
2091       $part= "";
2092       continue;
2093     }
2095     if ($rule[$pos] == "}" ){
2096       $variables[$pos]= expand_id($part, $attributes);
2097       $stripped.= "{".$pos."}";
2098       $trigger= false;
2099       continue;
2100     }
2102     if ($trigger){
2103       $part.= $rule[$pos];
2104     } else {
2105       $stripped.= $rule[$pos];
2106     }
2107   }
2109   /* Recurse through all possible combinations */
2110   $proposed= recurse($stripped, $variables);
2112   /* Get list of used ID's */
2113   $ldap= $config->get_ldap_link();
2114   $ldap->cd($config->current['BASE']);
2116   /* Remove used uids and watch out for id tags */
2117   $ret= array();
2118   foreach($proposed as $uid){
2120     /* Check for id tag and modify uid if needed */
2121     if(preg_match('/\{id(:|!)\d+}/',$uid, $m)){
2122       $size= preg_replace('/^.*{id(:|!)(\d+)}.*$/', '\\2', $uid);
2124       $start= $m[1]==":"?0:-1;
2125       for ($i= $start, $p= pow(10,$size)-1; $i < $p; $i++){
2126         if ($i == -1) {
2127           $number= "";
2128         } else {
2129           $number= sprintf("%0".$size."d", $i+1);
2130         }
2131         $res= preg_replace('/{id(:|!)\d+}/', $number, $uid);
2133         $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
2134         if($ldap->count() == 0){
2135           $uid= $res;
2136           break;
2137         }
2138       }
2140       /* Remove link if nothing has been found */
2141       $uid= preg_replace('/{id(:|!)\d+}/', '', $uid);
2142     }
2144     if(preg_match('/\{id#\d+}/',$uid)){
2145       $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
2147       while (true){
2148         mt_srand((double) microtime()*1000000);
2149         $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
2150         $res= preg_replace('/{id#(\d+)}/', $number, $uid);
2151         $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
2152         if($ldap->count() == 0){
2153           $uid= $res;
2154           break;
2155         }
2156       }
2158       /* Remove link if nothing has been found */
2159       $uid= preg_replace('/{id#\d+}/', '', $uid);
2160     }
2162     /* Don't assign used ones */
2163     $ldap->search("(uid=".preg_replace('/[{}]/', '', $uid).")",array('dn'));
2164     if($ldap->count() == 0){
2165       /* Add uid, but remove {} first. These are invalid anyway. */
2166       $ret[]= preg_replace('/[{}]/', '', $uid);
2167     }
2168   }
2170   return(array_unique($ret));
2174 /*! \brief Convert various data sizes to bytes
2175  *
2176  * Given a certain value in the format n(g|m|k), where n
2177  * is a value and (g|m|k) stands for Gigabyte, Megabyte and Kilobyte
2178  * this function returns the byte value.
2179  *
2180  * \param string 'value' a value in the above specified format
2181  * \return a byte value or the original value if specified string is simply
2182  * a numeric value
2183  *
2184  */
2185 function to_byte($value) {
2186   $value= strtolower(trim($value));
2188   if(!is_numeric(substr($value, -1))) {
2190     switch(substr($value, -1)) {
2191       case 'g':
2192         $mult= 1073741824;
2193         break;
2194       case 'm':
2195         $mult= 1048576;
2196         break;
2197       case 'k':
2198         $mult= 1024;
2199         break;
2200     }
2202     return ($mult * (int)substr($value, 0, -1));
2203   } else {
2204     return $value;
2205   }
2209 /*! \brief Check if a value exists in an array (case-insensitive)
2210  * 
2211  * This is just as http://php.net/in_array except that the comparison
2212  * is case-insensitive.
2213  *
2214  * \param string 'value' needle
2215  * \param array 'items' haystack
2216  */ 
2217 function in_array_ics($value, $items)
2219         return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
2223 /*! \brief Generate a clickable alphabet */
2224 function generate_alphabet($count= 10)
2226   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
2227   $alphabet= "";
2228   $c= 0;
2230   /* Fill cells with charaters */
2231   for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
2232     if ($c == 0){
2233       $alphabet.= "<tr>";
2234     }
2236     $ch = mb_substr($characters, $i, 1, "UTF8");
2237     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
2238       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
2240     if ($c++ == $count){
2241       $alphabet.= "</tr>";
2242       $c= 0;
2243     }
2244   }
2246   /* Fill remaining cells */
2247   while ($c++ <= $count){
2248     $alphabet.= "<td>&nbsp;</td>";
2249   }
2251   return ($alphabet);
2255 /*! \brief Removes malicious characters from a (POST) string. */
2256 function validate($string)
2258   return (strip_tags(str_replace('\0', '', $string)));
2262 /*! \brief Evaluate the current GOsa version from the build in revision string */
2263 function get_gosa_version()
2265   global $svn_revision, $svn_path;
2267   /* Extract informations */
2268   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
2270   /* Release or development? */
2271   if (preg_match('%/gosa/trunk/%', $svn_path)){
2272     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
2273   } else {
2274     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
2275     return (sprintf(_("GOsa $release"), $revision));
2276   }
2280 /*! \brief Recursively delete a path in the file system
2281  *
2282  * Will delete the given path and all its files recursively.
2283  * Can also follow links if told so.
2284  *
2285  * \param string 'path'
2286  * \param boolean 'followLinks' TRUE to follow links, FALSE (default)
2287  * for not following links
2288  */
2289 function rmdirRecursive($path, $followLinks=false) {
2290   $dir= opendir($path);
2291   while($entry= readdir($dir)) {
2292     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
2293       unlink($path."/".$entry);
2294     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
2295       rmdirRecursive($path."/".$entry);
2296     }
2297   }
2298   closedir($dir);
2299   return rmdir($path);
2303 /*! \brief Get directory content information
2304  *
2305  * Returns the content of a directory as an array in an
2306  * ascended sorted manner.
2307  *
2308  * \param string 'path'
2309  * \param boolean weither to sort the content descending.
2310  */
2311 function scan_directory($path,$sort_desc=false)
2313   $ret = false;
2315   /* is this a dir ? */
2316   if(is_dir($path)) {
2318     /* is this path a readable one */
2319     if(is_readable($path)){
2321       /* Get contents and write it into an array */   
2322       $ret = array();    
2324       $dir = opendir($path);
2326       /* Is this a correct result ?*/
2327       if($dir){
2328         while($fp = readdir($dir))
2329           $ret[]= $fp;
2330       }
2331     }
2332   }
2333   /* Sort array ascending , like scandir */
2334   sort($ret);
2336   /* Sort descending if parameter is sort_desc is set */
2337   if($sort_desc) {
2338     $ret = array_reverse($ret);
2339   }
2341   return($ret);
2345 /*! \brief Clean the smarty compile dir */
2346 function clean_smarty_compile_dir($directory)
2348   global $svn_revision;
2350   if(is_dir($directory) && is_readable($directory)) {
2351     // Set revision filename to REVISION
2352     $revision_file= $directory."/REVISION";
2354     /* Is there a stamp containing the current revision? */
2355     if(!file_exists($revision_file)) {
2356       // create revision file
2357       create_revision($revision_file, $svn_revision);
2358     } else {
2359       # check for "$config->...['CONFIG']/revision" and the
2360       # contents should match the revision number
2361       if(!compare_revision($revision_file, $svn_revision)){
2362         // If revision differs, clean compile directory
2363         foreach(scan_directory($directory) as $file) {
2364           if(($file==".")||($file=="..")) continue;
2365           if( is_file($directory."/".$file) &&
2366               is_writable($directory."/".$file)) {
2367             // delete file
2368             if(!unlink($directory."/".$file)) {
2369               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
2370               // This should never be reached
2371             }
2372           } elseif(is_dir($directory."/".$file) &&
2373               is_writable($directory."/".$file)) {
2374             // Just recursively delete it
2375             rmdirRecursive($directory."/".$file);
2376           }
2377         }
2378         // We should now create a fresh revision file
2379         clean_smarty_compile_dir($directory);
2380       } else {
2381         // Revision matches, nothing to do
2382       }
2383     }
2384   } else {
2385     // Smarty compile dir is not accessible
2386     // (Smarty will warn about this)
2387   }
2391 function create_revision($revision_file, $revision)
2393   $result= false;
2395   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2396     if($fh= fopen($revision_file, "w")) {
2397       if(fwrite($fh, $revision)) {
2398         $result= true;
2399       }
2400     }
2401     fclose($fh);
2402   } else {
2403     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2404   }
2406   return $result;
2410 function compare_revision($revision_file, $revision)
2412   // false means revision differs
2413   $result= false;
2415   if(file_exists($revision_file) && is_readable($revision_file)) {
2416     // Open file
2417     if($fh= fopen($revision_file, "r")) {
2418       // Compare File contents with current revision
2419       if($revision == fread($fh, filesize($revision_file))) {
2420         $result= true;
2421       }
2422     } else {
2423       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2424     }
2425     // Close file
2426     fclose($fh);
2427   }
2429   return $result;
2433 /*! \brief Return HTML for a progressbar
2434  *
2435  * \code
2436  * $smarty->assign("installprogress", progressbar($current_progress_in_percent),100,15,true); 
2437  * \endcode
2438  *
2439  * \param int 'percentage' Value to display
2440  * \param int 'width' width of the resulting output
2441  * \param int 'height' height of the resulting output
2442  * \param boolean 'showvalue' weither to show the percentage in the progressbar or not
2443  * */
2444 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2446   return("<img src='progress.php?x=$width&amp;y=$height&amp;p=$percentage'>");
2450 /*! \brief Lookup a key in an array case-insensitive
2451  *
2452  * Given an associative array this can lookup the value of
2453  * a certain key, regardless of the case.
2454  *
2455  * \code
2456  * $items = array ('FOO' => 'blub', 'bar' => 'blub');
2457  * array_key_ics('foo', $items); # Returns 'blub'
2458  * array_key_ics('BAR', $items); # Returns 'blub'
2459  * \endcode
2460  *
2461  * \param string 'key' needle
2462  * \param array 'items' haystack
2463  */
2464 function array_key_ics($ikey, $items)
2466   $tmp= array_change_key_case($items, CASE_LOWER);
2467   $ikey= strtolower($ikey);
2468   if (isset($tmp[$ikey])){
2469     return($tmp[$ikey]);
2470   }
2472   return ('');
2476 /*! \brief Determine if two arrays are different
2477  *
2478  * \param array 'src'
2479  * \param array 'dst'
2480  * \return boolean TRUE or FALSE
2481  * */
2482 function array_differs($src, $dst)
2484   /* If the count is differing, the arrays differ */
2485   if (count ($src) != count ($dst)){
2486     return (TRUE);
2487   }
2489   return (count(array_diff($src, $dst)) != 0);
2493 function saveFilter($a_filter, $values)
2495   if (isset($_POST['regexit'])){
2496     $a_filter["regex"]= $_POST['regexit'];
2498     foreach($values as $type){
2499       if (isset($_POST[$type])) {
2500         $a_filter[$type]= "checked";
2501       } else {
2502         $a_filter[$type]= "";
2503       }
2504     }
2505   }
2507   /* React on alphabet links if needed */
2508   if (isset($_GET['search'])){
2509     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2510     if ($s == "**"){
2511       $s= "*";
2512     }
2513     $a_filter['regex']= $s;
2514   }
2516   return ($a_filter);
2520 /*! \brief Escape all LDAP filter relevant characters */
2521 function normalizeLdap($input)
2523   return (addcslashes($input, '()|'));
2527 /*! \brief Return the gosa base directory */
2528 function get_base_dir()
2530   global $BASE_DIR;
2532   return $BASE_DIR;
2536 /*! \brief Test weither we are allowed to read the object */
2537 function obj_is_readable($dn, $object, $attribute)
2539   global $ui;
2541   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2545 /*! \brief Test weither we are allowed to change the object */
2546 function obj_is_writable($dn, $object, $attribute)
2548   global $ui;
2550   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2554 /*! \brief Explode a DN into its parts
2555  *
2556  * Similar to explode (http://php.net/explode), but a bit more specific
2557  * for the needs when splitting, exploding LDAP DNs.
2558  *
2559  * \param string 'dn' the DN to split
2560  * \param config-object a config object. only neeeded if DN shall be verified in the LDAP
2561  * \param boolean verify_in_ldap check weither DN is valid
2562  *
2563  */
2564 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2566   /* Initialize variables */
2567   $ret  = array("count" => 0);  // Set count to 0
2568   $next = true;                 // if false, then skip next loops and return
2569   $cnt  = 0;                    // Current number of loops
2570   $max  = 100;                  // Just for security, prevent looops
2571   $ldap = NULL;                 // To check if created result a valid
2572   $keep = "";                   // save last failed parse string
2574   /* Check each parsed dn in ldap ? */
2575   if($config!==NULL && $verify_in_ldap){
2576     $ldap = $config->get_ldap_link();
2577   }
2579   /* Lets start */
2580   $called = false;
2581   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2583     $cnt ++;
2584     if(!preg_match("/,/",$dn)){
2585       $next = false;
2586     }
2587     $object = preg_replace("/[,].*$/","",$dn);
2588     $dn     = preg_replace("/^[^,]+,/","",$dn);
2590     $called = true;
2592     /* Check if current dn is valid */
2593     if($ldap!==NULL){
2594       $ldap->cd($dn);
2595       $ldap->cat($dn,array("dn"));
2596       if($ldap->count()){
2597         $ret[]  = $keep.$object;
2598         $keep   = "";
2599       }else{
2600         $keep  .= $object.",";
2601       }
2602     }else{
2603       $ret[]  = $keep.$object;
2604       $keep   = "";
2605     }
2606   }
2608   /* No dn was posted */
2609   if($cnt == 0 && !empty($dn)){
2610     $ret[] = $dn;
2611   }
2613   /* Append the rest */
2614   $test = $keep.$dn;
2615   if($called && !empty($test)){
2616     $ret[] = $keep.$dn;
2617   }
2618   $ret['count'] = count($ret) - 1;
2620   return($ret);
2624 function get_base_from_hook($dn, $attrib)
2626   global $config;
2628   if ($config->get_cfg_value("baseIdHook") != ""){
2629     
2630     /* Call hook script - if present */
2631     $command= $config->get_cfg_value("baseIdHook");
2633     if ($command != ""){
2634       $command.= " '".LDAP::fix($dn)."' $attrib";
2635       if (check_command($command)){
2636         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2637         exec($command, $output);
2638         if (preg_match("/^[0-9]+$/", $output[0])){
2639           return ($output[0]);
2640         } else {
2641           msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2642           return ($config->get_cfg_value("uidNumberBase"));
2643         }
2644       } else {
2645         msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2646         return ($config->get_cfg_value("uidNumberBase"));
2647       }
2649     } else {
2651       msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2652       return ($config->get_cfg_value("uidNumberBase"));
2654     }
2655   }
2659 /*! \brief Check if schema version matches the requirements */
2660 function check_schema_version($class, $version)
2662   return preg_match("/\(v$version\)/", $class['DESC']);
2666 /*! \brief Check if LDAP schema matches the requirements */
2667 function check_schema($cfg,$rfc2307bis = FALSE)
2669   $messages= array();
2671   /* Get objectclasses */
2672   $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2673   $objectclasses = $ldap->get_objectclasses();
2674   if(count($objectclasses) == 0){
2675     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2676   }
2678   /* This is the default block used for each entry.
2679    *  to avoid unset indexes.
2680    */
2681   $def_check = array("REQUIRED_VERSION" => "0",
2682       "SCHEMA_FILES"     => array(),
2683       "CLASSES_REQUIRED" => array(),
2684       "STATUS"           => FALSE,
2685       "IS_MUST_HAVE"     => FALSE,
2686       "MSG"              => "",
2687       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2689   /* The gosa base schema */
2690   $checks['gosaObject'] = $def_check;
2691   $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2692   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa-samba3.schema","gosa-samba2.schema");
2693   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2694   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2696   /* GOsa Account class */
2697   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.6";
2698   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa-samba3.schema","gosa-samba2.schema");
2699   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2700   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2701   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2703   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2704   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2705   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa-samba3.schema","gosa-samba2.schema");
2706   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2707   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2708   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2710   /* Some other checks */
2711   foreach(array(
2712         "gosaCacheEntry"        => array("version" => "2.6.1", "class" => "gosaAccount"),
2713         "gosaDepartment"        => array("version" => "2.6.1", "class" => "gosaAccount"),
2714         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2715         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2716         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2717         "gosaUserTemplate"      => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2718         "gosaMailAccount"       => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa-samba3.schema"),
2719         "gosaProxyAccount"      => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa-samba3.schema"),
2720         "gosaApplication"       => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2721         "gosaApplicationGroup"  => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2722         "GOhard"                => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2723         "gotoTerminal"          => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2724         "goServer"              => array("version" => "2.6.1", "class" => "server","file" => "goserver.schema"),
2725         "goTerminalServer"      => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2726         "goShareServer"         => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2727         "goNtpServer"           => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2728         "goSyslogServer"        => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2729         "goLdapServer"          => array("version" => "2.6.1", "class" => "goServer"),
2730         "goCupsServer"          => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2731         "goImapServer"          => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa-samba3.schema"),
2732         "goKrbServer"           => array("version" => "2.6.1", "class" => "goServer"),
2733         "goFaxServer"           => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2734         ) as $name => $values){
2736           $checks[$name] = $def_check;
2737           if(isset($values['version'])){
2738             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2739           }
2740           if(isset($values['file'])){
2741             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2742           }
2743           if (isset($values['class'])) {
2744             $checks[$name]["CLASSES_REQUIRED"] = is_array($values['class'])?$values['class']:array($values['class']);
2745           }
2746         }
2747   foreach($checks as $name => $value){
2748     foreach($value['CLASSES_REQUIRED'] as $class){
2750       if(!isset($objectclasses[$name])){
2751         if($value['IS_MUST_HAVE']){
2752           $checks[$name]['STATUS'] = FALSE;
2753           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2754         } else {
2755           $checks[$name]['STATUS'] = TRUE;
2756           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2757         }
2758       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2759         $checks[$name]['STATUS'] = FALSE;
2761         $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2762       }else{
2763         $checks[$name]['STATUS'] = TRUE;
2764         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2765       }
2766     }
2767   }
2769   $tmp = $objectclasses;
2771   /* The gosa base schema */
2772   $checks['posixGroup'] = $def_check;
2773   $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2774   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa-samba3.schema","gosa-samba2.schema");
2775   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2776   $checks['posixGroup']['STATUS']           = TRUE;
2777   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2778   $checks['posixGroup']['MSG']              = "";
2779   $checks['posixGroup']['INFO']             = "";
2781   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2782   if(isset($tmp['posixGroup'])){
2784     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2785       $checks['posixGroup']['STATUS']           = FALSE;
2786       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2787       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2788     }
2789     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2790       $checks['posixGroup']['STATUS']           = FALSE;
2791       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2792       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2793     }
2794   }
2796   return($checks);
2800 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2802   $tmp = array(
2803         "de_DE" => "German",
2804         "fr_FR" => "French",
2805         "it_IT" => "Italian",
2806         "es_ES" => "Spanish",
2807         "en_US" => "English",
2808         "nl_NL" => "Dutch",
2809         "pl_PL" => "Polish",
2810         #"sv_SE" => "Swedish",
2811         "zh_CN" => "Chinese",
2812         "vi_VN" => "Vietnamese",
2813         "ru_RU" => "Russian");
2814   
2815   $tmp2= array(
2816         "de_DE" => _("German"),
2817         "fr_FR" => _("French"),
2818         "it_IT" => _("Italian"),
2819         "es_ES" => _("Spanish"),
2820         "en_US" => _("English"),
2821         "nl_NL" => _("Dutch"),
2822         "pl_PL" => _("Polish"),
2823         #"sv_SE" => _("Swedish"),
2824         "zh_CN" => _("Chinese"),
2825         "vi_VN" => _("Vietnamese"),
2826         "ru_RU" => _("Russian"));
2828   $ret = array();
2829   if($languages_in_own_language){
2831     $old_lang = setlocale(LC_ALL, 0);
2833     /* If the locale wasn't correclty set before, there may be an incorrect
2834         locale returned. Something like this: 
2835           C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2836         Extract the locale name from this string and use it to restore old locale.
2837      */
2838     if(preg_match("/LC_CTYPE/",$old_lang)){
2839       $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2840     }
2841     
2842     foreach($tmp as $key => $name){
2843       $lang = $key.".UTF-8";
2844       setlocale(LC_ALL, $lang);
2845       if($strip_region_tag){
2846         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2847       }else{
2848         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2849       }
2850     }
2851     setlocale(LC_ALL, $old_lang);
2852   }else{
2853     foreach($tmp as $key => $name){
2854       if($strip_region_tag){
2855         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2856       }else{
2857         $ret[$key] = _($name);
2858       }
2859     }
2860   }
2861   return($ret);
2865 /*! \brief Returns contents of the given POST variable and check magic quotes settings
2866  *
2867  * Depending on the magic quotes settings this returns a stripclashed'ed version of
2868  * a certain POST variable.
2869  *
2870  * \param string 'name' the POST var to return ($_POST[$name])
2871  * \return string
2872  * */
2873 function get_post($name)
2875   if(!isset($_POST[$name])){
2876     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2877     return(FALSE);
2878   }
2880   if(get_magic_quotes_gpc()){
2881     return(stripcslashes(validate($_POST[$name])));
2882   }else{
2883     return(validate($_POST[$name]));
2884   }
2888 /*! \brief Return class name in correct case */
2889 function get_correct_class_name($cls)
2891   global $class_mapping;
2892   if(isset($class_mapping) && is_array($class_mapping)){
2893     foreach($class_mapping as $class => $file){
2894       if(preg_match("/^".$cls."$/i",$class)){
2895         return($class);
2896       }
2897     }
2898   }
2899   return(FALSE);
2903 /*! \brief Change the password of a given DN
2904  * 
2905  * Change the password of a given DN with the specified hash.
2906  *
2907  * \param string 'dn' the DN whose password shall be changed
2908  * \param string 'password' the password
2909  * \param int mode
2910  * \param string 'hash' which hash to use to encrypt it, default is empty
2911  * for cleartext storage.
2912  * \return boolean TRUE on success FALSE on error
2913  */
2914 function change_password ($dn, $password, $mode=0, $hash= "")
2916   global $config;
2917   $newpass= "";
2919   /* Convert to lower. Methods are lowercase */
2920   $hash= strtolower($hash);
2922   // Get all available encryption Methods
2924   // NON STATIC CALL :)
2925   $methods = new passwordMethod(session::get('config'));
2926   $available = $methods->get_available_methods();
2928   // read current password entry for $dn, to detect the encryption Method
2929   $ldap       = $config->get_ldap_link();
2930   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2931   $attrs      = $ldap->fetch ();
2933   /* Is ensure that clear passwords will stay clear */
2934   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2935     $hash = "clear";
2936   }
2938   // Detect the encryption Method
2939   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2941     /* Check for supported algorithm */
2942     mt_srand((double) microtime()*1000000);
2944     /* Extract used hash */
2945     if ($hash == ""){
2946       $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2947     } else {
2948       $test = new $available[$hash]($config,$dn);
2949       $test->set_hash($hash);
2950     }
2952   } else {
2953     // User MD5 by default
2954     $hash= "md5";
2955     $test = new  $available['md5']($config);
2956   }
2958   if($test instanceOf passwordMethod){
2960     $deactivated = $test->is_locked($config,$dn);
2962     /* Feed password backends with information */
2963     $test->dn= $dn;
2964     $test->attrs= $attrs;
2965     $newpass= $test->generate_hash($password);
2967     // Update shadow timestamp?
2968     if (isset($attrs["shadowLastChange"][0])){
2969       $shadow= (int)(date("U") / 86400);
2970     } else {
2971       $shadow= 0;
2972     }
2974     // Write back modified entry
2975     $ldap->cd($dn);
2976     $attrs= array();
2978     // Not for groups
2979     if ($mode == 0){
2981       if ($shadow != 0){
2982         $attrs['shadowLastChange']= $shadow;
2983       }
2985       // Create SMB Password
2986       $attrs= generate_smb_nt_hash($password);
2987     }
2989     $attrs['userPassword']= array();
2990     $attrs['userPassword']= $newpass;
2992     $ldap->modify($attrs);
2994     /* Read ! if user was deactivated */
2995     if($deactivated){
2996       $test->lock_account($config,$dn);
2997     }
2999     new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
3001     if (!$ldap->success()) {
3002       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
3003     } else {
3005       /* Run backend method for change/create */
3006       if(!$test->set_password($password)){
3007         return(FALSE);
3008       }
3010       /* Find postmodify entries for this class */
3011       $command= $config->search("password", "POSTMODIFY",array('menu'));
3013       if ($command != ""){
3014         /* Walk through attribute list */
3015         $command= preg_replace("/%userPassword/", $password, $command);
3016         $command= preg_replace("/%dn/", $dn, $command);
3018         if (check_command($command)){
3019           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
3020           exec($command);
3021         } else {
3022           $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
3023           msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
3024         }
3025       }
3026     }
3027     return(TRUE);
3028   }
3032 /*! \brief Generate samba hashes
3033  *
3034  * Given a certain password this constructs an array like
3035  * array['sambaLMPassword'] etc.
3036  *
3037  * \param string 'password'
3038  * \return array contains several keys for lmPassword, ntPassword, pwdLastSet, etc. depending
3039  * on the samba version
3040  */
3041 function generate_smb_nt_hash($password)
3043   global $config;
3045   # Try to use gosa-si?
3046   if ($config->get_cfg_value("gosaSupportURI") != ""){
3047         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
3048     if (isset($res['XML']['HASH'])){
3049         $hash= $res['XML']['HASH'];
3050     } else {
3051       $hash= "";
3052     }
3054     if ($hash == "") {
3055       msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
3056       return ("");
3057     }
3058   } else {
3059           $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
3060           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
3062           exec($tmp, $ar);
3063           flush();
3064           reset($ar);
3065           $hash= current($ar);
3067     if ($hash == "") {
3068       msg_dialog::display(_("Configuration error"), sprintf(_("Cannot generate samba hash: running '%s' failed, check the 'sambaHashHook'!"),$config->get_cfg_value('sambaHashHook')), ERROR_DIALOG);
3069       return ("");
3070     }
3071   }
3073   list($lm,$nt)= split (":", trim($hash));
3075   $attrs['sambaLMPassword']= $lm;
3076   $attrs['sambaNTPassword']= $nt;
3077   $attrs['sambaPwdLastSet']= date('U');
3078   $attrs['sambaBadPasswordCount']= "0";
3079   $attrs['sambaBadPasswordTime']= "0";
3080   return($attrs);
3084 /*! \brief Get the Change Sequence Number of a certain DN
3085  *
3086  * To verify if a given object has been changed outside of Gosa
3087  * in the meanwhile, this function can be used to get the entryCSN
3088  * from the LDAP directory. It uses the attribute as configured
3089  * in modificationDetectionAttribute
3090  *
3091  * \param string 'dn'
3092  * \return either the result or "" in any other case
3093  */
3094 function getEntryCSN($dn)
3096   global $config;
3097   if(empty($dn) || !is_object($config)){
3098     return("");
3099   }
3101   /* Get attribute that we should use as serial number */
3102   $attr= $config->get_cfg_value("modificationDetectionAttribute");
3103   if($attr != ""){
3104     $ldap = $config->get_ldap_link();
3105     $ldap->cat($dn,array($attr));
3106     $csn = $ldap->fetch();
3107     if(isset($csn[$attr][0])){
3108       return($csn[$attr][0]);
3109     }
3110   }
3111   return("");
3115 /*! \brief Add (a) given objectClass(es) to an attrs entry
3116  * 
3117  * The function adds the specified objectClass(es) to the given
3118  * attrs entry.
3119  *
3120  * \param mixed 'classes' Either a single objectClass or several objectClasses
3121  * as an array
3122  * \param array 'attrs' The attrs array to be modified.
3123  *
3124  * */
3125 function add_objectClass($classes, &$attrs)
3127   if (is_array($classes)){
3128     $list= $classes;
3129   } else {
3130     $list= array($classes);
3131   }
3133   foreach ($list as $class){
3134     $attrs['objectClass'][]= $class;
3135   }
3139 /*! \brief Removes a given objectClass from the attrs entry
3140  *
3141  * Similar to add_objectClass, except that it removes the given
3142  * objectClasses. See it for the params.
3143  * */
3144 function remove_objectClass($classes, &$attrs)
3146   if (isset($attrs['objectClass'])){
3147     /* Array? */
3148     if (is_array($classes)){
3149       $list= $classes;
3150     } else {
3151       $list= array($classes);
3152     }
3154     $tmp= array();
3155     foreach ($attrs['objectClass'] as $oc) {
3156       foreach ($list as $class){
3157         if (strtolower($oc) != strtolower($class)){
3158           $tmp[]= $oc;
3159         }
3160       }
3161     }
3162     $attrs['objectClass']= $tmp;
3163   }
3167 /*! \brief  Initialize a file download with given content, name and data type. 
3168  *  \param  string data The content to send.
3169  *  \param  string name The name of the file.
3170  *  \param  string type The content identifier, default value is "application/octet-stream";
3171  */
3172 function send_binary_content($data,$name,$type = "application/octet-stream")
3174   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
3175   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
3176   header("Cache-Control: no-cache");
3177   header("Pragma: no-cache");
3178   header("Cache-Control: post-check=0, pre-check=0");
3179   header("Content-type: ".$type."");
3181   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
3183   /* Strip name if it is a complete path */
3184   if (preg_match ("/\//", $name)) {
3185         $name= basename($name);
3186   }
3187   
3188   /* force download dialog */
3189   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
3190     header('Content-Disposition: filename="'.$name.'"');
3191   } else {
3192     header('Content-Disposition: attachment; filename="'.$name.'"');
3193   }
3195   echo $data;
3196   exit();
3200 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
3202   if(is_string($str)){
3203     return(htmlentities($str,$type,$charset));
3204   }elseif(is_array($str)){
3205     foreach($str as $name => $value){
3206       $str[$name] = reverse_html_entities($value,$type,$charset);
3207     }
3208   }
3209   return($str);
3213 /*! \brief Encode special string characters so we can use the string in \
3214            HTML output, without breaking quotes.
3215     \param string The String we want to encode.
3216     \return string The encoded String
3217  */
3218 function xmlentities($str)
3219
3220   if(is_string($str)){
3222     static $asc2uni= array();
3223     if (!count($asc2uni)){
3224       for($i=128;$i<256;$i++){
3225     #    $asc2uni[chr($i)] = "&#x".dechex($i).";";
3226       }
3227     }
3229     $str = str_replace("&", "&amp;", $str);
3230     $str = str_replace("<", "&lt;", $str);
3231     $str = str_replace(">", "&gt;", $str);
3232     $str = str_replace("'", "&apos;", $str);
3233     $str = str_replace("\"", "&quot;", $str);
3234     $str = str_replace("\r", "", $str);
3235     $str = strtr($str,$asc2uni);
3236     return $str;
3237   }elseif(is_array($str)){
3238     foreach($str as $name => $value){
3239       $str[$name] = xmlentities($value);
3240     }
3241   }
3242   return($str);
3246 /*! \brief  Updates all accessTo attributes from a given value to a new one.
3247             For example if a host is renamed.
3248     \param  String  $from The source accessTo name.
3249     \param  String  $to   The destination accessTo name.
3250 */
3251 function update_accessTo($from,$to)
3253   global $config;
3254   $ldap = $config->get_ldap_link();
3255   $ldap->cd($config->current['BASE']);
3256   $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
3257   while($attrs = $ldap->fetch()){
3258     $new_attrs = array("accessTo" => array());
3259     $dn = $attrs['dn'];
3260     for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
3261       $new_attrs['objectClass'][] =  $attrs['objectClass'][$i];
3262     }
3263     for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
3264       if($attrs['accessTo'][$i] == $from){
3265         if(!empty($to)){
3266           $new_attrs['accessTo'][] =  $to;
3267         }
3268       }else{
3269         $new_attrs['accessTo'][] =  $attrs['accessTo'][$i]; 
3270       }
3271     }
3272     $ldap->cd($dn);
3273     $ldap->modify($new_attrs);
3274     if (!$ldap->success()){
3275       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
3276     }
3277     new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
3278   }
3282 /*! \brief Returns a random char */
3283 function get_random_char () {
3284      $randno = rand (0, 63);
3285      if ($randno < 12) {
3286          return (chr ($randno + 46)); // Digits, '/' and '.'
3287      } else if ($randno < 38) {
3288          return (chr ($randno + 53)); // Uppercase
3289      } else {
3290          return (chr ($randno + 59)); // Lowercase
3291      }
3295 function cred_encrypt($input, $password) {
3297   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3298   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3300   return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
3305 function cred_decrypt($input,$password) {
3306   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3307   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3309   return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
3313 function get_object_info()
3315   return(session::get('objectinfo'));
3319 function set_object_info($str = "")
3321   session::set('objectinfo',$str);
3325 function isIpInNet($ip, $net, $mask) {
3326    // Move to long ints
3327    $ip= ip2long($ip);
3328    $net= ip2long($net);
3329    $mask= ip2long($mask);
3331    // Mask given IP with mask. If it returns "net", we're in...
3332    $res= $ip & $mask;
3334    return ($res == $net);
3338 function get_next_id($attrib, $dn)
3340   global $config;
3342   switch ($config->get_cfg_value("idAllocationMethod", "traditional")){
3343     case "pool":
3344       return get_next_id_pool($attrib);
3345     case "traditional":
3346       return get_next_id_traditional($attrib, $dn);
3347   }
3349   msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("unknown idAllocation method!"), ERROR_DIALOG);
3350   return null;
3354 function get_next_id_pool($attrib) {
3355   global $config;
3357   /* Fill informational values */
3358   $min= $config->get_cfg_value("${attrib}PoolMin", 10000);
3359   $max= $config->get_cfg_value("${attrib}PoolMax", 40000);
3361   /* Sanity check */
3362   if ($min >= $max) {
3363     msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." ".sprintf(_("%sPoolMin >= %sPoolMax!"), $attrib), ERROR_DIALOG);
3364     return null;
3365   }
3367   /* ID to skip */
3368   $ldap= $config->get_ldap_link();
3369   $id= null;
3371   /* Try to allocate the ID several times before failing */
3372   $tries= 3;
3373   while ($tries--) {
3375     /* Look for ID map entry */
3376     $ldap->cd ($config->current['BASE']);
3377     $ldap->search ("(&(objectClass=sambaUnixIdPool)($attrib=*))", array("$attrib"));
3379     /* If it does not exist, create one with these defaults */
3380     if ($ldap->count() == 0) {
3381       /* Fill informational values */
3382       $minUserId= $config->get_cfg_value("uidPoolMin", 10000);
3383       $minGroupId= $config->get_cfg_value("gidPoolMin", 10000);
3385       /* Add as default */
3386       $attrs= array("objectClass" => array("organizationalUnit", "sambaUnixIdPool"));
3387       $attrs["ou"]= "idmap";
3388       $attrs["uidNumber"]= $minUserId;
3389       $attrs["gidNumber"]= $minGroupId;
3390       $ldap->cd("ou=idmap,".$config->current['BASE']);
3391       $ldap->add($attrs);
3392       if ($ldap->error != "Success") {
3393         msg_dialog::display(_("Error"), _("Cannot create sambaUnixIdPool entry!"), ERROR_DIALOG);
3394         return null;
3395       }
3396       $tries++;
3397       continue;
3398     }
3399     /* Bail out if it's not unique */
3400     if ($ldap->count() != 1) {
3401       msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("sambaUnixIdPool is not unique!"), ERROR_DIALOG);
3402       return null;
3403     }
3405     /* Store old attrib and generate new */
3406     $attrs= $ldap->fetch();
3407     $dn= $ldap->getDN();
3408     $oldAttr= $attrs[$attrib][0];
3409     $newAttr= $oldAttr + 1;
3411     /* Sanity check */
3412     if ($newAttr >= $max) {
3413       msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("no ID available!"), ERROR_DIALOG);
3414       return null;
3415     }
3416     if ($newAttr < $min) {
3417       msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("no ID available!"), ERROR_DIALOG);
3418       return null;
3419     }
3421     #FIXME: PHP is not able to do a modification of "del: .../add: ...", so this
3422     #       is completely unsafe in the moment.
3423     #/* Remove old attr, add new attr */
3424     #$attrs= array($attrib => $oldAttr);
3425     #$ldap->rm($attrs, $dn);
3426     #if ($ldap->error != "Success") {
3427     #  continue;
3428     #}
3429     $ldap->cd($dn);
3430     $ldap->modify(array($attrib => $newAttr));
3431     if ($ldap->error != "Success") {
3432       msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." ".$ldap->get_error(), ERROR_DIALOG);
3433       return null;
3434     } else {
3435       return $oldAttr;
3436     }
3437   }
3439   /* Bail out if we had problems getting the next id */
3440   if (!$tries) {
3441     msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("maximum tries exceeded!"), ERROR_DIALOG);
3442   }
3444   return $id;
3448 function get_next_id_traditional($attrib, $dn)
3450   global $config;
3452   $ids= array();
3453   $ldap= $config->get_ldap_link();
3455   $ldap->cd ($config->current['BASE']);
3456   if (preg_match('/gidNumber/i', $attrib)){
3457     $oc= "posixGroup";
3458   } else {
3459     $oc= "posixAccount";
3460   }
3461   $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
3463   /* Get list of ids */
3464   while ($attrs= $ldap->fetch()){
3465     $ids[]= (int)$attrs["$attrib"][0];
3466   }
3468   /* Add the nobody id */
3469   $ids[]= 65534;
3471   /* get the ranges */
3472   $tmp = array('0'=> 1000);
3473   if (preg_match('/posixAccount/', $oc) && $config->get_cfg_value("uidNumberBase") != ""){
3474     $tmp= split('-',$config->get_cfg_value("uidNumberBase"));
3475   } elseif($config->get_cfg_value("gidNumberBase") != ""){
3476     $tmp= split('-',$config->get_cfg_value("gidNumberBase"));
3477   }
3479   /* Set hwm to max if not set - for backward compatibility */
3480   $lwm= $tmp[0];
3481   if (isset($tmp[1])){
3482     $hwm= $tmp[1];
3483   } else {
3484     $hwm= pow(2,32);
3485   }
3486   /* Find out next free id near to UID_BASE */
3487   if ($config->get_cfg_value("baseIdHook") == ""){
3488     $base= $lwm;
3489   } else {
3490     /* Call base hook */
3491     $base= get_base_from_hook($dn, $attrib);
3492   }
3493   for ($id= $base; $id++; $id < pow(2,32)){
3494     if (!in_array($id, $ids)){
3495       return ($id);
3496     }
3497   }
3499   /* Should not happen */
3500   if ($id == $hwm){
3501     msg_dialog::display(_("Error"), _("Cannot allocate a free ID!"), ERROR_DIALOG);
3502     exit;
3503   }
3507 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3508 ?>