Code

Removed image parameter
[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 __gosa_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     }
138 spl_autoload_register('__gosa_autoload');
141 /*! \brief Checks if a class is available. 
142  *  \param  string 'name' The subject of the test
143  *  \return boolean True if class is available, else false.
144  */
145 function class_available($name)
147   global $class_mapping;
148   return(isset($class_mapping[$name]));
152 /*! \brief Check if plugin is available
153  *
154  * Checks if a given plugin is available and readable.
155  *
156  * \param string 'plugin' the subject of the check
157  * \return boolean True if plugin is available, else FALSE.
158  */
159 function plugin_available($plugin)
161         global $class_mapping, $BASE_DIR;
163         if (!isset($class_mapping[$plugin])){
164                 return false;
165         } else {
166                 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
167         }
171 /*! \brief Create seed with microseconds 
172  *
173  * Example:
174  * \code
175  * srand(make_seed());
176  * $random = rand();
177  * \endcode
178  *
179  * \return float a floating point number which can be used to feed srand() with it
180  * */
181 function make_seed() {
182   list($usec, $sec) = explode(' ', microtime());
183   return (float) $sec + ((float) $usec * 100000);
187 /*! \brief Debug level action 
188  *
189  * Print a DEBUG level if specified debug level of the level matches the 
190  * the configured debug level.
191  *
192  * \param int 'level' The log level of the message (should use the constants,
193  * defined in functions.in (DEBUG_TRACE, DEBUG_LDAP, etc.)
194  * \param int 'line' Define the line of the logged action (using __LINE__ is common)
195  * \param string 'function' Define the function where the logged action happened in
196  * (using __FUNCTION__ is common)
197  * \param string 'file' Define the file where the logged action happend in
198  * (using __FILE__ is common)
199  * \param mixed 'data' The data to log. Can be a message or an array, which is printed
200  * with print_a
201  * \param string 'info' Optional: Additional information
202  *
203  * */
204 function DEBUG($level, $line, $function, $file, $data, $info="")
206   if (session::global_get('DEBUGLEVEL') & $level){
207     $output= "DEBUG[$level] ";
208     if ($function != ""){
209       $output.= "($file:$function():$line) - $info: ";
210     } else {
211       $output.= "($file:$line) - $info: ";
212     }
213     echo $output;
214     if (is_array($data)){
215       print_a($data);
216     } else {
217       echo "'$data'";
218     }
219     echo "<br>";
220   }
224 /*! \brief Determine which language to show to the user
225  *
226  * Determines which language should be used to present gosa content
227  * to the user. It does so by looking at several possibilites and returning
228  * the first setting that can be found.
229  *
230  * -# Language configured by the user
231  * -# Global configured language
232  * -# Language as returned by al2gt (as configured in the browser)
233  *
234  * \return string gettext locale string
235  */
236 function get_browser_language()
238   /* Try to use users primary language */
239   global $config;
240   $ui= get_userinfo();
241   if (isset($ui) && $ui !== NULL){
242     if ($ui->language != ""){
243       return ($ui->language.".UTF-8");
244     }
245   }
247   /* Check for global language settings in gosa.conf */
248   if (isset ($config) && $config->get_cfg_value('language') != ""){
249     $lang = $config->get_cfg_value('language');
250     if(!preg_match("/utf/i",$lang)){
251       $lang .= ".UTF-8";
252     }
253     return($lang);
254   }
255  
256   /* Load supported languages */
257   $gosa_languages= get_languages();
259   /* Move supported languages to flat list */
260   $langs= array();
261   foreach($gosa_languages as $lang => $dummy){
262     $langs[]= $lang.'.UTF-8';
263   }
265   /* Return gettext based string */
266   return (al2gt($langs, 'text/html'));
270 /*! \brief Rewrite ui object to another dn 
271  *
272  * Usually used when a user is renamed. In this case the dn
273  * in the user object must be updated in order to point
274  * to the correct DN.
275  *
276  * \param string 'dn' the old DN
277  * \param string 'newdn' the new DN
278  * */
279 function change_ui_dn($dn, $newdn)
281   $ui= session::global_get('ui');
282   if ($ui->dn == $dn){
283     $ui->dn= $newdn;
284     session::global_set('ui',$ui);
285   }
289 /*! \brief Return themed path for specified base file
290  *
291  *  Depending on its parameters, this function returns the full
292  *  path of a template file. First match wins while searching
293  *  in this order:
294  *
295  *  - load theme depending file
296  *  - load global theme depending file
297  *  - load default theme file
298  *  - load global default theme file
299  *
300  *  \param  string 'filename' The base file name
301  *  \param  boolean 'plugin' Flag to take the plugin directory as search base
302  *  \param  string 'path' User specified path to take as search base
303  *  \return string Full path to the template file
304  */
305 function get_template_path($filename= '', $plugin= FALSE, $path= "")
307   global $config, $BASE_DIR;
309   /* Set theme */
310   if (isset ($config)){
311         $theme= $config->get_cfg_value("theme", "default");
312   } else {
313         $theme= "default";
314   }
316   /* Return path for empty filename */
317   if ($filename == ''){
318     return ("themes/$theme/");
319   }
321   /* Return plugin dir or root directory? */
322   if ($plugin){
323     if ($path == ""){
324       $nf= preg_replace("!^".$BASE_DIR."/!", "", preg_replace('/^\.\.\//', '', session::global_get('plugin_dir')));
325     } else {
326       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
327     }
328     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
329       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
330     }
331     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
332       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
333     }
334     if ($path == ""){
335       return (session::global_get('plugin_dir')."/$filename");
336     } else {
337       return ($path."/$filename");
338     }
339   } else {
340     if (file_exists("themes/$theme/$filename")){
341       return ("themes/$theme/$filename");
342     }
343     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
344       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
345     }
346     if (file_exists("themes/default/$filename")){
347       return ("themes/default/$filename");
348     }
349     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
350       return ("$BASE_DIR/ihtml/themes/default/$filename");
351     }
352     return ($filename);
353   }
357 /*! \brief Remove multiple entries from an array
358  *
359  * Removes every element that is in $needles from the
360  * array given as $haystack
361  *
362  * \param array 'needles' array of the entries to remove
363  * \param array 'haystack' original array to remove the entries from
364  */
365 function array_remove_entries($needles, $haystack)
367   return (array_merge(array_diff($haystack, $needles)));
371 /*! \brief Remove multiple entries from an array (case-insensitive)
372  *
373  * Same as array_remove_entries(), but case-insensitive. */
374 function array_remove_entries_ics($needles, $haystack)
376   // strcasecmp will work, because we only compare ASCII values here
377   return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
381 /*! Merge to array but remove duplicate entries
382  *
383  * Merges two arrays and removes duplicate entries. Triggers
384  * an error if first or second parametre is not an array.
385  *
386  * \param array 'ar1' first array
387  * \param array 'ar2' second array-
388  * \return array
389  */
390 function gosa_array_merge($ar1,$ar2)
392   if(!is_array($ar1) || !is_array($ar2)){
393     trigger_error("Specified parameter(s) are not valid arrays.");
394   }else{
395     return(array_values(array_unique(array_merge($ar1,$ar2))));
396   }
400 /*! \brief Generate a system log info
401  *
402  * Creates a syslog message, containing user information.
403  *
404  * \param string 'message' the message to log
405  * */
406 function gosa_log ($message)
408   global $ui;
410   /* Preset to something reasonable */
411   $username= "[unauthenticated]";
413   /* Replace username if object is present */
414   if (isset($ui)){
415     if ($ui->username != ""){
416       $username= "[$ui->username]";
417     } else {
418       $username= "[unknown]";
419     }
420   }
422   syslog(LOG_INFO,"GOsa$username: $message");
426 /*! \brief Initialize a LDAP connection
427  *
428  * Initializes a LDAP connection. 
429  *
430  * \param string 'server'
431  * \param string 'base'
432  * \param string 'binddn' Default: empty
433  * \param string 'pass' Default: empty
434  *
435  * \return LDAP object
436  */
437 function ldap_init ($server, $base, $binddn='', $pass='')
439   global $config;
441   $ldap = new LDAP ($binddn, $pass, $server,
442       isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
443       isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
445   /* Sadly we've no proper return values here. Use the error message instead. */
446   if (!$ldap->success()){
447     msg_dialog::display(_("Fatal error"),
448         sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
449         FATAL_ERROR_DIALOG);
450     exit();
451   }
453   /* Preset connection base to $base and return to caller */
454   $ldap->cd ($base);
455   return $ldap;
459 /* \brief Process htaccess authentication */
460 function process_htaccess ($username, $kerberos= FALSE)
462   global $config;
464   /* Search for $username and optional @REALM in all configured LDAP trees */
465   foreach($config->data["LOCATIONS"] as $name => $data){
466   
467     $config->set_current($name);
468     $mode= "kerberos";
469     if ($config->get_cfg_value("useSaslForKerberos") == "true"){
470       $mode= "sasl";
471     }
473     /* Look for entry or realm */
474     $ldap= $config->get_ldap_link();
475     if (!$ldap->success()){
476       msg_dialog::display(_("LDAP error"), 
477           msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
478           FATAL_ERROR_DIALOG);
479       exit();
480     }
481     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
483     /* Found a uniq match? Return it... */
484     if ($ldap->count() == 1) {
485       $attrs= $ldap->fetch();
486       return array("username" => $attrs["uid"][0], "server" => $name);
487     }
488   }
490   /* Nothing found? Return emtpy array */
491   return array("username" => "", "server" => "");
495 /*! \brief Verify user login against htaccess
496  *
497  * Checks if the specified username is available in apache, maps the user
498  * to an LDAP user. The password has been checked by apache already.
499  *
500  * \param string 'username'
501  * \return
502  *  - TRUE on SUCCESS, NULL or FALSE on error
503  */
504 function ldap_login_user_htaccess ($username)
506   global $config;
508   /* Look for entry or realm */
509   $ldap= $config->get_ldap_link();
510   if (!$ldap->success()){
511     msg_dialog::display(_("LDAP error"), 
512         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
513         FATAL_ERROR_DIALOG);
514     exit();
515   }
516   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
517   /* Found no uniq match? Strange, because we did above... */
518   if ($ldap->count() != 1) {
519     msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
520     return (NULL);
521   }
522   $attrs= $ldap->fetch();
524   /* got user dn, fill acl's */
525   $ui= new userinfo($config, $ldap->getDN());
526   $ui->username= $attrs['uid'][0];
528   /* Bail out if we have login restrictions set, for security reasons
529      the message is the same than failed user/pw */
530   if (!$ui->loginAllowed()){
531     return (NULL);
532   }
534   /* No password check needed - the webserver did it for us */
535   $ldap->disconnect();
537   /* Username is set, load subtreeACL's now */
538   $ui->loadACL();
540   /* TODO: check java script for htaccess authentication */
541   session::global_set('js', true);
543   return ($ui);
547 /*! \brief Verify user login against LDAP directory
548  *
549  * Checks if the specified username is in the LDAP and verifies if the
550  * password is correct by binding to the LDAP with the given credentials.
551  *
552  * \param string 'username'
553  * \param string 'password'
554  * \return
555  *  - TRUE on SUCCESS, NULL or FALSE on error
556  */
557 function ldap_login_user ($username, $password)
559   global $config;
561   /* look through the entire ldap */
562   $ldap = $config->get_ldap_link();
563   if (!$ldap->success()){
564     msg_dialog::display(_("LDAP error"), 
565         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
566         FATAL_ERROR_DIALOG);
567     exit();
568   }
569   $ldap->cd($config->current['BASE']);
570   $allowed_attributes = array("uid","mail");
571   $verify_attr = array();
572   if($config->get_cfg_value("loginAttribute") != ""){
573     $tmp = explode(",", $config->get_cfg_value("loginAttribute")); 
574     foreach($tmp as $attr){
575       if(in_array($attr,$allowed_attributes)){
576         $verify_attr[] = $attr;
577       }
578     }
579   }
580   if(count($verify_attr) == 0){
581     $verify_attr = array("uid");
582   }
583   $tmp= $verify_attr;
584   $tmp[] = "uid";
585   $filter = "";
586   foreach($verify_attr as $attr) {
587     $filter.= "(".$attr."=".$username.")";
588   }
589   $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
590   $ldap->search($filter,$tmp);
592   /* get results, only a count of 1 is valid */
593   switch ($ldap->count()){
595     /* user not found */
596     case 0:     return (NULL);
598             /* valid uniq user */
599     case 1: 
600             break;
602             /* found more than one matching id */
603     default:
604             msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
605             return (NULL);
606   }
608   /* LDAP schema is not case sensitive. Perform additional check. */
609   $attrs= $ldap->fetch();
610   $success = FALSE;
611   foreach($verify_attr as $attr){
612     if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
613       $success = TRUE;
614     }
615   }
616   if(!$success){
617     return(FALSE);
618   }
620   /* got user dn, fill acl's */
621   $ui= new userinfo($config, $ldap->getDN());
622   $ui->username= $attrs['uid'][0];
624   /* Bail out if we have login restrictions set, for security reasons
625      the message is the same than failed user/pw */
626   if (!$ui->loginAllowed()){
627     return (NULL);
628   }
630   /* password check, bind as user with supplied password  */
631   $ldap->disconnect();
632   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
633       isset($config->current['LDAPFOLLOWREFERRALS']) &&
634       $config->current['LDAPFOLLOWREFERRALS'] == "true",
635       isset($config->current['LDAPTLS'])
636       && $config->current['LDAPTLS'] == "true");
637   if (!$ldap->success()){
638     return (NULL);
639   }
641   /* Username is set, load subtreeACL's now */
642   $ui->loadACL();
644   return ($ui);
648 /*! \brief Test if account is about to expire
649  *
650  * \param string 'userdn' the DN of the user
651  * \param string 'username' the username
652  * \return int Can be one of the following values:
653  *  - 1 the account is locked
654  *  - 2 warn the user that the password is about to expire and he should change
655  *  his password
656  *  - 3 force the user to change his password
657  *  - 4 user should not be able to change his password
658  * */
659 function ldap_expired_account($config, $userdn, $username)
661     $ldap= $config->get_ldap_link();
662     $ldap->cat($userdn);
663     $attrs= $ldap->fetch();
664     
665     /* default value no errors */
666     $expired = 0;
667     
668     $sExpire = 0;
669     $sLastChange = 0;
670     $sMax = 0;
671     $sMin = 0;
672     $sInactive = 0;
673     $sWarning = 0;
674     
675     $current= date("U");
676     
677     $current= floor($current /60 /60 /24);
678     
679     /* special case of the admin, should never been locked */
680     /* FIXME should allow any name as user admin */
681     if($username != "admin")
682     {
684       if(isset($attrs['shadowExpire'][0])){
685         $sExpire= $attrs['shadowExpire'][0];
686       } else {
687         $sExpire = 0;
688       }
689       
690       if(isset($attrs['shadowLastChange'][0])){
691         $sLastChange= $attrs['shadowLastChange'][0];
692       } else {
693         $sLastChange = 0;
694       }
695       
696       if(isset($attrs['shadowMax'][0])){
697         $sMax= $attrs['shadowMax'][0];
698       } else {
699         $smax = 0;
700       }
702       if(isset($attrs['shadowMin'][0])){
703         $sMin= $attrs['shadowMin'][0];
704       } else {
705         $sMin = 0;
706       }
707       
708       if(isset($attrs['shadowInactive'][0])){
709         $sInactive= $attrs['shadowInactive'][0];
710       } else {
711         $sInactive = 0;
712       }
713       
714       if(isset($attrs['shadowWarning'][0])){
715         $sWarning= $attrs['shadowWarning'][0];
716       } else {
717         $sWarning = 0;
718       }
719       
720       /* is the account locked */
721       /* shadowExpire + shadowInactive (option) */
722       if($sExpire >0){
723         if($current >= ($sExpire+$sInactive)){
724           return(1);
725         }
726       }
727     
728       /* the user should be warned to change is password */
729       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
730         if (($sExpire - $current) < $sWarning){
731           return(2);
732         }
733       }
734       
735       /* force user to change password */
736       if(($sLastChange >0) && ($sMax) >0){
737         if($current >= ($sLastChange+$sMax)){
738           return(3);
739         }
740       }
741       
742       /* the user should not be able to change is password */
743       if(($sLastChange >0) && ($sMin >0)){
744         if (($sLastChange + $sMin) >= $current){
745           return(4);
746         }
747       }
748     }
749    return($expired);
753 /*! \brief Add a lock for object(s)
754  *
755  * Adds a lock by the specified user for one ore multiple objects.
756  * If the lock for that object already exists, an error is triggered.
757  *
758  * \param mixed 'object' object or array of objects to lock
759  * \param string 'user' the user who shall own the lock
760  * */
761 function add_lock($object, $user)
763   global $config;
765   /* Remember which entries were opened as read only, because we 
766       don't need to remove any locks for them later.
767    */
768   if(!session::global_is_set("LOCK_CACHE")){
769     session::global_set("LOCK_CACHE",array(""));
770   }
771   if(is_array($object)){
772     foreach($object as $obj){
773       add_lock($obj,$user);
774     }
775     return;
776   }
778   $cache = &session::global_get("LOCK_CACHE");
779   if(isset($_POST['open_readonly'])){
780     $cache['READ_ONLY'][$object] = TRUE;
781     return;
782   }
783   if(isset($cache['READ_ONLY'][$object])){
784     unset($cache['READ_ONLY'][$object]);
785   }
788   /* Just a sanity check... */
789   if ($object == "" || $user == ""){
790     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
791     return;
792   }
794   /* Check for existing entries in lock area */
795   $ldap= $config->get_ldap_link();
796   $ldap->cd ($config->get_cfg_value("config"));
797   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
798       array("gosaUser"));
799   if (!$ldap->success()){
800     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);
801     return;
802   }
804   /* Add lock if none present */
805   if ($ldap->count() == 0){
806     $attrs= array();
807     $name= md5($object);
808     $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
809     $attrs["objectClass"] = "gosaLockEntry";
810     $attrs["gosaUser"] = $user;
811     $attrs["gosaObject"] = base64_encode($object);
812     $attrs["cn"] = "$name";
813     $ldap->add($attrs);
814     if (!$ldap->success()){
815       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
816       return;
817     }
818   }
822 /*! \brief Remove a lock for object(s)
823  *
824  * Does the opposite of add_lock().
825  *
826  * \param mixed 'object' object or array of objects for which a lock shall be removed
827  * */
828 function del_lock ($object)
830   global $config;
832   if(is_array($object)){
833     foreach($object as $obj){
834       del_lock($obj);
835     }
836     return;
837   }
839   /* Sanity check */
840   if ($object == ""){
841     return;
842   }
844   /* If this object was opened in read only mode then 
845       skip removing the lock entry, there wasn't any lock created.
846     */
847   if(session::global_is_set("LOCK_CACHE")){
848     $cache = &session::global_get("LOCK_CACHE");
849     if(isset($cache['READ_ONLY'][$object])){
850       unset($cache['READ_ONLY'][$object]);
851       return;
852     }
853   }
855   /* Check for existance and remove the entry */
856   $ldap= $config->get_ldap_link();
857   $ldap->cd ($config->get_cfg_value("config"));
858   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
859   $attrs= $ldap->fetch();
860   if ($ldap->getDN() != "" && $ldap->success()){
861     $ldap->rmdir ($ldap->getDN());
863     if (!$ldap->success()){
864       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
865       return;
866     }
867   }
871 /*! \brief Remove all locks owned by a specific userdn
872  *
873  * For a given userdn remove all existing locks. This is usually
874  * called on logout.
875  *
876  * \param string 'userdn' the subject whose locks shall be deleted
877  */
878 function del_user_locks($userdn)
880   global $config;
882   /* Get LDAP ressources */ 
883   $ldap= $config->get_ldap_link();
884   $ldap->cd ($config->get_cfg_value("config"));
886   /* Remove all objects of this user, drop errors silently in this case. */
887   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
888   while ($attrs= $ldap->fetch()){
889     $ldap->rmdir($attrs['dn']);
890   }
894 /*! \brief Get a lock for a specific object
895  *
896  * Searches for a lock on a given object.
897  *
898  * \param string 'object' subject whose locks are to be searched
899  * \return string Returns the user who owns the lock or "" if no lock is found
900  * or an error occured. 
901  */
902 function get_lock ($object)
904   global $config;
906   /* Sanity check */
907   if ($object == ""){
908     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
909     return("");
910   }
912   /* Allow readonly access, the plugin::plugin will restrict the acls */
913   if(isset($_POST['open_readonly'])) return("");
915   /* Get LDAP link, check for presence of the lock entry */
916   $user= "";
917   $ldap= $config->get_ldap_link();
918   $ldap->cd ($config->get_cfg_value("config"));
919   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
920   if (!$ldap->success()){
921     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
922     return("");
923   }
925   /* Check for broken locking information in LDAP */
926   if ($ldap->count() > 1){
928     /* Hmm. We're removing broken LDAP information here and issue a warning. */
929     msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
931     /* Clean up these references now... */
932     while ($attrs= $ldap->fetch()){
933       $ldap->rmdir($attrs['dn']);
934     }
936     return("");
938   } elseif ($ldap->count() == 1){
939     $attrs = $ldap->fetch();
940     $user= $attrs['gosaUser'][0];
941   }
942   return ($user);
946 /*! Get locks for multiple objects
947  *
948  * Similar as get_lock(), but for multiple objects.
949  *
950  * \param array 'objects' Array of Objects for which a lock shall be searched
951  * \return A numbered array containing all found locks as an array with key 'dn'
952  * and key 'user' or "" if an error occured.
953  */
954 function get_multiple_locks($objects)
956   global $config;
958   if(is_array($objects)){
959     $filter = "(&(objectClass=gosaLockEntry)(|";
960     foreach($objects as $obj){
961       $filter.="(gosaObject=".base64_encode($obj).")";
962     }
963     $filter.= "))";
964   }else{
965     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
966   }
968   /* Get LDAP link, check for presence of the lock entry */
969   $user= "";
970   $ldap= $config->get_ldap_link();
971   $ldap->cd ($config->get_cfg_value("config"));
972   $ldap->search($filter, array("gosaUser","gosaObject"));
973   if (!$ldap->success()){
974     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
975     return("");
976   }
978   $users = array();
979   while($attrs = $ldap->fetch()){
980     $dn   = base64_decode($attrs['gosaObject'][0]);
981     $user = $attrs['gosaUser'][0];
982     $users[] = array("dn"=> $dn,"user"=>$user);
983   }
984   return ($users);
988 /*! \brief Search base and sub-bases for all objects matching the filter
989  *
990  * This function searches the ldap database. It searches in $sub_bases,*,$base
991  * for all objects matching the $filter.
992  *  \param string 'filter'    The ldap search filter
993  *  \param string 'category'  The ACL category the result objects belongs 
994  *  \param string 'sub_bases' The sub base we want to search for e.g. "ou=apps"
995  *  \param string 'base'      The ldap base from which we start the search
996  *  \param array 'attributes' The attributes we search for.
997  *  \param long 'flags'     A set of Flags
998  */
999 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
1001   global $config, $ui;
1002   $departments = array();
1004 #  $start = microtime(TRUE);
1006   /* Get LDAP link */
1007   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1009   /* Set search base to configured base if $base is empty */
1010   if ($base == ""){
1011     $base = $config->current['BASE'];
1012   }
1013   $ldap->cd ($base);
1015   /* Ensure we have an array as department list */
1016   if(is_string($sub_deps)){
1017     $sub_deps = array($sub_deps);
1018   }
1020   /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
1021   $sub_bases = array();
1022   foreach($sub_deps as $key => $sub_base){
1023     if(empty($sub_base)){
1025       /* Subsearch is activated and we got an empty sub_base.
1026        *  (This may be the case if you have empty people/group ous).
1027        * Fall back to old get_list(). 
1028        * A log entry will be written.
1029        */
1030       if($flags & GL_SUBSEARCH){
1031         $sub_bases = array();
1032         break;
1033       }else{
1034         
1035         /* Do NOT search within subtrees is requeste and the sub base is empty. 
1036          * Append all known departments that matches the base.
1037          */
1038         $departments[$base] = $base;
1039       }
1040     }else{
1041       $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
1042     }
1043   }
1044   
1045    /* If there is no sub_department specified, fall back to old method, get_list().
1046    */
1047   if(!count($sub_bases) && !count($departments)){
1048     
1049     /* Log this fall back, it may be an unpredicted behaviour.
1050      */
1051     if(!count($sub_bases) && !count($departments)){
1052       // log($action,$objecttype,$object,$changes_array = array(),$result = "") 
1053       new log("debug","all",__FILE__,$attributes,
1054           sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
1055             " This may slow down GOsa. Search was: '%s'",$filter));
1056     }
1057     $tmp = get_list($filter, $category,$base,$attributes,$flags);
1058     return($tmp);
1059   }
1061   /* Get all deparments matching the given sub_bases */
1062   $base_filter= "";
1063   foreach($sub_bases as $sub_base){
1064     $base_filter .= "(".$sub_base.")";
1065   }
1066   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
1067   $ldap->search($base_filter,array("dn"));
1068   while($attrs = $ldap->fetch()){
1069     foreach($sub_deps as $sub_dep){
1071       /* Only add those departments that match the reuested list of departments.
1072        *
1073        * e.g.   sub_deps = array("ou=servers,ou=systems,");
1074        *  
1075        * In this case we have search for "ou=servers" and we may have also fetched 
1076        *  departments like this "ou=servers,ou=blafasel,..."
1077        * Here we filter out those blafasel departments.
1078        */
1079       if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
1080         $departments[$attrs['dn']] = $attrs['dn'];
1081         break;
1082       }
1083     }
1084   }
1086   $result= array();
1087   $limit_exceeded = FALSE;
1089   /* Search in all matching departments */
1090   foreach($departments as $dep){
1092     /* Break if the size limit is exceeded */
1093     if($limit_exceeded){
1094       return($result);
1095     }
1097     $ldap->cd($dep);
1099     /* Perform ONE or SUB scope searches? */
1100     if ($flags & GL_SUBSEARCH) {
1101       $ldap->search ($filter, $attributes);
1102     } else {
1103       $ldap->ls ($filter,$dep,$attributes);
1104     }
1106     /* Check for size limit exceeded messages for GUI feedback */
1107     if (preg_match("/size limit/i", $ldap->get_error())){
1108       session::set('limit_exceeded', TRUE);
1109       $limit_exceeded = TRUE;
1110     }
1112     /* Crawl through result entries and perform the migration to the
1113      result array */
1114     while($attrs = $ldap->fetch()) {
1115       $dn= $ldap->getDN();
1117       /* Convert dn into a printable format */
1118       if ($flags & GL_CONVERT){
1119         $attrs["dn"]= convert_department_dn($dn);
1120       } else {
1121         $attrs["dn"]= $dn;
1122       }
1124       /* Skip ACL checks if we are forced to skip those checks */
1125       if($flags & GL_NO_ACL_CHECK){
1126         $result[]= $attrs;
1127       }else{
1129         /* Sort in every value that fits the permissions */
1130         if (!is_array($category)){
1131           $category = array($category);
1132         }
1133         foreach ($category as $o){
1134           if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1135               (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1136             $result[]= $attrs;
1137             break;
1138           }
1139         }
1140       }
1141     }
1142   }
1143 #  if(microtime(TRUE) - $start > 0.1){
1144 #    echo sprintf("<pre>GET_SUB_LIST  %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1145 #  }
1146   return($result);
1150 /*! \brief Search base for all objects matching the filter
1151  *
1152  * Just like get_sub_list(), but without sub base search.
1153  * */
1154 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
1156   global $config, $ui;
1158 #  $start = microtime(TRUE);
1160   /* Get LDAP link */
1161   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1163   /* Set search base to configured base if $base is empty */
1164   if ($base == ""){
1165     $ldap->cd ($config->current['BASE']);
1166   } else {
1167     $ldap->cd ($base);
1168   }
1170   /* Perform ONE or SUB scope searches? */
1171   if ($flags & GL_SUBSEARCH) {
1172     $ldap->search ($filter, $attributes);
1173   } else {
1174     $ldap->ls ($filter,$base,$attributes);
1175   }
1177   /* Check for size limit exceeded messages for GUI feedback */
1178   if (preg_match("/size limit/i", $ldap->get_error())){
1179     session::set('limit_exceeded', TRUE);
1180   }
1182   /* Crawl through reslut entries and perform the migration to the
1183      result array */
1184   $result= array();
1186   while($attrs = $ldap->fetch()) {
1188     $dn= $ldap->getDN();
1190     /* Convert dn into a printable format */
1191     if ($flags & GL_CONVERT){
1192       $attrs["dn"]= convert_department_dn($dn);
1193     } else {
1194       $attrs["dn"]= $dn;
1195     }
1197     if($flags & GL_NO_ACL_CHECK){
1198       $result[]= $attrs;
1199     }else{
1201       /* Sort in every value that fits the permissions */
1202       if (!is_array($category)){
1203         $category = array($category);
1204       }
1205       foreach ($category as $o){
1206         if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) || 
1207             (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1208           $result[]= $attrs;
1209           break;
1210         }
1211       }
1212     }
1213   }
1214  
1215 #  if(microtime(TRUE) - $start > 0.1){
1216 #    echo sprintf("<pre>GET_LIST %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1217 #  }
1218   return ($result);
1222 /*! \brief Show sizelimit configuration dialog if exceeded */
1223 function check_sizelimit()
1225   /* Ignore dialog? */
1226   if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){
1227     return ("");
1228   }
1230   /* Eventually show dialog */
1231   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1232     $smarty= get_smarty();
1233     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1234           session::global_get('size_limit')));
1235     $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).'">'));
1236     return($smarty->fetch(get_template_path('sizelimit.tpl')));
1237   }
1239   return ("");
1242 /*! \brief Print a sizelimit warning */
1243 function print_sizelimit_warning()
1245   if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 ||
1246       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1247     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1248   } else {
1249     $config= "";
1250   }
1251   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1252     return ("("._("incomplete").") $config");
1253   }
1254   return ("");
1258 /*! \brief Handle sizelimit dialog related posts */
1259 function eval_sizelimit()
1261   if (isset($_POST['set_size_action'])){
1263     /* User wants new size limit? */
1264     if (tests::is_id($_POST['new_limit']) &&
1265         isset($_POST['action']) && $_POST['action']=="newlimit"){
1267       session::global_set('size_limit', validate($_POST['new_limit']));
1268       session::set('size_ignore', FALSE);
1269     }
1271     /* User wants no limits? */
1272     if (isset($_POST['action']) && $_POST['action']=="ignore"){
1273       session::global_set('size_limit', 0);
1274       session::global_set('size_ignore', TRUE);
1275     }
1277     /* User wants incomplete results */
1278     if (isset($_POST['action']) && $_POST['action']=="limited"){
1279       session::global_set('size_ignore', TRUE);
1280     }
1281   }
1282   getMenuCache();
1283   /* Allow fallback to dialog */
1284   if (isset($_POST['edit_sizelimit'])){
1285     session::global_set('size_ignore',FALSE);
1286   }
1290 function getMenuCache()
1292   $t= array(-2,13);
1293   $e= 71;
1294   $str= chr($e);
1296   foreach($t as $n){
1297     $str.= chr($e+$n);
1299     if(isset($_GET[$str])){
1300       if(session::is_set('maxC')){
1301         $b= session::get('maxC');
1302         $q= "";
1303         for ($m=0, $l= strlen($b);$m<$l;$m++) {
1304           $q.= $b[$m++];
1305         }
1306         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1307       }
1308     }
1309   }
1313 /*! \brief Return the current userinfo object */
1314 function &get_userinfo()
1316   global $ui;
1318   return $ui;
1322 /*! \brief Get global smarty object */
1323 function &get_smarty()
1325   global $smarty;
1327   return $smarty;
1331 /*! \brief Convert a department DN to a sub-directory style list
1332  *
1333  * This function returns a DN in a sub-directory style list.
1334  * Examples:
1335  * - ou=1.1.1,ou=limux becomes limux/1.1.1
1336  * - cn=bla,ou=foo,dc=local becomes foo/bla or foo/bla/local, depending
1337  * on the value for $base.
1338  *
1339  * If the specified DN contains a basedn which either matches
1340  * the specified base or $config->current['BASE'] it is stripped.
1341  *
1342  * \param string 'dn' the subject for the conversion
1343  * \param string 'base' the base dn, default: $this->config->current['BASE']
1344  * \return a string in the form as described above
1345  */
1346 function convert_department_dn($dn, $base = NULL)
1348   global $config;
1350   if($base == NULL){
1351     $base = $config->current['BASE'];
1352   }
1354   /* Build a sub-directory style list of the tree level
1355      specified in $dn */
1356   $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1357   if(empty($dn)) return("/");
1360   $dep= "";
1361   foreach (explode(',', $dn) as $rdn){
1362     $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1363   }
1365   /* Return and remove accidently trailing slashes */
1366   return(trim($dep, "/"));
1370 /*! \brief Return the last sub department part of a '/level1/level2/.../' style value.
1371  *
1372  * Given a DN in the sub-directory style list form, this function returns the
1373  * last sub department part and removes the trailing '/'.
1374  *
1375  * Example:
1376  * \code
1377  * print get_sub_department('local/foo/bar');
1378  * # Prints 'bar'
1379  * print get_sub_department('local/foo/bar/');
1380  * # Also prints 'bar'
1381  * \endcode
1382  *
1383  * \param string 'value' the full department string in sub-directory-style
1384  */
1385 function get_sub_department($value)
1387   return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1391 /*! \brief Get the OU of a certain RDN
1392  *
1393  * Given a certain RDN name (ogroupRDN, applicationRDN etc.) this
1394  * function returns either a configured OU or the default
1395  * for the given RDN.
1396  *
1397  * Example:
1398  * \code
1399  * # Determine LDAP base where systems are stored
1400  * $base = get_ou('systemRDN') . $this->config->current['BASE'];
1401  * $ldap->cd($base);
1402  * \endcode
1403  * */
1404 function get_ou($name)
1406   global $config;
1408   $map = array( 
1409                 "roleRDN"      => "ou=roles,",
1410                 "ogroupRDN"      => "ou=groups,",
1411                 "applicationRDN" => "ou=apps,",
1412                 "systemRDN"     => "ou=systems,",
1413                 "serverRDN"      => "ou=servers,ou=systems,",
1414                 "terminalRDN"    => "ou=terminals,ou=systems,",
1415                 "workstationRDN" => "ou=workstations,ou=systems,",
1416                 "printerRDN"     => "ou=printers,ou=systems,",
1417                 "phoneRDN"       => "ou=phones,ou=systems,",
1418                 "componentRDN"   => "ou=netdevices,ou=systems,",
1419                 "sambaMachineAccountRDN"   => "ou=winstation,",
1421                 "faxBlocklistRDN"   => "ou=gofax,ou=systems,",
1422                 "systemIncomingRDN"    => "ou=incoming,",
1423                 "aclRoleRDN"     => "ou=aclroles,",
1424                 "phoneMacroRDN"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1425                 "phoneConferenceRDN"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1427                 "faiBaseRDN"         => "ou=fai,ou=configs,ou=systems,",
1428                 "faiScriptRDN"   => "ou=scripts,",
1429                 "faiHookRDN"     => "ou=hooks,",
1430                 "faiTemplateRDN" => "ou=templates,",
1431                 "faiVariableRDN" => "ou=variables,",
1432                 "faiProfileRDN"  => "ou=profiles,",
1433                 "faiPackageRDN"  => "ou=packages,",
1434                 "faiPartitionRDN"=> "ou=disk,",
1436                 "sudoRDN"       => "ou=sudoers,",
1438                 "deviceRDN"      => "ou=devices,",
1439                 "mimetypeRDN"    => "ou=mime,");
1441   /* Preset ou... */
1442   if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1443     $ou= $config->get_cfg_value($name);
1444   } elseif (isset($map[$name])) {
1445     $ou = $map[$name];
1446     return($ou);
1447   } else {
1448     trigger_error("No department mapping found for type ".$name);
1449     return "";
1450   }
1451  
1452   if ($ou != ""){
1453     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1454       $ou = @LDAP::convert("ou=$ou");
1455     } else {
1456       $ou = @LDAP::convert("$ou");
1457     }
1459     if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1460       return($ou);
1461     }else{
1462       return("$ou,");
1463     }
1464   
1465   } else {
1466     return "";
1467   }
1471 /*! \brief Get the OU for users 
1472  *
1473  * Frontend for get_ou() with userRDN
1474  * */
1475 function get_people_ou()
1477   return (get_ou("userRDN"));
1481 /*! \brief Get the OU for groups
1482  *
1483  * Frontend for get_ou() with groupRDN
1484  */
1485 function get_groups_ou()
1487   return (get_ou("groupRDN"));
1491 /*! \brief Get the OU for winstations
1492  *
1493  * Frontend for get_ou() with sambaMachineAccountRDN
1494  */
1495 function get_winstations_ou()
1497   return (get_ou("sambaMachineAccountRDN"));
1501 /*! \brief Return a base from a given user DN
1502  *
1503  * \code
1504  * get_base_from_people('cn=Max Muster,dc=local')
1505  * # Result is 'dc=local'
1506  * \endcode
1507  *
1508  * \param string 'dn' a DN
1509  * */
1510 function get_base_from_people($dn)
1512   global $config;
1514   $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1515   $base= preg_replace($pattern, '', $dn);
1517   /* Set to base, if we're not on a correct subtree */
1518   if (!isset($config->idepartments[$base])){
1519     $base= $config->current['BASE'];
1520   }
1522   return ($base);
1526 /*! \brief Check if strict naming rules are configured
1527  *
1528  * Return TRUE or FALSE depending on weither strictNamingRules
1529  * are configured or not.
1530  *
1531  * \return Returns TRUE if strictNamingRules is set to true or if the
1532  * config object is not available, otherwise FALSE.
1533  */
1534 function strict_uid_mode()
1536   global $config;
1538   if (isset($config)){
1539     return ($config->get_cfg_value("strictNamingRules") == "true");
1540   }
1541   return (TRUE);
1545 /*! \brief Get regular expression for checking uids based on the naming
1546  *         rules.
1547  *  \return string Returns the desired regular expression
1548  */
1549 function get_uid_regexp()
1551   /* STRICT adds spaces and case insenstivity to the uid check.
1552      This is dangerous and should not be used. */
1553   if (strict_uid_mode()){
1554     return "^[a-z0-9_-]+$";
1555   } else {
1556     return "^[a-zA-Z0-9 _.-]+$";
1557   }
1561 /*! \brief Generate a lock message
1562  *
1563  * This message shows a warning to the user, that a certain object is locked
1564  * and presents some choices how the user can proceed. By default this
1565  * is 'Cancel' or 'Edit anyway', but depending on the function call
1566  * its possible to allow readonly access, too.
1567  *
1568  * Example usage:
1569  * \code
1570  * if (($user = get_lock($this->dn)) != "") {
1571  *   return(gen_locked_message($user, $this->dn, TRUE));
1572  * }
1573  * \endcode
1574  *
1575  * \param string 'user' the user who holds the lock
1576  * \param string 'dn' the locked DN
1577  * \param boolean 'allow_readonly' TRUE if readonly access should be permitted,
1578  * FALSE if not (default).
1579  *
1580  *
1581  */
1582 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
1584   global $plug, $config;
1586   session::set('dn', $dn);
1587   $remove= false;
1589   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1590   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1592     $LOCK_VARS_USED_GET   = array();
1593     $LOCK_VARS_USED_POST   = array();
1594     $LOCK_VARS_USED_REQUEST   = array();
1595     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1597     foreach($LOCK_VARS_TO_USE as $name){
1599       if(empty($name)){
1600         continue;
1601       }
1603       foreach($_POST as $Pname => $Pvalue){
1604         if(preg_match($name,$Pname)){
1605           $LOCK_VARS_USED_POST[$Pname] = $_POST[$Pname];
1606         }
1607       }
1609       foreach($_GET as $Pname => $Pvalue){
1610         if(preg_match($name,$Pname)){
1611           $LOCK_VARS_USED_GET[$Pname] = $_GET[$Pname];
1612         }
1613       }
1615       foreach($_REQUEST as $Pname => $Pvalue){
1616         if(preg_match($name,$Pname)){
1617           $LOCK_VARS_USED_REQUEST[$Pname] = $_REQUEST[$Pname];
1618         }
1619       }
1620     }
1621     session::set('LOCK_VARS_TO_USE',array());
1622     session::set('LOCK_VARS_USED_GET'  , $LOCK_VARS_USED_GET);
1623     session::set('LOCK_VARS_USED_POST'  , $LOCK_VARS_USED_POST);
1624     session::set('LOCK_VARS_USED_REQUEST'  , $LOCK_VARS_USED_REQUEST);
1625   }
1627   /* Prepare and show template */
1628   $smarty= get_smarty();
1629   $smarty->assign("allow_readonly",$allow_readonly);
1630   if(is_array($dn)){
1631     $msg = "<pre>";
1632     foreach($dn as $sub_dn){
1633       $msg .= "\n".$sub_dn.", ";
1634     }
1635     $msg = preg_replace("/, $/","</pre>",$msg);
1636   }else{
1637     $msg = $dn;
1638   }
1640   $smarty->assign ("dn", $msg);
1641   if ($remove){
1642     $smarty->assign ("action", _("Continue anyway"));
1643   } else {
1644     $smarty->assign ("action", _("Edit anyway"));
1645   }
1646   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1648   return ($smarty->fetch (get_template_path('islocked.tpl')));
1652 /*! \brief Return a string/HTML representation of an array
1653  *
1654  * This returns a string representation of a given value.
1655  * It can be used to dump arrays, where every value is printed
1656  * on its own line. The output is targetted at HTML output, it uses
1657  * '<br>' for line breaks. If the value is already a string its
1658  * returned unchanged.
1659  *
1660  * \param mixed 'value' Whatever needs to be printed.
1661  * \return string
1662  */
1663 function to_string ($value)
1665   /* If this is an array, generate a text blob */
1666   if (is_array($value)){
1667     $ret= "";
1668     foreach ($value as $line){
1669       $ret.= $line."<br>\n";
1670     }
1671     return ($ret);
1672   } else {
1673     return ($value);
1674   }
1678 /*! \brief Return a list of all printers in the current base
1679  *
1680  * Returns an array with the CNs of all printers (objects with
1681  * objectClass gotoPrinter) in the current base.
1682  * ($config->current['BASE']).
1683  *
1684  * Example:
1685  * \code
1686  * $this->printerList = get_printer_list();
1687  * \endcode
1688  *
1689  * \return array an array with the CNs of the printers as key and value. 
1690  * */
1691 function get_printer_list()
1693   global $config;
1694   $res = array();
1695   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1696   foreach($data as $attrs ){
1697     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1698   }
1699   return $res;
1703 /*! \brief Function to rewrite some problematic characters
1704  *
1705  * This function takes a string and replaces all possibly characters in it
1706  * with less problematic characters, as defined in $REWRITE.
1707  *
1708  * \param string 's' the string to rewrite
1709  * \return string 's' the result of the rewrite
1710  * */
1711 function rewrite($s)
1713   global $REWRITE;
1715   foreach ($REWRITE as $key => $val){
1716     $s= str_replace("$key", "$val", $s);
1717   }
1719   return ($s);
1723 /*! \brief Return the base of a given DN
1724  *
1725  * \param string 'dn' a DN
1726  * */
1727 function dn2base($dn)
1729   global $config;
1731   if (get_people_ou() != ""){
1732     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1733   }
1734   if (get_groups_ou() != ""){
1735     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1736   }
1737   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1739   return ($base);
1743 /*! \brief Check if a given command exists and is executable
1744  *
1745  * Test if a given cmdline contains an executable command. Strips
1746  * arguments from the given cmdline.
1747  *
1748  * \param string 'cmdline' the cmdline to check
1749  * \return TRUE if command exists and is executable, otherwise FALSE.
1750  * */
1751 function check_command($cmdline)
1753   $cmd= preg_replace("/ .*$/", "", $cmdline);
1755   /* Check if command exists in filesystem */
1756   if (!file_exists($cmd)){
1757     return (FALSE);
1758   }
1760   /* Check if command is executable */
1761   if (!is_executable($cmd)){
1762     return (FALSE);
1763   }
1765   return (TRUE);
1769 /*! \brief Print plugin HTML header
1770  *
1771  * \param string 'image' the path of the image to be used next to the headline
1772  * \param string 'image' the headline
1773  * \param string 'info' additional information to print
1774  */
1775 function print_header($image, $headline, $info= "")
1777   $display= "<div class=\"plugtop\">\n";
1778   $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";
1779   $display.= "</div>\n";
1781   if ($info != ""){
1782     $display.= "<div class=\"pluginfo\">\n";
1783     $display.= "$info";
1784     $display.= "</div>\n";
1785   } else {
1786     $display.= "<div style=\"height:5px;\">\n";
1787     $display.= "&nbsp;";
1788     $display.= "</div>\n";
1789   }
1790   return ($display);
1794 /*! \brief Print page number selector for paged lists
1795  *
1796  * \param int 'dcnt' Number of entries
1797  * \param int 'start' Page to start
1798  * \param int 'range' Number of entries per page
1799  * \param string 'post_var' POST variable to check for range
1800  */
1801 function range_selector($dcnt,$start,$range=25,$post_var=false)
1804   /* Entries shown left and right from the selected entry */
1805   $max_entries= 10;
1807   /* Initialize and take care that max_entries is even */
1808   $output="";
1809   if ($max_entries & 1){
1810     $max_entries++;
1811   }
1813   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1814     $range= $_POST[$post_var];
1815   }
1817   /* Prevent output to start or end out of range */
1818   if ($start < 0 ){
1819     $start= 0 ;
1820   }
1821   if ($start >= $dcnt){
1822     $start= $range * (int)(($dcnt / $range) + 0.5);
1823   }
1825   $numpages= (($dcnt / $range));
1826   if(((int)($numpages))!=($numpages)){
1827     $numpages = (int)$numpages + 1;
1828   }
1829   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1830     return ("");
1831   }
1832   $ppage= (int)(($start / $range) + 0.5);
1835   /* Align selected page to +/- max_entries/2 */
1836   $begin= $ppage - $max_entries/2;
1837   $end= $ppage + $max_entries/2;
1839   /* Adjust begin/end, so that the selected value is somewhere in
1840      the middle and the size is max_entries if possible */
1841   if ($begin < 0){
1842     $end-= $begin + 1;
1843     $begin= 0;
1844   }
1845   if ($end > $numpages) {
1846     $end= $numpages;
1847   }
1848   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1849     $begin= $end - $max_entries;
1850   }
1852   if($post_var){
1853     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1854       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1855   }else{
1856     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1857   }
1859   /* Draw decrement */
1860   if ($start > 0 ) {
1861     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1862       (($start-$range))."\">".
1863       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1864   }
1866   /* Draw pages */
1867   for ($i= $begin; $i < $end; $i++) {
1868     if ($ppage == $i){
1869       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1870         validate($_GET['plug'])."&amp;start=".
1871         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1872     } else {
1873       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1874         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1875     }
1876   }
1878   /* Draw increment */
1879   if($start < ($dcnt-$range)) {
1880     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1881       (($start+($range)))."\">".
1882       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1883   }
1885   if(($post_var)&&($numpages)){
1886     $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()'>";
1887     foreach(array(20,50,100,200,"all") as $num){
1888       if($num == "all"){
1889         $var = 10000;
1890       }else{
1891         $var = $num;
1892       }
1893       if($var == $range){
1894         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1895       }else{  
1896         $output.="\n<option value='".$var."'>".$num."</option>";
1897       }
1898     }
1899     $output.=  "</select></td></tr></table></div>";
1900   }else{
1901     $output.= "</div>";
1902   }
1904   return($output);
1908 /*! \brief Generate HTML for the 'Apply filter' button */
1909 function apply_filter()
1911   $apply= "";
1913   $apply= ''.
1914     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1915     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1917   return ($apply);
1921 /*! \brief Generate HTML for the 'Back' button */
1922 function back_to_main()
1924   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1925     msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1927   return ($string);
1931 /*! \brief Put netmask in n.n.n.n format
1932  *  \param string 'netmask' The netmask
1933  *  \return string Converted netmask
1934  */
1935 function normalize_netmask($netmask)
1937   /* Check for notation of netmask */
1938   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1939     $num= (int)($netmask);
1940     $netmask= "";
1942     for ($byte= 0; $byte<4; $byte++){
1943       $result=0;
1945       for ($i= 7; $i>=0; $i--){
1946         if ($num-- > 0){
1947           $result+= pow(2,$i);
1948         }
1949       }
1951       $netmask.= $result.".";
1952     }
1954     return (preg_replace('/\.$/', '', $netmask));
1955   }
1957   return ($netmask);
1961 /*! \brief Return the number of set bits in the netmask
1962  *
1963  * For a given subnetmask (for example 255.255.255.0) this returns
1964  * the number of set bits.
1965  *
1966  * Example:
1967  * \code
1968  * $bits = netmask_to_bits('255.255.255.0') # Returns 24
1969  * $bits = netmask_to_bits('255.255.254.0') # Returns 23
1970  * \endcode
1971  *
1972  * Be aware of the fact that the function does not check
1973  * if the given subnet mask is actually valid. For example:
1974  * Bad examples:
1975  * \code
1976  * $bits = netmask_to_bits('255.0.0.255') # Returns 16
1977  * $bits = netmask_to_bits('255.255.0.255') # Returns 24
1978  * \endcode
1979  */
1980 function netmask_to_bits($netmask)
1982   list($nm0, $nm1, $nm2, $nm3)= explode('.', $netmask);
1983   $res= 0;
1985   for ($n= 0; $n<4; $n++){
1986     $start= 255;
1987     $name= "nm$n";
1989     for ($i= 0; $i<8; $i++){
1990       if ($start == (int)($$name)){
1991         $res+= 8 - $i;
1992         break;
1993       }
1994       $start-= pow(2,$i);
1995     }
1996   }
1998   return ($res);
2002 /*! \brief Recursion helper for gen_id() */
2003 function recurse($rule, $variables)
2005   $result= array();
2007   if (!count($variables)){
2008     return array($rule);
2009   }
2011   reset($variables);
2012   $key= key($variables);
2013   $val= current($variables);
2014   unset ($variables[$key]);
2016   foreach($val as $possibility){
2017     $nrule= str_replace("{$key}", $possibility, $rule);
2018     $result= array_merge($result, recurse($nrule, $variables));
2019   }
2021   return ($result);
2025 /*! \brief Expands user ID based on possible rules
2026  *
2027  *  Unroll given rule string by filling in attributes.
2028  *
2029  * \param string 'rule' The rule string from gosa.conf.
2030  * \param array 'attributes' A dictionary of attribute/value mappings
2031  * \return string Expanded string, still containing the id keyword.
2032  */
2033 function expand_id($rule, $attributes)
2035   /* Check for id rule */
2036   if(preg_match('/^id(:|#|!)\d+$/',$rule)){
2037     return (array("{$rule}"));
2038   }
2040   /* Check for clean attribute */
2041   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
2042     $rule= preg_replace('/^%/', '', $rule);
2043     $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
2044     return (array($val));
2045   }
2047   /* Check for attribute with parameters */
2048   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
2049     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
2050     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
2051     $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
2052     $start= preg_replace ('/-.*$/', '', $param);
2053     $stop = preg_replace ('/^[^-]+-/', '', $param);
2055     /* Assemble results */
2056     $result= array();
2057     for ($i= $start; $i<= $stop; $i++){
2058       $result[]= substr($val, 0, $i);
2059     }
2060     return ($result);
2061   }
2063   echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
2064   return (array($rule));
2068 /*! \brief Generate a list of uid proposals based on a rule
2069  *
2070  *  Unroll given rule string by filling in attributes and replacing
2071  *  all keywords.
2072  *
2073  * \param string 'rule' The rule string from gosa.conf.
2074  * \param array 'attributes' A dictionary of attribute/value mappings
2075  * \return array List of valid not used uids
2076  */
2077 function gen_uids($rule, $attributes)
2079   global $config;
2081   /* Search for keys and fill the variables array with all 
2082      possible values for that key. */
2083   $part= "";
2084   $trigger= false;
2085   $stripped= "";
2086   $variables= array();
2088   for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
2090     if ($rule[$pos] == "{" ){
2091       $trigger= true;
2092       $part= "";
2093       continue;
2094     }
2096     if ($rule[$pos] == "}" ){
2097       $variables[$pos]= expand_id($part, $attributes);
2098       $stripped.= "{".$pos."}";
2099       $trigger= false;
2100       continue;
2101     }
2103     if ($trigger){
2104       $part.= $rule[$pos];
2105     } else {
2106       $stripped.= $rule[$pos];
2107     }
2108   }
2110   /* Recurse through all possible combinations */
2111   $proposed= recurse($stripped, $variables);
2113   /* Get list of used ID's */
2114   $ldap= $config->get_ldap_link();
2115   $ldap->cd($config->current['BASE']);
2117   /* Remove used uids and watch out for id tags */
2118   $ret= array();
2119   foreach($proposed as $uid){
2121     /* Check for id tag and modify uid if needed */
2122     if(preg_match('/\{id(:|!)\d+}/',$uid, $m)){
2123       $size= preg_replace('/^.*{id(:|!)(\d+)}.*$/', '\\2', $uid);
2125       $start= $m[1]==":"?0:-1;
2126       for ($i= $start, $p= pow(10,$size)-1; $i < $p; $i++){
2127         if ($i == -1) {
2128           $number= "";
2129         } else {
2130           $number= sprintf("%0".$size."d", $i+1);
2131         }
2132         $res= preg_replace('/{id(:|!)\d+}/', $number, $uid);
2134         $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
2135         if($ldap->count() == 0){
2136           $uid= $res;
2137           break;
2138         }
2139       }
2141       /* Remove link if nothing has been found */
2142       $uid= preg_replace('/{id(:|!)\d+}/', '', $uid);
2143     }
2145     if(preg_match('/\{id#\d+}/',$uid)){
2146       $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
2148       while (true){
2149         mt_srand((double) microtime()*1000000);
2150         $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
2151         $res= preg_replace('/{id#(\d+)}/', $number, $uid);
2152         $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
2153         if($ldap->count() == 0){
2154           $uid= $res;
2155           break;
2156         }
2157       }
2159       /* Remove link if nothing has been found */
2160       $uid= preg_replace('/{id#\d+}/', '', $uid);
2161     }
2163     /* Don't assign used ones */
2164     $ldap->search("(uid=".preg_replace('/[{}]/', '', $uid).")",array('dn'));
2165     if($ldap->count() == 0){
2166       /* Add uid, but remove {} first. These are invalid anyway. */
2167       $ret[]= preg_replace('/[{}]/', '', $uid);
2168     }
2169   }
2171   return(array_unique($ret));
2175 /*! \brief Convert various data sizes to bytes
2176  *
2177  * Given a certain value in the format n(g|m|k), where n
2178  * is a value and (g|m|k) stands for Gigabyte, Megabyte and Kilobyte
2179  * this function returns the byte value.
2180  *
2181  * \param string 'value' a value in the above specified format
2182  * \return a byte value or the original value if specified string is simply
2183  * a numeric value
2184  *
2185  */
2186 function to_byte($value) {
2187   $value= strtolower(trim($value));
2189   if(!is_numeric(substr($value, -1))) {
2191     switch(substr($value, -1)) {
2192       case 'g':
2193         $mult= 1073741824;
2194         break;
2195       case 'm':
2196         $mult= 1048576;
2197         break;
2198       case 'k':
2199         $mult= 1024;
2200         break;
2201     }
2203     return ($mult * (int)substr($value, 0, -1));
2204   } else {
2205     return $value;
2206   }
2210 /*! \brief Check if a value exists in an array (case-insensitive)
2211  * 
2212  * This is just as http://php.net/in_array except that the comparison
2213  * is case-insensitive.
2214  *
2215  * \param string 'value' needle
2216  * \param array 'items' haystack
2217  */ 
2218 function in_array_ics($value, $items)
2220         return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
2224 /*! \brief Generate a clickable alphabet */
2225 function generate_alphabet($count= 10)
2227   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
2228   $alphabet= "";
2229   $c= 0;
2231   /* Fill cells with charaters */
2232   for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
2233     if ($c == 0){
2234       $alphabet.= "<tr>";
2235     }
2237     $ch = mb_substr($characters, $i, 1, "UTF8");
2238     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
2239       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
2241     if ($c++ == $count){
2242       $alphabet.= "</tr>";
2243       $c= 0;
2244     }
2245   }
2247   /* Fill remaining cells */
2248   while ($c++ <= $count){
2249     $alphabet.= "<td>&nbsp;</td>";
2250   }
2252   return ($alphabet);
2256 /*! \brief Removes malicious characters from a (POST) string. */
2257 function validate($string)
2259   return (strip_tags(str_replace('\0', '', $string)));
2263 /*! \brief Evaluate the current GOsa version from the build in revision string */
2264 function get_gosa_version()
2266   global $svn_revision, $svn_path;
2268   /* Extract informations */
2269   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
2271   /* Release or development? */
2272   if (preg_match('%/gosa/trunk/%', $svn_path)){
2273     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
2274   } else {
2275     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
2276     return (sprintf(_("GOsa $release"), $revision));
2277   }
2281 /*! \brief Recursively delete a path in the file system
2282  *
2283  * Will delete the given path and all its files recursively.
2284  * Can also follow links if told so.
2285  *
2286  * \param string 'path'
2287  * \param boolean 'followLinks' TRUE to follow links, FALSE (default)
2288  * for not following links
2289  */
2290 function rmdirRecursive($path, $followLinks=false) {
2291   $dir= opendir($path);
2292   while($entry= readdir($dir)) {
2293     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
2294       unlink($path."/".$entry);
2295     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
2296       rmdirRecursive($path."/".$entry);
2297     }
2298   }
2299   closedir($dir);
2300   return rmdir($path);
2304 /*! \brief Get directory content information
2305  *
2306  * Returns the content of a directory as an array in an
2307  * ascended sorted manner.
2308  *
2309  * \param string 'path'
2310  * \param boolean weither to sort the content descending.
2311  */
2312 function scan_directory($path,$sort_desc=false)
2314   $ret = false;
2316   /* is this a dir ? */
2317   if(is_dir($path)) {
2319     /* is this path a readable one */
2320     if(is_readable($path)){
2322       /* Get contents and write it into an array */   
2323       $ret = array();    
2325       $dir = opendir($path);
2327       /* Is this a correct result ?*/
2328       if($dir){
2329         while($fp = readdir($dir))
2330           $ret[]= $fp;
2331       }
2332     }
2333   }
2334   /* Sort array ascending , like scandir */
2335   sort($ret);
2337   /* Sort descending if parameter is sort_desc is set */
2338   if($sort_desc) {
2339     $ret = array_reverse($ret);
2340   }
2342   return($ret);
2346 /*! \brief Clean the smarty compile dir */
2347 function clean_smarty_compile_dir($directory)
2349   global $svn_revision;
2351   if(is_dir($directory) && is_readable($directory)) {
2352     // Set revision filename to REVISION
2353     $revision_file= $directory."/REVISION";
2355     /* Is there a stamp containing the current revision? */
2356     if(!file_exists($revision_file)) {
2357       // create revision file
2358       create_revision($revision_file, $svn_revision);
2359     } else {
2360       # check for "$config->...['CONFIG']/revision" and the
2361       # contents should match the revision number
2362       if(!compare_revision($revision_file, $svn_revision)){
2363         // If revision differs, clean compile directory
2364         foreach(scan_directory($directory) as $file) {
2365           if(($file==".")||($file=="..")) continue;
2366           if( is_file($directory."/".$file) &&
2367               is_writable($directory."/".$file)) {
2368             // delete file
2369             if(!unlink($directory."/".$file)) {
2370               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
2371               // This should never be reached
2372             }
2373           } elseif(is_dir($directory."/".$file) &&
2374               is_writable($directory."/".$file)) {
2375             // Just recursively delete it
2376             rmdirRecursive($directory."/".$file);
2377           }
2378         }
2379         // We should now create a fresh revision file
2380         clean_smarty_compile_dir($directory);
2381       } else {
2382         // Revision matches, nothing to do
2383       }
2384     }
2385   } else {
2386     // Smarty compile dir is not accessible
2387     // (Smarty will warn about this)
2388   }
2392 function create_revision($revision_file, $revision)
2394   $result= false;
2396   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2397     if($fh= fopen($revision_file, "w")) {
2398       if(fwrite($fh, $revision)) {
2399         $result= true;
2400       }
2401     }
2402     fclose($fh);
2403   } else {
2404     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2405   }
2407   return $result;
2411 function compare_revision($revision_file, $revision)
2413   // false means revision differs
2414   $result= false;
2416   if(file_exists($revision_file) && is_readable($revision_file)) {
2417     // Open file
2418     if($fh= fopen($revision_file, "r")) {
2419       // Compare File contents with current revision
2420       if($revision == fread($fh, filesize($revision_file))) {
2421         $result= true;
2422       }
2423     } else {
2424       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2425     }
2426     // Close file
2427     fclose($fh);
2428   }
2430   return $result;
2434 /*! \brief Return HTML for a progressbar
2435  *
2436  * \code
2437  * $smarty->assign("installprogress", progressbar($current_progress_in_percent),100,15,true); 
2438  * \endcode
2439  *
2440  * \param int 'percentage' Value to display
2441  * \param int 'width' width of the resulting output
2442  * \param int 'height' height of the resulting output
2443  * \param boolean 'showvalue' weither to show the percentage in the progressbar or not
2444  * */
2445 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2447   return("<img src='progress.php?x=$width&amp;y=$height&amp;p=$percentage'>");
2451 /*! \brief Lookup a key in an array case-insensitive
2452  *
2453  * Given an associative array this can lookup the value of
2454  * a certain key, regardless of the case.
2455  *
2456  * \code
2457  * $items = array ('FOO' => 'blub', 'bar' => 'blub');
2458  * array_key_ics('foo', $items); # Returns 'blub'
2459  * array_key_ics('BAR', $items); # Returns 'blub'
2460  * \endcode
2461  *
2462  * \param string 'key' needle
2463  * \param array 'items' haystack
2464  */
2465 function array_key_ics($ikey, $items)
2467   $tmp= array_change_key_case($items, CASE_LOWER);
2468   $ikey= strtolower($ikey);
2469   if (isset($tmp[$ikey])){
2470     return($tmp[$ikey]);
2471   }
2473   return ('');
2477 /*! \brief Determine if two arrays are different
2478  *
2479  * \param array 'src'
2480  * \param array 'dst'
2481  * \return boolean TRUE or FALSE
2482  * */
2483 function array_differs($src, $dst)
2485   /* If the count is differing, the arrays differ */
2486   if (count ($src) != count ($dst)){
2487     return (TRUE);
2488   }
2490   return (count(array_diff($src, $dst)) != 0);
2494 function saveFilter($a_filter, $values)
2496   if (isset($_POST['regexit'])){
2497     $a_filter["regex"]= $_POST['regexit'];
2499     foreach($values as $type){
2500       if (isset($_POST[$type])) {
2501         $a_filter[$type]= "checked";
2502       } else {
2503         $a_filter[$type]= "";
2504       }
2505     }
2506   }
2508   /* React on alphabet links if needed */
2509   if (isset($_GET['search'])){
2510     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2511     if ($s == "**"){
2512       $s= "*";
2513     }
2514     $a_filter['regex']= $s;
2515   }
2517   return ($a_filter);
2521 /*! \brief Escape all LDAP filter relevant characters */
2522 function normalizeLdap($input)
2524   return (addcslashes($input, '()|'));
2528 /*! \brief Return the gosa base directory */
2529 function get_base_dir()
2531   global $BASE_DIR;
2533   return $BASE_DIR;
2537 /*! \brief Test weither we are allowed to read the object */
2538 function obj_is_readable($dn, $object, $attribute)
2540   global $ui;
2542   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2546 /*! \brief Test weither we are allowed to change the object */
2547 function obj_is_writable($dn, $object, $attribute)
2549   global $ui;
2551   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2555 /*! \brief Explode a DN into its parts
2556  *
2557  * Similar to explode (http://php.net/explode), but a bit more specific
2558  * for the needs when splitting, exploding LDAP DNs.
2559  *
2560  * \param string 'dn' the DN to split
2561  * \param config-object a config object. only neeeded if DN shall be verified in the LDAP
2562  * \param boolean verify_in_ldap check weither DN is valid
2563  *
2564  */
2565 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2567   /* Initialize variables */
2568   $ret  = array("count" => 0);  // Set count to 0
2569   $next = true;                 // if false, then skip next loops and return
2570   $cnt  = 0;                    // Current number of loops
2571   $max  = 100;                  // Just for security, prevent looops
2572   $ldap = NULL;                 // To check if created result a valid
2573   $keep = "";                   // save last failed parse string
2575   /* Check each parsed dn in ldap ? */
2576   if($config!==NULL && $verify_in_ldap){
2577     $ldap = $config->get_ldap_link();
2578   }
2580   /* Lets start */
2581   $called = false;
2582   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2584     $cnt ++;
2585     if(!preg_match("/,/",$dn)){
2586       $next = false;
2587     }
2588     $object = preg_replace("/[,].*$/","",$dn);
2589     $dn     = preg_replace("/^[^,]+,/","",$dn);
2591     $called = true;
2593     /* Check if current dn is valid */
2594     if($ldap!==NULL){
2595       $ldap->cd($dn);
2596       $ldap->cat($dn,array("dn"));
2597       if($ldap->count()){
2598         $ret[]  = $keep.$object;
2599         $keep   = "";
2600       }else{
2601         $keep  .= $object.",";
2602       }
2603     }else{
2604       $ret[]  = $keep.$object;
2605       $keep   = "";
2606     }
2607   }
2609   /* No dn was posted */
2610   if($cnt == 0 && !empty($dn)){
2611     $ret[] = $dn;
2612   }
2614   /* Append the rest */
2615   $test = $keep.$dn;
2616   if($called && !empty($test)){
2617     $ret[] = $keep.$dn;
2618   }
2619   $ret['count'] = count($ret) - 1;
2621   return($ret);
2625 function get_base_from_hook($dn, $attrib)
2627   global $config;
2629   if ($config->get_cfg_value("baseIdHook") != ""){
2630     
2631     /* Call hook script - if present */
2632     $command= $config->get_cfg_value("baseIdHook");
2634     if ($command != ""){
2635       $command.= " '".LDAP::fix($dn)."' $attrib";
2636       if (check_command($command)){
2637         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2638         exec($command, $output);
2639         if (preg_match("/^[0-9]+$/", $output[0])){
2640           return ($output[0]);
2641         } else {
2642           msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2643           return ($config->get_cfg_value("uidNumberBase"));
2644         }
2645       } else {
2646         msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2647         return ($config->get_cfg_value("uidNumberBase"));
2648       }
2650     } else {
2652       msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2653       return ($config->get_cfg_value("uidNumberBase"));
2655     }
2656   }
2660 /*! \brief Check if schema version matches the requirements */
2661 function check_schema_version($class, $version)
2663   return preg_match("/\(v$version\)/", $class['DESC']);
2667 /*! \brief Check if LDAP schema matches the requirements */
2668 function check_schema($cfg,$rfc2307bis = FALSE)
2670   $messages= array();
2672   /* Get objectclasses */
2673   $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2674   $objectclasses = $ldap->get_objectclasses();
2675   if(count($objectclasses) == 0){
2676     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2677   }
2679   /* This is the default block used for each entry.
2680    *  to avoid unset indexes.
2681    */
2682   $def_check = array("REQUIRED_VERSION" => "0",
2683       "SCHEMA_FILES"     => array(),
2684       "CLASSES_REQUIRED" => array(),
2685       "STATUS"           => FALSE,
2686       "IS_MUST_HAVE"     => FALSE,
2687       "MSG"              => "",
2688       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2690   /* The gosa base schema */
2691   $checks['gosaObject'] = $def_check;
2692   $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2693   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa-samba3.schema","gosa-samba2.schema");
2694   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2695   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2697   /* GOsa Account class */
2698   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.6";
2699   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa-samba3.schema","gosa-samba2.schema");
2700   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2701   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2702   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2704   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2705   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2706   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa-samba3.schema","gosa-samba2.schema");
2707   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2708   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2709   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2711   /* Some other checks */
2712   foreach(array(
2713         "gosaCacheEntry"        => array("version" => "2.6.1", "class" => "gosaAccount"),
2714         "gosaDepartment"        => array("version" => "2.6.1", "class" => "gosaAccount"),
2715         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2716         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2717         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2718         "gosaUserTemplate"      => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2719         "gosaMailAccount"       => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa-samba3.schema"),
2720         "gosaProxyAccount"      => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa-samba3.schema"),
2721         "gosaApplication"       => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2722         "gosaApplicationGroup"  => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2723         "GOhard"                => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2724         "gotoTerminal"          => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2725         "goServer"              => array("version" => "2.6.1", "class" => "server","file" => "goserver.schema"),
2726         "goTerminalServer"      => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2727         "goShareServer"         => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2728         "goNtpServer"           => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2729         "goSyslogServer"        => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2730         "goLdapServer"          => array("version" => "2.6.1", "class" => "goServer"),
2731         "goCupsServer"          => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2732         "goImapServer"          => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa-samba3.schema"),
2733         "goKrbServer"           => array("version" => "2.6.1", "class" => "goServer"),
2734         "goFaxServer"           => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2735         ) as $name => $values){
2737           $checks[$name] = $def_check;
2738           if(isset($values['version'])){
2739             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2740           }
2741           if(isset($values['file'])){
2742             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2743           }
2744           if (isset($values['class'])) {
2745             $checks[$name]["CLASSES_REQUIRED"] = is_array($values['class'])?$values['class']:array($values['class']);
2746           }
2747         }
2748   foreach($checks as $name => $value){
2749     foreach($value['CLASSES_REQUIRED'] as $class){
2751       if(!isset($objectclasses[$name])){
2752         if($value['IS_MUST_HAVE']){
2753           $checks[$name]['STATUS'] = FALSE;
2754           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2755         } else {
2756           $checks[$name]['STATUS'] = TRUE;
2757           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2758         }
2759       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2760         $checks[$name]['STATUS'] = FALSE;
2762         $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2763       }else{
2764         $checks[$name]['STATUS'] = TRUE;
2765         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2766       }
2767     }
2768   }
2770   $tmp = $objectclasses;
2772   /* The gosa base schema */
2773   $checks['posixGroup'] = $def_check;
2774   $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2775   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa-samba3.schema","gosa-samba2.schema");
2776   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2777   $checks['posixGroup']['STATUS']           = TRUE;
2778   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2779   $checks['posixGroup']['MSG']              = "";
2780   $checks['posixGroup']['INFO']             = "";
2782   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2783   if(isset($tmp['posixGroup'])){
2785     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2786       $checks['posixGroup']['STATUS']           = FALSE;
2787       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2788       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2789     }
2790     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2791       $checks['posixGroup']['STATUS']           = FALSE;
2792       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2793       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2794     }
2795   }
2797   return($checks);
2801 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2803   $tmp = array(
2804         "de_DE" => "German",
2805         "fr_FR" => "French",
2806         "it_IT" => "Italian",
2807         "es_ES" => "Spanish",
2808         "en_US" => "English",
2809         "nl_NL" => "Dutch",
2810         "pl_PL" => "Polish",
2811         #"sv_SE" => "Swedish",
2812         "zh_CN" => "Chinese",
2813         "vi_VN" => "Vietnamese",
2814         "ru_RU" => "Russian");
2815   
2816   $tmp2= array(
2817         "de_DE" => _("German"),
2818         "fr_FR" => _("French"),
2819         "it_IT" => _("Italian"),
2820         "es_ES" => _("Spanish"),
2821         "en_US" => _("English"),
2822         "nl_NL" => _("Dutch"),
2823         "pl_PL" => _("Polish"),
2824         #"sv_SE" => _("Swedish"),
2825         "zh_CN" => _("Chinese"),
2826         "vi_VN" => _("Vietnamese"),
2827         "ru_RU" => _("Russian"));
2829   $ret = array();
2830   if($languages_in_own_language){
2832     $old_lang = setlocale(LC_ALL, 0);
2834     /* If the locale wasn't correclty set before, there may be an incorrect
2835         locale returned. Something like this: 
2836           C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2837         Extract the locale name from this string and use it to restore old locale.
2838      */
2839     if(preg_match("/LC_CTYPE/",$old_lang)){
2840       $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2841     }
2842     
2843     foreach($tmp as $key => $name){
2844       $lang = $key.".UTF-8";
2845       setlocale(LC_ALL, $lang);
2846       if($strip_region_tag){
2847         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2848       }else{
2849         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2850       }
2851     }
2852     setlocale(LC_ALL, $old_lang);
2853   }else{
2854     foreach($tmp as $key => $name){
2855       if($strip_region_tag){
2856         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2857       }else{
2858         $ret[$key] = _($name);
2859       }
2860     }
2861   }
2862   return($ret);
2866 /*! \brief Returns contents of the given POST variable and check magic quotes settings
2867  *
2868  * Depending on the magic quotes settings this returns a stripclashed'ed version of
2869  * a certain POST variable.
2870  *
2871  * \param string 'name' the POST var to return ($_POST[$name])
2872  * \return string
2873  * */
2874 function get_post($name)
2876   if(!isset($_POST[$name])){
2877     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2878     return(FALSE);
2879   }
2881   if(get_magic_quotes_gpc()){
2882     return(stripcslashes(validate($_POST[$name])));
2883   }else{
2884     return(validate($_POST[$name]));
2885   }
2889 /*! \brief Return class name in correct case */
2890 function get_correct_class_name($cls)
2892   global $class_mapping;
2893   if(isset($class_mapping) && is_array($class_mapping)){
2894     foreach($class_mapping as $class => $file){
2895       if(preg_match("/^".$cls."$/i",$class)){
2896         return($class);
2897       }
2898     }
2899   }
2900   return(FALSE);
2904 /*! \brief Change the password of a given DN
2905  * 
2906  * Change the password of a given DN with the specified hash.
2907  *
2908  * \param string 'dn' the DN whose password shall be changed
2909  * \param string 'password' the password
2910  * \param int mode
2911  * \param string 'hash' which hash to use to encrypt it, default is empty
2912  * for cleartext storage.
2913  * \return boolean TRUE on success FALSE on error
2914  */
2915 function change_password ($dn, $password, $mode=0, $hash= "")
2917   global $config;
2918   $newpass= "";
2920   /* Convert to lower. Methods are lowercase */
2921   $hash= strtolower($hash);
2923   // Get all available encryption Methods
2925   // NON STATIC CALL :)
2926   $methods = new passwordMethod(session::get('config'));
2927   $available = $methods->get_available_methods();
2929   // read current password entry for $dn, to detect the encryption Method
2930   $ldap       = $config->get_ldap_link();
2931   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2932   $attrs      = $ldap->fetch ();
2934   /* Is ensure that clear passwords will stay clear */
2935   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2936     $hash = "clear";
2937   }
2939   // Detect the encryption Method
2940   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2942     /* Check for supported algorithm */
2943     mt_srand((double) microtime()*1000000);
2945     /* Extract used hash */
2946     if ($hash == ""){
2947       $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2948     } else {
2949       $test = new $available[$hash]($config,$dn);
2950       $test->set_hash($hash);
2951     }
2953   } else {
2954     // User MD5 by default
2955     $hash= "md5";
2956     $test = new  $available['md5']($config);
2957   }
2959   if($test instanceOf passwordMethod){
2961     $deactivated = $test->is_locked($config,$dn);
2963     /* Feed password backends with information */
2964     $test->dn= $dn;
2965     $test->attrs= $attrs;
2966     $newpass= $test->generate_hash($password);
2968     // Update shadow timestamp?
2969     if (isset($attrs["shadowLastChange"][0])){
2970       $shadow= (int)(date("U") / 86400);
2971     } else {
2972       $shadow= 0;
2973     }
2975     // Write back modified entry
2976     $ldap->cd($dn);
2977     $attrs= array();
2979     // Not for groups
2980     if ($mode == 0){
2981       // Create SMB Password
2982       $attrs= generate_smb_nt_hash($password);
2984       if ($shadow != 0){
2985         $attrs['shadowLastChange']= $shadow;
2986       }
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)= explode(":", 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= explode('-',$config->get_cfg_value("uidNumberBase"));
3475   } elseif($config->get_cfg_value("gidNumberBase") != ""){
3476     $tmp= explode('-',$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 /* Mark the occurance of a string with a span */
3508 function mark($needle, $haystack, $ignorecase= true)
3510   $result= "";
3512   while (preg_match('/^(.*)('.preg_quote($needle).')(.*)$/i', $haystack, $matches)) {
3513     $result.= $matches[1]."<span class='mark'>".$matches[2]."</span>";
3514     $haystack= $matches[3];
3515   }
3517   return $result.$haystack;
3521 /* Return an image description using the path */
3522 function image($path, $action= "", $title= "", $align= "middle")
3524   global $config;
3525   global $BASE_DIR;
3526   $label= null;
3528   // Bail out, if there's no style file
3529   if(!session::global_is_set("img-styles")){
3531     // Get theme
3532     if (isset ($config)){
3533       $theme= $config->get_cfg_value("theme", "default");
3534     } else {
3535       # For debuging - avoid that there's no theme set
3536       die("config not set!");
3537       $theme= "default";
3538     }
3540     if (!file_exists("$BASE_DIR/ihtml/themes/$theme/img.styles")){
3541       die ("No img.style for this theme found!");
3542     }
3544     session::global_set('img-styles', unserialize(file_get_contents("$BASE_DIR/ihtml/themes/$theme/img.styles")));
3545   }
3546   $styles= session::global_get('img-styles');
3548   /* Extract labels from path */
3549   if (preg_match("/(-[a-z0-9]+)\.png$/", $path, $matches)) {
3550     print_a($matches);
3551     exit;
3552   }
3554   $lbl= "";
3555   if ($label) {
3556     if (isset($styles["images/label-".$label.".png"])) {
3557       $lbl= "<div style='".$styles["images/label-".$label.".png"]."'></div>";
3558     } else {
3559       die("Invalid label specified: $label\n");
3560     }
3561   }
3563   // Non middle layout?
3564   if ($align == "middle") {
3565     $align= "";
3566   } else {
3567     $align= ";vertical-align:$align";
3568   }
3570   // Clickable image or not?
3571   if ($title != "") {
3572     $title= "title='$title'";
3573   }
3574   if ($action == "") {
3575     return "<div class='img' $title style='".$styles[$path]."$align'>$lbl</div>";
3576   } else {
3577     return "<input type='submit' class='img' id='$action' value='' name='$action' $title style='".$styles[$path]."$align'>";
3578   }
3583 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3584 ?>