Code

da98e1f39e56afda8c68a36086a29a6c2780d7bb
[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"), bold("update-gosa"));
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"), bold($class_name), bold("update-gosa"));
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, $config;
148     
149   $disabled = array();
150   if($config instanceOf config && $config->configRegistry instanceOf configRegistry){
151     $disabled = $config->configRegistry->getDisabledPlugins();
152   }
154   return(isset($class_mapping[$name]) && !isset($disabled[$name]));
158 /*! \brief Check if plugin is available
159  *
160  * Checks if a given plugin is available and readable.
161  *
162  * \param string 'plugin' the subject of the check
163  * \return boolean True if plugin is available, else FALSE.
164  */
165 function plugin_available($plugin)
167         global $class_mapping, $BASE_DIR;
169         if (!isset($class_mapping[$plugin])){
170                 return false;
171         } else {
172                 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
173         }
177 /*! \brief Create seed with microseconds 
178  *
179  * Example:
180  * \code
181  * srand(make_seed());
182  * $random = rand();
183  * \endcode
184  *
185  * \return float a floating point number which can be used to feed srand() with it
186  * */
187 function make_seed() {
188   list($usec, $sec) = explode(' ', microtime());
189   return (float) $sec + ((float) $usec * 100000);
193 /*! \brief Debug level action 
194  *
195  * Print a DEBUG level if specified debug level of the level matches the 
196  * the configured debug level.
197  *
198  * \param int 'level' The log level of the message (should use the constants,
199  * defined in functions.in (DEBUG_TRACE, DEBUG_LDAP, etc.)
200  * \param int 'line' Define the line of the logged action (using __LINE__ is common)
201  * \param string 'function' Define the function where the logged action happened in
202  * (using __FUNCTION__ is common)
203  * \param string 'file' Define the file where the logged action happend in
204  * (using __FILE__ is common)
205  * \param mixed 'data' The data to log. Can be a message or an array, which is printed
206  * with print_a
207  * \param string 'info' Optional: Additional information
208  *
209  * */
210 function DEBUG($level, $line, $function, $file, $data, $info="")
212   if (session::global_get('debugLevel') & $level){
213     $output= "DEBUG[$level] ";
214     if ($function != ""){
215       $output.= "($file:$function():$line) - $info: ";
216     } else {
217       $output.= "($file:$line) - $info: ";
218     }
219     echo $output;
220     if (is_array($data)){
221       print_a($data);
222     } else {
223       echo "'$data'";
224     }
225     echo "<br>";
226   }
230 /*! \brief Determine which language to show to the user
231  *
232  * Determines which language should be used to present gosa content
233  * to the user. It does so by looking at several possibilites and returning
234  * the first setting that can be found.
235  *
236  * -# Language configured by the user
237  * -# Global configured language
238  * -# Language as returned by al2gt (as configured in the browser)
239  *
240  * \return string gettext locale string
241  */
242 function get_browser_language()
244   /* Try to use users primary language */
245   global $config;
246   $ui= get_userinfo();
247   if (isset($ui) && $ui !== NULL){
248     if ($ui->language != ""){
249       return ($ui->language.".UTF-8");
250     }
251   }
253   /* Check for global language settings in gosa.conf */
254   if (isset ($config) && $config->get_cfg_value("core",'language') != ""){
255     $lang = $config->get_cfg_value("core",'language');
256     if(!preg_match("/utf/i",$lang)){
257       $lang .= ".UTF-8";
258     }
259     return($lang);
260   }
261  
262   /* Load supported languages */
263   $gosa_languages= get_languages();
265   /* Move supported languages to flat list */
266   $langs= array();
267   foreach($gosa_languages as $lang => $dummy){
268     $langs[]= $lang.'.UTF-8';
269   }
271   /* Return gettext based string */
272   return (al2gt($langs, 'text/html'));
276 /*! \brief Rewrite ui object to another dn 
277  *
278  * Usually used when a user is renamed. In this case the dn
279  * in the user object must be updated in order to point
280  * to the correct DN.
281  *
282  * \param string 'dn' the old DN
283  * \param string 'newdn' the new DN
284  * */
285 function change_ui_dn($dn, $newdn)
287   $ui= session::global_get('ui');
288   if ($ui->dn == $dn){
289     $ui->dn= $newdn;
290     session::global_set('ui',$ui);
291   }
295 /*! \brief Return themed path for specified base file
296  *
297  *  Depending on its parameters, this function returns the full
298  *  path of a template file. First match wins while searching
299  *  in this order:
300  *
301  *  - load theme depending file
302  *  - load global theme depending file
303  *  - load default theme file
304  *  - load global default theme file
305  *
306  *  \param  string 'filename' The base file name
307  *  \param  boolean 'plugin' Flag to take the plugin directory as search base
308  *  \param  string 'path' User specified path to take as search base
309  *  \return string Full path to the template file
310  */
311 function get_template_path($filename= '', $plugin= FALSE, $path= "")
313   global $config, $BASE_DIR;
315   /* Set theme */
316   if (isset ($config)){
317         $theme= $config->get_cfg_value("core","theme");
318   } else {
319         $theme= "default";
320   }
322   /* Return path for empty filename */
323   if ($filename == ''){
324     return ("themes/$theme/");
325   }
327   /* Return plugin dir or root directory? */
328   if ($plugin){
329     if ($path == ""){
330       $nf= preg_replace("!^".$BASE_DIR."/!", "", preg_replace('/^\.\.\//', '', session::global_get('plugin_dir')));
331     } else {
332       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
333     }
334     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
335       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
336     }
337     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
338       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
339     }
340     if ($path == ""){
341       return (session::global_get('plugin_dir')."/$filename");
342     } else {
343       return ($path."/$filename");
344     }
345   } else {
346     if (file_exists("themes/$theme/$filename")){
347       return ("themes/$theme/$filename");
348     }
349     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
350       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
351     }
352     if (file_exists("themes/default/$filename")){
353       return ("themes/default/$filename");
354     }
355     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
356       return ("$BASE_DIR/ihtml/themes/default/$filename");
357     }
358     return ($filename);
359   }
363 /*! \brief Remove multiple entries from an array
364  *
365  * Removes every element that is in $needles from the
366  * array given as $haystack
367  *
368  * \param array 'needles' array of the entries to remove
369  * \param array 'haystack' original array to remove the entries from
370  */
371 function array_remove_entries($needles, $haystack)
373   return (array_merge(array_diff($haystack, $needles)));
377 /*! \brief Remove multiple entries from an array (case-insensitive)
378  *
379  * Same as array_remove_entries(), but case-insensitive. */
380 function array_remove_entries_ics($needles, $haystack)
382   // strcasecmp will work, because we only compare ASCII values here
383   return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
387 /*! Merge to array but remove duplicate entries
388  *
389  * Merges two arrays and removes duplicate entries. Triggers
390  * an error if first or second parametre is not an array.
391  *
392  * \param array 'ar1' first array
393  * \param array 'ar2' second array-
394  * \return array
395  */
396 function gosa_array_merge($ar1,$ar2)
398   if(!is_array($ar1) || !is_array($ar2)){
399     trigger_error("Specified parameter(s) are not valid arrays.");
400   }else{
401     return(array_values(array_unique(array_merge($ar1,$ar2))));
402   }
406 /*! \brief Generate a system log info
407  *
408  * Creates a syslog message, containing user information.
409  *
410  * \param string 'message' the message to log
411  * */
412 function gosa_log ($message)
414   global $ui;
416   /* Preset to something reasonable */
417   $username= "[unauthenticated]";
419   /* Replace username if object is present */
420   if (isset($ui)){
421     if ($ui->username != ""){
422       $username= "[$ui->username]";
423     } else {
424       $username= "[unknown]";
425     }
426   }
428   syslog(LOG_INFO,"GOsa$username: $message");
432 /*! \brief Initialize a LDAP connection
433  *
434  * Initializes a LDAP connection. 
435  *
436  * \param string 'server'
437  * \param string 'base'
438  * \param string 'binddn' Default: empty
439  * \param string 'pass' Default: empty
440  *
441  * \return LDAP object
442  */
443 function ldap_init ($server, $base, $binddn='', $pass='')
445   global $config;
447   $ldap = new LDAP ($binddn, $pass, $server,
448       isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
449       isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
451   /* Sadly we've no proper return values here. Use the error message instead. */
452   if (!$ldap->success()){
453     msg_dialog::display(_("Fatal error"),
454         sprintf(_("Error while connecting to LDAP: %s"), $ldap->get_error()),
455         FATAL_ERROR_DIALOG);
456     exit();
457   }
459   /* Preset connection base to $base and return to caller */
460   $ldap->cd ($base);
461   return $ldap;
465 /* \brief Process htaccess authentication */
466 function process_htaccess ($username, $kerberos= FALSE)
468   global $config;
470   /* Search for $username and optional @REALM in all configured LDAP trees */
471   foreach($config->data["LOCATIONS"] as $name => $data){
472   
473     $config->set_current($name);
474     $mode= "kerberos";
475     if ($config->get_cfg_value("core","useSaslForKerberos") == "true"){
476       $mode= "sasl";
477     }
479     /* Look for entry or realm */
480     $ldap= $config->get_ldap_link();
481     if (!$ldap->success()){
482       msg_dialog::display(_("LDAP error"), 
483           msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
484           FATAL_ERROR_DIALOG);
485       exit();
486     }
487     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
489     /* Found a uniq match? Return it... */
490     if ($ldap->count() == 1) {
491       $attrs= $ldap->fetch();
492       return array("username" => $attrs["uid"][0], "server" => $name);
493     }
494   }
496   /* Nothing found? Return emtpy array */
497   return array("username" => "", "server" => "");
501 /*! \brief Verify user login against htaccess
502  *
503  * Checks if the specified username is available in apache, maps the user
504  * to an LDAP user. The password has been checked by apache already.
505  *
506  * \param string 'username'
507  * \return
508  *  - TRUE on SUCCESS, NULL or FALSE on error
509  */
510 function ldap_login_user_htaccess ($username)
512   global $config;
514   /* Look for entry or realm */
515   $ldap= $config->get_ldap_link();
516   if (!$ldap->success()){
517     msg_dialog::display(_("LDAP error"), 
518         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
519         FATAL_ERROR_DIALOG);
520     exit();
521   }
522   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
523   /* Found no uniq match? Strange, because we did above... */
524   if ($ldap->count() != 1) {
525     msg_dialog::display(_("LDAP error"), _("User ID is not unique!"), FATAL_ERROR_DIALOG);
526     return (NULL);
527   }
528   $attrs= $ldap->fetch();
530   /* got user dn, fill acl's */
531   $ui= new userinfo($config, $ldap->getDN());
532   $ui->username= $attrs['uid'][0];
534   /* Bail out if we have login restrictions set, for security reasons
535      the message is the same than failed user/pw */
536   if (!$ui->loginAllowed()){
537     new log("security","login","",array(),"Login restriction for user \"$username\", login not permitted");
538     return (NULL);
539   }
541   /* No password check needed - the webserver did it for us */
542   $ldap->disconnect();
544   /* Username is set, load subtreeACL's now */
545   $ui->loadACL();
547   /* TODO: check java script for htaccess authentication */
548   session::global_set('js', true);
550   return ($ui);
554 /*! \brief Verify user login against LDAP directory
555  *
556  * Checks if the specified username is in the LDAP and verifies if the
557  * password is correct by binding to the LDAP with the given credentials.
558  *
559  * \param string 'username'
560  * \param string 'password'
561  * \return
562  *  - TRUE on SUCCESS, NULL or FALSE on error
563  */
564 function ldap_login_user ($username, $password)
566   global $config;
568   /* look through the entire ldap */
569   $ldap = $config->get_ldap_link();
570   if (!$ldap->success()){
571     msg_dialog::display(_("LDAP error"), 
572         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
573         FATAL_ERROR_DIALOG);
574     exit();
575   }
576   $ldap->cd($config->current['BASE']);
577   $allowed_attributes = array("uid","mail");
578   $verify_attr = array();
579   if($config->get_cfg_value("core","loginAttribute") != ""){
580     $tmp = explode(",", $config->get_cfg_value("core","loginAttribute")); 
581     foreach($tmp as $attr){
582       if(in_array($attr,$allowed_attributes)){
583         $verify_attr[] = $attr;
584       }
585     }
586   }
587   if(count($verify_attr) == 0){
588     $verify_attr = array("uid");
589   }
590   $tmp= $verify_attr;
591   $tmp[] = "uid";
592   $filter = "";
593   foreach($verify_attr as $attr) {
594     $filter.= "(".$attr."=".$username.")";
595   }
596   $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
597   $ldap->search($filter,$tmp);
599   /* get results, only a count of 1 is valid */
600   switch ($ldap->count()){
602     /* user not found */
603     case 0:     return (NULL);
605             /* valid uniq user */
606     case 1: 
607             break;
609             /* found more than one matching id */
610     default:
611             msg_dialog::display(_("Internal error"), _("User ID is not unique!"), FATAL_ERROR_DIALOG);
612             return (NULL);
613   }
615   /* LDAP schema is not case sensitive. Perform additional check. */
616   $attrs= $ldap->fetch();
617   $success = FALSE;
618   foreach($verify_attr as $attr){
619     if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
620       $success = TRUE;
621     }
622   }
623   if(!$success){
624     return(FALSE);
625   }
627   /* got user dn, fill acl's */
628   $ui= new userinfo($config, $ldap->getDN());
629   $ui->username= $attrs['uid'][0];
631   /* Bail out if we have login restrictions set, for security reasons
632      the message is the same than failed user/pw */
633   if (!$ui->loginAllowed()){
634     new log("security","login","",array(),"Login restriction for user \"$username\", login not permitted");
635     return (NULL);
636   }
638   /* password check, bind as user with supplied password  */
639   $ldap->disconnect();
640   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
641       isset($config->current['LDAPFOLLOWREFERRALS']) &&
642       $config->current['LDAPFOLLOWREFERRALS'] == "true",
643       isset($config->current['LDAPTLS'])
644       && $config->current['LDAPTLS'] == "true");
645   if (!$ldap->success()){
646     return (NULL);
647   }
649   /* Username is set, load subtreeACL's now */
650   $ui->loadACL();
652   return ($ui);
656 /*! \brief Test if account is about to expire
657  *
658  * \param string 'userdn' the DN of the user
659  * \param string 'username' the username
660  * \return int Can be one of the following values:
661  *  - 1 the account is locked
662  *  - 2 warn the user that the password is about to expire and he should change
663  *  his password
664  *  - 3 force the user to change his password
665  *  - 4 user should not be able to change his password
666  * */
667 function ldap_expired_account($config, $userdn, $username)
669     $ldap= $config->get_ldap_link();
670     $ldap->cat($userdn);
671     $attrs= $ldap->fetch();
672     
673     /* default value no errors */
674     $expired = 0;
675     
676     $sExpire = 0;
677     $sLastChange = 0;
678     $sMax = 0;
679     $sMin = 0;
680     $sInactive = 0;
681     $sWarning = 0;
682     
683     $current= date("U");
684     
685     $current= floor($current /60 /60 /24);
686     
687     /* special case of the admin, should never been locked */
688     /* FIXME should allow any name as user admin */
689     if($username != "admin")
690     {
692       if(isset($attrs['shadowExpire'][0])){
693         $sExpire= $attrs['shadowExpire'][0];
694       } else {
695         $sExpire = 0;
696       }
697       
698       if(isset($attrs['shadowLastChange'][0])){
699         $sLastChange= $attrs['shadowLastChange'][0];
700       } else {
701         $sLastChange = 0;
702       }
703       
704       if(isset($attrs['shadowMax'][0])){
705         $sMax= $attrs['shadowMax'][0];
706       } else {
707         $smax = 0;
708       }
710       if(isset($attrs['shadowMin'][0])){
711         $sMin= $attrs['shadowMin'][0];
712       } else {
713         $sMin = 0;
714       }
715       
716       if(isset($attrs['shadowInactive'][0])){
717         $sInactive= $attrs['shadowInactive'][0];
718       } else {
719         $sInactive = 0;
720       }
721       
722       if(isset($attrs['shadowWarning'][0])){
723         $sWarning= $attrs['shadowWarning'][0];
724       } else {
725         $sWarning = 0;
726       }
727       
728       /* is the account locked */
729       /* shadowExpire + shadowInactive (option) */
730       if($sExpire >0){
731         if($current >= ($sExpire+$sInactive)){
732           return(1);
733         }
734       }
735     
736       /* the user should be warned to change is password */
737       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
738         if (($sExpire - $current) < $sWarning){
739           return(2);
740         }
741       }
742       
743       /* force user to change password */
744       if(($sLastChange >0) && ($sMax) >0){
745         if($current >= ($sLastChange+$sMax)){
746           return(3);
747         }
748       }
749       
750       /* the user should not be able to change is password */
751       if(($sLastChange >0) && ($sMin >0)){
752         if (($sLastChange + $sMin) >= $current){
753           return(4);
754         }
755       }
756     }
757    return($expired);
761 /*! \brief Add a lock for object(s)
762  *
763  * Adds a lock by the specified user for one ore multiple objects.
764  * If the lock for that object already exists, an error is triggered.
765  *
766  * \param mixed 'object' object or array of objects to lock
767  * \param string 'user' the user who shall own the lock
768  * */
769 function add_lock($object, $user)
771   global $config;
773   /* Remember which entries were opened as read only, because we 
774       don't need to remove any locks for them later.
775    */
776   if(!session::global_is_set("LOCK_CACHE")){
777     session::global_set("LOCK_CACHE",array(""));
778   }
779   if(is_array($object)){
780     foreach($object as $obj){
781       add_lock($obj,$user);
782     }
783     return;
784   }
786   $cache = &session::global_get("LOCK_CACHE");
787   if(isset($_POST['open_readonly'])){
788     $cache['READ_ONLY'][$object] = TRUE;
789     return;
790   }
791   if(isset($cache['READ_ONLY'][$object])){
792     unset($cache['READ_ONLY'][$object]);
793   }
796   /* Just a sanity check... */
797   if ($object == "" || $user == ""){
798     msg_dialog::display(_("Internal error"), _("Error while locking entry!"), ERROR_DIALOG);
799     return;
800   }
802   /* Check for existing entries in lock area */
803   $ldap= $config->get_ldap_link();
804   $ldap->cd ($config->get_cfg_value("core","config"));
805   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
806       array("gosaUser"));
807   if (!$ldap->success()){
808     msg_dialog::display(_("Configuration error"), sprintf(_("Cannot store lock information in LDAP!")."<br><br>"._('Error: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
809     return;
810   }
812   /* Add lock if none present */
813   if ($ldap->count() == 0){
814     $attrs= array();
815     $name= md5($object);
816     $ldap->cd("cn=$name,".$config->get_cfg_value("core","config"));
817     $attrs["objectClass"] = "gosaLockEntry";
818     $attrs["gosaUser"] = $user;
819     $attrs["gosaObject"] = base64_encode($object);
820     $attrs["cn"] = "$name";
821     $ldap->add($attrs);
822     if (!$ldap->success()){
823       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("core","config"), 0, ERROR_DIALOG));
824       return;
825     }
826   }
830 /*! \brief Remove a lock for object(s)
831  *
832  * Does the opposite of add_lock().
833  *
834  * \param mixed 'object' object or array of objects for which a lock shall be removed
835  * */
836 function del_lock ($object)
838   global $config;
840   if(is_array($object)){
841     foreach($object as $obj){
842       del_lock($obj);
843     }
844     return;
845   }
847   /* Sanity check */
848   if ($object == ""){
849     return;
850   }
852   /* If this object was opened in read only mode then 
853       skip removing the lock entry, there wasn't any lock created.
854     */
855   if(session::global_is_set("LOCK_CACHE")){
856     $cache = &session::global_get("LOCK_CACHE");
857     if(isset($cache['READ_ONLY'][$object])){
858       unset($cache['READ_ONLY'][$object]);
859       return;
860     }
861   }
863   /* Check for existance and remove the entry */
864   $ldap= $config->get_ldap_link();
865   $ldap->cd ($config->get_cfg_value("core","config"));
866   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
867   $attrs= $ldap->fetch();
868   if ($ldap->getDN() != "" && $ldap->success()){
869     $ldap->rmdir ($ldap->getDN());
871     if (!$ldap->success()){
872       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
873       return;
874     }
875   }
879 /*! \brief Remove all locks owned by a specific userdn
880  *
881  * For a given userdn remove all existing locks. This is usually
882  * called on logout.
883  *
884  * \param string 'userdn' the subject whose locks shall be deleted
885  */
886 function del_user_locks($userdn)
888   global $config;
890   /* Get LDAP ressources */ 
891   $ldap= $config->get_ldap_link();
892   $ldap->cd ($config->get_cfg_value("core","config"));
894   /* Remove all objects of this user, drop errors silently in this case. */
895   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
896   while ($attrs= $ldap->fetch()){
897     $ldap->rmdir($attrs['dn']);
898   }
902 /*! \brief Get a lock for a specific object
903  *
904  * Searches for a lock on a given object.
905  *
906  * \param string 'object' subject whose locks are to be searched
907  * \return string Returns the user who owns the lock or "" if no lock is found
908  * or an error occured. 
909  */
910 function get_lock ($object)
912   global $config;
914   /* Sanity check */
915   if ($object == ""){
916     msg_dialog::display(_("Internal error"), _("Error while locking entry!"), ERROR_DIALOG);
917     return("");
918   }
920   /* Allow readonly access, the plugin::plugin will restrict the acls */
921   if(isset($_POST['open_readonly'])) return("");
923   /* Get LDAP link, check for presence of the lock entry */
924   $user= "";
925   $ldap= $config->get_ldap_link();
926   $ldap->cd ($config->get_cfg_value("core","config"));
927   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
928   if (!$ldap->success()){
929     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
930     return("");
931   }
933   /* Check for broken locking information in LDAP */
934   if ($ldap->count() > 1){
936     /* Clean up these references now... */
937     while ($attrs= $ldap->fetch()){
938       $ldap->rmdir($attrs['dn']);
939     }
941     return("");
943   } elseif ($ldap->count() == 1){
944     $attrs = $ldap->fetch();
945     $user= $attrs['gosaUser'][0];
946   }
947   return ($user);
951 /*! Get locks for multiple objects
952  *
953  * Similar as get_lock(), but for multiple objects.
954  *
955  * \param array 'objects' Array of Objects for which a lock shall be searched
956  * \return A numbered array containing all found locks as an array with key 'dn'
957  * and key 'user' or "" if an error occured.
958  */
959 function get_multiple_locks($objects)
961   global $config;
963   if(is_array($objects)){
964     $filter = "(&(objectClass=gosaLockEntry)(|";
965     foreach($objects as $obj){
966       $filter.="(gosaObject=".base64_encode($obj).")";
967     }
968     $filter.= "))";
969   }else{
970     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
971   }
973   /* Get LDAP link, check for presence of the lock entry */
974   $user= "";
975   $ldap= $config->get_ldap_link();
976   $ldap->cd ($config->get_cfg_value("core","config"));
977   $ldap->search($filter, array("gosaUser","gosaObject"));
978   if (!$ldap->success()){
979     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
980     return("");
981   }
983   $users = array();
984   while($attrs = $ldap->fetch()){
985     $dn   = base64_decode($attrs['gosaObject'][0]);
986     $user = $attrs['gosaUser'][0];
987     $users[] = array("dn"=> $dn,"user"=>$user);
988   }
989   return ($users);
993 /*! \brief Search base and sub-bases for all objects matching the filter
994  *
995  * This function searches the ldap database. It searches in $sub_bases,*,$base
996  * for all objects matching the $filter.
997  *  \param string 'filter'    The ldap search filter
998  *  \param string 'category'  The ACL category the result objects belongs 
999  *  \param string 'sub_bases' The sub base we want to search for e.g. "ou=apps"
1000  *  \param string 'base'      The ldap base from which we start the search
1001  *  \param array 'attributes' The attributes we search for.
1002  *  \param long 'flags'     A set of Flags
1003  */
1004 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
1006   global $config, $ui;
1007   $departments = array();
1009 #  $start = microtime(TRUE);
1011   /* Get LDAP link */
1012   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1014   /* Set search base to configured base if $base is empty */
1015   if ($base == ""){
1016     $base = $config->current['BASE'];
1017   }
1018   $ldap->cd ($base);
1020   /* Ensure we have an array as department list */
1021   if(is_string($sub_deps)){
1022     $sub_deps = array($sub_deps);
1023   }
1025   /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
1026   $sub_bases = array();
1027   foreach($sub_deps as $key => $sub_base){
1028     if(empty($sub_base)){
1030       /* Subsearch is activated and we got an empty sub_base.
1031        *  (This may be the case if you have empty people/group ous).
1032        * Fall back to old get_list(). 
1033        * A log entry will be written.
1034        */
1035       if($flags & GL_SUBSEARCH){
1036         $sub_bases = array();
1037         break;
1038       }else{
1039         
1040         /* Do NOT search within subtrees is requeste and the sub base is empty. 
1041          * Append all known departments that matches the base.
1042          */
1043         $departments[$base] = $base;
1044       }
1045     }else{
1046       $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
1047     }
1048   }
1049   
1050    /* If there is no sub_department specified, fall back to old method, get_list().
1051    */
1052   if(!count($sub_bases) && !count($departments)){
1053     
1054     /* Log this fall back, it may be an unpredicted behaviour.
1055      */
1056     if(!count($sub_bases) && !count($departments)){
1057       // log($action,$objecttype,$object,$changes_array = array(),$result = "") 
1058       new log("debug","all",__FILE__,$attributes,
1059           sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
1060             " This may slow down GOsa. Used filter: %s", $filter));
1061     }
1062     $tmp = get_list($filter, $category,$base,$attributes,$flags);
1063     return($tmp);
1064   }
1066   /* Get all deparments matching the given sub_bases */
1067   $base_filter= "";
1068   foreach($sub_bases as $sub_base){
1069     $base_filter .= "(".$sub_base.")";
1070   }
1071   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
1072   $ldap->search($base_filter,array("dn"));
1073   while($attrs = $ldap->fetch()){
1074     foreach($sub_deps as $sub_dep){
1076       /* Only add those departments that match the reuested list of departments.
1077        *
1078        * e.g.   sub_deps = array("ou=servers,ou=systems,");
1079        *  
1080        * In this case we have search for "ou=servers" and we may have also fetched 
1081        *  departments like this "ou=servers,ou=blafasel,..."
1082        * Here we filter out those blafasel departments.
1083        */
1084       if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
1085         $departments[$attrs['dn']] = $attrs['dn'];
1086         break;
1087       }
1088     }
1089   }
1091   $result= array();
1092   $limit_exceeded = FALSE;
1094   /* Search in all matching departments */
1095   foreach($departments as $dep){
1097     /* Break if the size limit is exceeded */
1098     if($limit_exceeded){
1099       return($result);
1100     }
1102     $ldap->cd($dep);
1104     /* Perform ONE or SUB scope searches? */
1105     if ($flags & GL_SUBSEARCH) {
1106       $ldap->search ($filter, $attributes);
1107     } else {
1108       $ldap->ls ($filter,$dep,$attributes);
1109     }
1111     /* Check for size limit exceeded messages for GUI feedback */
1112     if (preg_match("/size limit/i", $ldap->get_error())){
1113       session::set('limit_exceeded', TRUE);
1114       $limit_exceeded = TRUE;
1115     }
1117     /* Crawl through result entries and perform the migration to the
1118      result array */
1119     while($attrs = $ldap->fetch()) {
1120       $dn= $ldap->getDN();
1122       /* Convert dn into a printable format */
1123       if ($flags & GL_CONVERT){
1124         $attrs["dn"]= convert_department_dn($dn);
1125       } else {
1126         $attrs["dn"]= $dn;
1127       }
1129       /* Skip ACL checks if we are forced to skip those checks */
1130       if($flags & GL_NO_ACL_CHECK){
1131         $result[]= $attrs;
1132       }else{
1134         /* Sort in every value that fits the permissions */
1135         if (!is_array($category)){
1136           $category = array($category);
1137         }
1138         foreach ($category as $o){
1139           if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1140               (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1141             $result[]= $attrs;
1142             break;
1143           }
1144         }
1145       }
1146     }
1147   }
1148 #  if(microtime(TRUE) - $start > 0.1){
1149 #    echo sprintf("<pre>GET_SUB_LIST  %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1150 #  }
1151   return($result);
1155 /*! \brief Search base for all objects matching the filter
1156  *
1157  * Just like get_sub_list(), but without sub base search.
1158  * */
1159 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
1161   global $config, $ui;
1163 #  $start = microtime(TRUE);
1165   /* Get LDAP link */
1166   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1168   /* Set search base to configured base if $base is empty */
1169   if ($base == ""){
1170     $ldap->cd ($config->current['BASE']);
1171   } else {
1172     $ldap->cd ($base);
1173   }
1175   /* Perform ONE or SUB scope searches? */
1176   if ($flags & GL_SUBSEARCH) {
1177     $ldap->search ($filter, $attributes);
1178   } else {
1179     $ldap->ls ($filter,$base,$attributes);
1180   }
1182   /* Check for size limit exceeded messages for GUI feedback */
1183   if (preg_match("/size limit/i", $ldap->get_error())){
1184     session::set('limit_exceeded', TRUE);
1185   }
1187   /* Crawl through reslut entries and perform the migration to the
1188      result array */
1189   $result= array();
1191   while($attrs = $ldap->fetch()) {
1193     $dn= $ldap->getDN();
1195     /* Convert dn into a printable format */
1196     if ($flags & GL_CONVERT){
1197       $attrs["dn"]= convert_department_dn($dn);
1198     } else {
1199       $attrs["dn"]= $dn;
1200     }
1202     if($flags & GL_NO_ACL_CHECK){
1203       $result[]= $attrs;
1204     }else{
1206       /* Sort in every value that fits the permissions */
1207       if (!is_array($category)){
1208         $category = array($category);
1209       }
1210       foreach ($category as $o){
1211         if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) || 
1212             (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1213           $result[]= $attrs;
1214           break;
1215         }
1216       }
1217     }
1218   }
1219  
1220 #  if(microtime(TRUE) - $start > 0.1){
1221 #    echo sprintf("<pre>GET_LIST %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1222 #  }
1223   return ($result);
1227 /*! \brief Show sizelimit configuration dialog if exceeded */
1228 function check_sizelimit()
1230   /* Ignore dialog? */
1231   if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){
1232     return ("");
1233   }
1235   /* Eventually show dialog */
1236   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1237     $smarty= get_smarty();
1238     $smarty->assign('warning', sprintf(_("The current size limit of %d entries is exceeded!"),
1239           session::global_get('size_limit')));
1240     $smarty->assign('limit_message', sprintf(_("Set the size limit to %s"), '<input type="text" name="new_limit" maxlength="10" size="5" value="'.(session::global_get('size_limit') +100).'">'));
1241     return($smarty->fetch(get_template_path('sizelimit.tpl')));
1242   }
1244   return ("");
1247 /*! \brief Print a sizelimit warning */
1248 function print_sizelimit_warning()
1250   if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 ||
1251       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1252     $config= "<button type='submit' name='edit_sizelimit'>"._("Configure")."</button>";
1253   } else {
1254     $config= "";
1255   }
1256   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1257     return ("("._("list is incomplete").") $config");
1258   }
1259   return ("");
1263 /*! \brief Handle sizelimit dialog related posts */
1264 function eval_sizelimit()
1266   if (isset($_POST['set_size_action'])){
1268     /* User wants new size limit? */
1269     if (tests::is_id($_POST['new_limit']) &&
1270         isset($_POST['action']) && $_POST['action']=="newlimit"){
1272       session::global_set('size_limit', validate($_POST['new_limit']));
1273       session::set('size_ignore', FALSE);
1274     }
1276     /* User wants no limits? */
1277     if (isset($_POST['action']) && $_POST['action']=="ignore"){
1278       session::global_set('size_limit', 0);
1279       session::global_set('size_ignore', TRUE);
1280     }
1282     /* User wants incomplete results */
1283     if (isset($_POST['action']) && $_POST['action']=="limited"){
1284       session::global_set('size_ignore', TRUE);
1285     }
1286   }
1287   getMenuCache();
1288   /* Allow fallback to dialog */
1289   if (isset($_POST['edit_sizelimit'])){
1290     session::global_set('size_ignore',FALSE);
1291   }
1295 function getMenuCache()
1297   $t= array(-2,13);
1298   $e= 71;
1299   $str= chr($e);
1301   foreach($t as $n){
1302     $str.= chr($e+$n);
1304     if(isset($_GET[$str])){
1305       if(session::is_set('maxC')){
1306         $b= session::get('maxC');
1307         $q= "";
1308         for ($m=0, $l= strlen($b);$m<$l;$m++) {
1309           $q.= $b[$m++];
1310         }
1311         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1312       }
1313     }
1314   }
1318 /*! \brief Return the current userinfo object */
1319 function &get_userinfo()
1321   global $ui;
1323   return $ui;
1327 /*! \brief Get global smarty object */
1328 function &get_smarty()
1330   global $smarty;
1332   return $smarty;
1336 /*! \brief Convert a department DN to a sub-directory style list
1337  *
1338  * This function returns a DN in a sub-directory style list.
1339  * Examples:
1340  * - ou=1.1.1,ou=limux becomes limux/1.1.1
1341  * - cn=bla,ou=foo,dc=local becomes foo/bla or foo/bla/local, depending
1342  * on the value for $base.
1343  *
1344  * If the specified DN contains a basedn which either matches
1345  * the specified base or $config->current['BASE'] it is stripped.
1346  *
1347  * \param string 'dn' the subject for the conversion
1348  * \param string 'base' the base dn, default: $this->config->current['BASE']
1349  * \return a string in the form as described above
1350  */
1351 function convert_department_dn($dn, $base = NULL)
1353   global $config;
1355   if($base == NULL){
1356     $base = $config->current['BASE'];
1357   }
1359   /* Build a sub-directory style list of the tree level
1360      specified in $dn */
1361   $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1362   if(empty($dn)) return("/");
1365   $dep= "";
1366   foreach (explode(',', $dn) as $rdn){
1367     $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1368   }
1370   /* Return and remove accidently trailing slashes */
1371   return(trim($dep, "/"));
1375 /*! \brief Return the last sub department part of a '/level1/level2/.../' style value.
1376  *
1377  * Given a DN in the sub-directory style list form, this function returns the
1378  * last sub department part and removes the trailing '/'.
1379  *
1380  * Example:
1381  * \code
1382  * print get_sub_department('local/foo/bar');
1383  * # Prints 'bar'
1384  * print get_sub_department('local/foo/bar/');
1385  * # Also prints 'bar'
1386  * \endcode
1387  *
1388  * \param string 'value' the full department string in sub-directory-style
1389  */
1390 function get_sub_department($value)
1392   return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1396 /*! \brief Get the OU of a certain RDN
1397  *
1398  * Given a certain RDN name (ogroupRDN, applicationRDN etc.) this
1399  * function returns either a configured OU or the default
1400  * for the given RDN.
1401  *
1402  * Example:
1403  * \code
1404  * # Determine LDAP base where systems are stored
1405  * $base = get_ou("systemManagement", "systemRDN") . $this->config->current['BASE'];
1406  * $ldap->cd($base);
1407  * \endcode
1408  * */
1409 function get_ou($class,$name)
1411     global $config;
1413     if(!$config->configRegistry->propertyExists($class,$name)){
1414         trigger_error("No department mapping found for type ".$name);
1415         return "";
1416     }
1418     $ou = $config->configRegistry->getPropertyValue($class,$name);
1419     if ($ou != ""){
1420         if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1421             $ou = @LDAP::convert("ou=$ou");
1422         } else {
1423             $ou = @LDAP::convert("$ou");
1424         }
1426         if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1427             return($ou);
1428         }else{
1429             if(!preg_match("/,$/", $ou)){
1430                 return("$ou,");
1431             }else{
1432                 return($ou);
1433             }
1434         }
1436     } else {
1437         return "";
1438     }
1442 /*! \brief Get the OU for users 
1443  *
1444  * Frontend for get_ou() with userRDN
1445  * */
1446 function get_people_ou()
1448   return (get_ou("core", "userRDN"));
1452 /*! \brief Get the OU for groups
1453  *
1454  * Frontend for get_ou() with groupRDN
1455  */
1456 function get_groups_ou()
1458   return (get_ou("core", "groupRDN"));
1462 /*! \brief Get the OU for winstations
1463  *
1464  * Frontend for get_ou() with sambaMachineAccountRDN
1465  */
1466 function get_winstations_ou()
1468   return (get_ou("wingeneric", "sambaMachineAccountRDN"));
1472 /*! \brief Return a base from a given user DN
1473  *
1474  * \code
1475  * get_base_from_people('cn=Max Muster,dc=local')
1476  * # Result is 'dc=local'
1477  * \endcode
1478  *
1479  * \param string 'dn' a DN
1480  * */
1481 function get_base_from_people($dn)
1483   global $config;
1485   $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1486   $base= preg_replace($pattern, '', $dn);
1488   /* Set to base, if we're not on a correct subtree */
1489   if (!isset($config->idepartments[$base])){
1490     $base= $config->current['BASE'];
1491   }
1493   return ($base);
1497 /*! \brief Check if strict naming rules are configured
1498  *
1499  * Return TRUE or FALSE depending on weither strictNamingRules
1500  * are configured or not.
1501  *
1502  * \return Returns TRUE if strictNamingRules is set to true or if the
1503  * config object is not available, otherwise FALSE.
1504  */
1505 function strict_uid_mode()
1507   global $config;
1509   if (isset($config)){
1510     return ($config->get_cfg_value("core","strictNamingRules") == "true");
1511   }
1512   return (TRUE);
1516 /*! \brief Get regular expression for checking uids based on the naming
1517  *         rules.
1518  *  \return string Returns the desired regular expression
1519  */
1520 function get_uid_regexp()
1522   /* STRICT adds spaces and case insenstivity to the uid check.
1523      This is dangerous and should not be used. */
1524   if (strict_uid_mode()){
1525     return "^[a-z0-9_-]+$";
1526   } else {
1527     return "^[a-zA-Z0-9 _.-]+$";
1528   }
1532 /*! \brief Generate a lock message
1533  *
1534  * This message shows a warning to the user, that a certain object is locked
1535  * and presents some choices how the user can proceed. By default this
1536  * is 'Cancel' or 'Edit anyway', but depending on the function call
1537  * its possible to allow readonly access, too.
1538  *
1539  * Example usage:
1540  * \code
1541  * if (($user = get_lock($this->dn)) != "") {
1542  *   return(gen_locked_message($user, $this->dn, TRUE));
1543  * }
1544  * \endcode
1545  *
1546  * \param string 'user' the user who holds the lock
1547  * \param string 'dn' the locked DN
1548  * \param boolean 'allow_readonly' TRUE if readonly access should be permitted,
1549  * FALSE if not (default).
1550  *
1551  *
1552  */
1553 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
1555   global $plug, $config;
1557   session::set('dn', $dn);
1558   $remove= false;
1560   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1561   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1563     $LOCK_VARS_USED_GET   = array();
1564     $LOCK_VARS_USED_POST   = array();
1565     $LOCK_VARS_USED_REQUEST   = array();
1566     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1568     foreach($LOCK_VARS_TO_USE as $name){
1570       if(empty($name)){
1571         continue;
1572       }
1574       foreach($_POST as $Pname => $Pvalue){
1575         if(preg_match($name,$Pname)){
1576           $LOCK_VARS_USED_POST[$Pname] = $_POST[$Pname];
1577         }
1578       }
1580       foreach($_GET as $Pname => $Pvalue){
1581         if(preg_match($name,$Pname)){
1582           $LOCK_VARS_USED_GET[$Pname] = $_GET[$Pname];
1583         }
1584       }
1586       foreach($_REQUEST as $Pname => $Pvalue){
1587         if(preg_match($name,$Pname)){
1588           $LOCK_VARS_USED_REQUEST[$Pname] = $_REQUEST[$Pname];
1589         }
1590       }
1591     }
1592     session::set('LOCK_VARS_TO_USE',array());
1593     session::set('LOCK_VARS_USED_GET'  , $LOCK_VARS_USED_GET);
1594     session::set('LOCK_VARS_USED_POST'  , $LOCK_VARS_USED_POST);
1595     session::set('LOCK_VARS_USED_REQUEST'  , $LOCK_VARS_USED_REQUEST);
1596   }
1598   /* Prepare and show template */
1599   $smarty= get_smarty();
1600   $smarty->assign("allow_readonly",$allow_readonly);
1601   $msg= msgPool::buildList($dn);
1603   $smarty->assign ("dn", $msg);
1604   if ($remove){
1605     $smarty->assign ("action", _("Continue anyway"));
1606   } else {
1607     $smarty->assign ("action", _("Edit anyway"));
1608   }
1610   $smarty->assign ("message", _("These entries are currently locked:"). $msg);
1612   return ($smarty->fetch (get_template_path('islocked.tpl')));
1616 /*! \brief Return a string/HTML representation of an array
1617  *
1618  * This returns a string representation of a given value.
1619  * It can be used to dump arrays, where every value is printed
1620  * on its own line. The output is targetted at HTML output, it uses
1621  * '<br>' for line breaks. If the value is already a string its
1622  * returned unchanged.
1623  *
1624  * \param mixed 'value' Whatever needs to be printed.
1625  * \return string
1626  */
1627 function to_string ($value)
1629   /* If this is an array, generate a text blob */
1630   if (is_array($value)){
1631     $ret= "";
1632     foreach ($value as $line){
1633       $ret.= $line."<br>\n";
1634     }
1635     return ($ret);
1636   } else {
1637     return ($value);
1638   }
1642 /*! \brief Return a list of all printers in the current base
1643  *
1644  * Returns an array with the CNs of all printers (objects with
1645  * objectClass gotoPrinter) in the current base.
1646  * ($config->current['BASE']).
1647  *
1648  * Example:
1649  * \code
1650  * $this->printerList = get_printer_list();
1651  * \endcode
1652  *
1653  * \return array an array with the CNs of the printers as key and value. 
1654  * */
1655 function get_printer_list()
1657   global $config;
1658   $res = array();
1659   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1660   foreach($data as $attrs ){
1661     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1662   }
1663   return $res;
1667 /*! \brief Function to rewrite some problematic characters
1668  *
1669  * This function takes a string and replaces all possibly characters in it
1670  * with less problematic characters, as defined in $REWRITE.
1671  *
1672  * \param string 's' the string to rewrite
1673  * \return string 's' the result of the rewrite
1674  * */
1675 function rewrite($s)
1677   global $REWRITE;
1679   foreach ($REWRITE as $key => $val){
1680     $s= str_replace("$key", "$val", $s);
1681   }
1683   return ($s);
1687 /*! \brief Return the base of a given DN
1688  *
1689  * \param string 'dn' a DN
1690  * */
1691 function dn2base($dn)
1693   global $config;
1695   if (get_people_ou() != ""){
1696     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1697   }
1698   if (get_groups_ou() != ""){
1699     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1700   }
1701   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1703   return ($base);
1707 /*! \brief Check if a given command exists and is executable
1708  *
1709  * Test if a given cmdline contains an executable command. Strips
1710  * arguments from the given cmdline.
1711  *
1712  * \param string 'cmdline' the cmdline to check
1713  * \return TRUE if command exists and is executable, otherwise FALSE.
1714  * */
1715 function check_command($cmdline)
1717   $cmd= preg_replace("/ .*$/", "", $cmdline);
1719   /* Check if command exists in filesystem */
1720   if (!file_exists($cmd)){
1721     return (FALSE);
1722   }
1724   /* Check if command is executable */
1725   if (!is_executable($cmd)){
1726     return (FALSE);
1727   }
1729   return (TRUE);
1733 /*! \brief Print plugin HTML header
1734  *
1735  * \param string 'image' the path of the image to be used next to the headline
1736  * \param string 'image' the headline
1737  * \param string 'info' additional information to print
1738  */
1739 function print_header($image, $headline, $info= "")
1741   $display= "<div class=\"plugtop\">\n";
1742   $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";
1743   $display.= "</div>\n";
1745   if ($info != ""){
1746     $display.= "<div class=\"pluginfo\">\n";
1747     $display.= "$info";
1748     $display.= "</div>\n";
1749   } else {
1750     $display.= "<div style=\"height:5px;\">\n";
1751     $display.= "&nbsp;";
1752     $display.= "</div>\n";
1753   }
1754   return ($display);
1758 /*! \brief Print page number selector for paged lists
1759  *
1760  * \param int 'dcnt' Number of entries
1761  * \param int 'start' Page to start
1762  * \param int 'range' Number of entries per page
1763  * \param string 'post_var' POST variable to check for range
1764  */
1765 function range_selector($dcnt,$start,$range=25,$post_var=false)
1768   /* Entries shown left and right from the selected entry */
1769   $max_entries= 10;
1771   /* Initialize and take care that max_entries is even */
1772   $output="";
1773   if ($max_entries & 1){
1774     $max_entries++;
1775   }
1777   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1778     $range= $_POST[$post_var];
1779   }
1781   /* Prevent output to start or end out of range */
1782   if ($start < 0 ){
1783     $start= 0 ;
1784   }
1785   if ($start >= $dcnt){
1786     $start= $range * (int)(($dcnt / $range) + 0.5);
1787   }
1789   $numpages= (($dcnt / $range));
1790   if(((int)($numpages))!=($numpages)){
1791     $numpages = (int)$numpages + 1;
1792   }
1793   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1794     return ("");
1795   }
1796   $ppage= (int)(($start / $range) + 0.5);
1799   /* Align selected page to +/- max_entries/2 */
1800   $begin= $ppage - $max_entries/2;
1801   $end= $ppage + $max_entries/2;
1803   /* Adjust begin/end, so that the selected value is somewhere in
1804      the middle and the size is max_entries if possible */
1805   if ($begin < 0){
1806     $end-= $begin + 1;
1807     $begin= 0;
1808   }
1809   if ($end > $numpages) {
1810     $end= $numpages;
1811   }
1812   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1813     $begin= $end - $max_entries;
1814   }
1816   if($post_var){
1817     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1818       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1819   }else{
1820     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1821   }
1823   /* Draw decrement */
1824   if ($start > 0 ) {
1825     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1826       (($start-$range))."\">".
1827       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1828   }
1830   /* Draw pages */
1831   for ($i= $begin; $i < $end; $i++) {
1832     if ($ppage == $i){
1833       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1834         validate($_GET['plug'])."&amp;start=".
1835         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1836     } else {
1837       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1838         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1839     }
1840   }
1842   /* Draw increment */
1843   if($start < ($dcnt-$range)) {
1844     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1845       (($start+($range)))."\">".
1846       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1847   }
1849   if(($post_var)&&($numpages)){
1850     $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()'>";
1851     foreach(array(20,50,100,200,"all") as $num){
1852       if($num == "all"){
1853         $var = 10000;
1854       }else{
1855         $var = $num;
1856       }
1857       if($var == $range){
1858         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1859       }else{  
1860         $output.="\n<option value='".$var."'>".$num."</option>";
1861       }
1862     }
1863     $output.=  "</select></td></tr></table></div>";
1864   }else{
1865     $output.= "</div>";
1866   }
1868   return($output);
1873 /*! \brief Generate HTML for the 'Back' button */
1874 function back_to_main()
1876   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1877     msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1879   return ($string);
1883 /*! \brief Put netmask in n.n.n.n format
1884  *  \param string 'netmask' The netmask
1885  *  \return string Converted netmask
1886  */
1887 function normalize_netmask($netmask)
1889   /* Check for notation of netmask */
1890   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1891     $num= (int)($netmask);
1892     $netmask= "";
1894     for ($byte= 0; $byte<4; $byte++){
1895       $result=0;
1897       for ($i= 7; $i>=0; $i--){
1898         if ($num-- > 0){
1899           $result+= pow(2,$i);
1900         }
1901       }
1903       $netmask.= $result.".";
1904     }
1906     return (preg_replace('/\.$/', '', $netmask));
1907   }
1909   return ($netmask);
1913 /*! \brief Return the number of set bits in the netmask
1914  *
1915  * For a given subnetmask (for example 255.255.255.0) this returns
1916  * the number of set bits.
1917  *
1918  * Example:
1919  * \code
1920  * $bits = netmask_to_bits('255.255.255.0') # Returns 24
1921  * $bits = netmask_to_bits('255.255.254.0') # Returns 23
1922  * \endcode
1923  *
1924  * Be aware of the fact that the function does not check
1925  * if the given subnet mask is actually valid. For example:
1926  * Bad examples:
1927  * \code
1928  * $bits = netmask_to_bits('255.0.0.255') # Returns 16
1929  * $bits = netmask_to_bits('255.255.0.255') # Returns 24
1930  * \endcode
1931  */
1932 function netmask_to_bits($netmask)
1934   list($nm0, $nm1, $nm2, $nm3)= explode('.', $netmask);
1935   $res= 0;
1937   for ($n= 0; $n<4; $n++){
1938     $start= 255;
1939     $name= "nm$n";
1941     for ($i= 0; $i<8; $i++){
1942       if ($start == (int)($$name)){
1943         $res+= 8 - $i;
1944         break;
1945       }
1946       $start-= pow(2,$i);
1947     }
1948   }
1950   return ($res);
1954 /*! \brief Recursion helper for gen_id() */
1955 function recurse($rule, $variables)
1957   $result= array();
1959   if (!count($variables)){
1960     return array($rule);
1961   }
1963   reset($variables);
1964   $key= key($variables);
1965   $val= current($variables);
1966   unset ($variables[$key]);
1968   foreach($val as $possibility){
1969     $nrule= str_replace("{$key}", $possibility, $rule);
1970     $result= array_merge($result, recurse($nrule, $variables));
1971   }
1973   return ($result);
1977 /*! \brief Expands user ID based on possible rules
1978  *
1979  *  Unroll given rule string by filling in attributes.
1980  *
1981  * \param string 'rule' The rule string from gosa.conf.
1982  * \param array 'attributes' A dictionary of attribute/value mappings
1983  * \return string Expanded string, still containing the id keyword.
1984  */
1985 function expand_id($rule, $attributes)
1987   /* Check for id rule */
1988   if(preg_match('/^id(:|#|!)\d+$/',$rule)){
1989     return (array("{$rule}"));
1990   }
1992   /* Check for clean attribute */
1993   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1994     $rule= preg_replace('/^%/', '', $rule);
1995     $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
1996     return (array($val));
1997   }
1999   /* Check for attribute with parameters */
2000   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
2001     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
2002     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
2003     $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
2004     $start= preg_replace ('/-.*$/', '', $param);
2005     $stop = preg_replace ('/^[^-]+-/', '', $param);
2007     /* Assemble results */
2008     $result= array();
2009     for ($i= $start; $i<= $stop; $i++){
2010       $result[]= substr($val, 0, $i);
2011     }
2012     return ($result);
2013   }
2015   echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
2016   return (array($rule));
2020 /*! \brief Generate a list of uid proposals based on a rule
2021  *
2022  *  Unroll given rule string by filling in attributes and replacing
2023  *  all keywords.
2024  *
2025  * \param string 'rule' The rule string from gosa.conf.
2026  * \param array 'attributes' A dictionary of attribute/value mappings
2027  * \return array List of valid not used uids
2028  */
2029 function gen_uids($rule, $attributes)
2031   global $config;
2033   /* Search for keys and fill the variables array with all 
2034      possible values for that key. */
2035   $part= "";
2036   $trigger= false;
2037   $stripped= "";
2038   $variables= array();
2040   for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
2042     if ($rule[$pos] == "{" ){
2043       $trigger= true;
2044       $part= "";
2045       continue;
2046     }
2048     if ($rule[$pos] == "}" ){
2049       $variables[$pos]= expand_id($part, $attributes);
2050       $stripped.= "{".$pos."}";
2051       $trigger= false;
2052       continue;
2053     }
2055     if ($trigger){
2056       $part.= $rule[$pos];
2057     } else {
2058       $stripped.= $rule[$pos];
2059     }
2060   }
2062   /* Recurse through all possible combinations */
2063   $proposed= recurse($stripped, $variables);
2065   /* Get list of used ID's */
2066   $ldap= $config->get_ldap_link();
2067   $ldap->cd($config->current['BASE']);
2069   /* Remove used uids and watch out for id tags */
2070   $ret= array();
2071   foreach($proposed as $uid){
2073     /* Check for id tag and modify uid if needed */
2074     if(preg_match('/\{id(:|!)\d+}/',$uid, $m)){
2075       $size= preg_replace('/^.*{id(:|!)(\d+)}.*$/', '\\2', $uid);
2077       $start= $m[1]==":"?0:-1;
2078       for ($i= $start, $p= pow(10,$size)-1; $i < $p; $i++){
2079         if ($i == -1) {
2080           $number= "";
2081         } else {
2082           $number= sprintf("%0".$size."d", $i+1);
2083         }
2084         $res= preg_replace('/{id(:|!)\d+}/', $number, $uid);
2086         $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
2087         if($ldap->count() == 0){
2088           $uid= $res;
2089           break;
2090         }
2091       }
2093       /* Remove link if nothing has been found */
2094       $uid= preg_replace('/{id(:|!)\d+}/', '', $uid);
2095     }
2097     if(preg_match('/\{id#\d+}/',$uid)){
2098       $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
2100       while (true){
2101         mt_srand((double) microtime()*1000000);
2102         $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
2103         $res= preg_replace('/{id#(\d+)}/', $number, $uid);
2104         $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
2105         if($ldap->count() == 0){
2106           $uid= $res;
2107           break;
2108         }
2109       }
2111       /* Remove link if nothing has been found */
2112       $uid= preg_replace('/{id#\d+}/', '', $uid);
2113     }
2115     /* Don't assign used ones */
2116     $ldap->search("(uid=".preg_replace('/[{}]/', '', $uid).")",array('dn'));
2117     if($ldap->count() == 0){
2118       /* Add uid, but remove {} first. These are invalid anyway. */
2119       $ret[]= preg_replace('/[{}]/', '', $uid);
2120     }
2121   }
2123   return(array_unique($ret));
2127 /*! \brief Convert various data sizes to bytes
2128  *
2129  * Given a certain value in the format n(g|m|k), where n
2130  * is a value and (g|m|k) stands for Gigabyte, Megabyte and Kilobyte
2131  * this function returns the byte value.
2132  *
2133  * \param string 'value' a value in the above specified format
2134  * \return a byte value or the original value if specified string is simply
2135  * a numeric value
2136  *
2137  */
2138 function to_byte($value) {
2139   $value= strtolower(trim($value));
2141   if(!is_numeric(substr($value, -1))) {
2143     switch(substr($value, -1)) {
2144       case 'g':
2145         $mult= 1073741824;
2146         break;
2147       case 'm':
2148         $mult= 1048576;
2149         break;
2150       case 'k':
2151         $mult= 1024;
2152         break;
2153     }
2155     return ($mult * (int)substr($value, 0, -1));
2156   } else {
2157     return $value;
2158   }
2162 /*! \brief Check if a value exists in an array (case-insensitive)
2163  * 
2164  * This is just as http://php.net/in_array except that the comparison
2165  * is case-insensitive.
2166  *
2167  * \param string 'value' needle
2168  * \param array 'items' haystack
2169  */ 
2170 function in_array_ics($value, $items)
2172         return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
2176 /*! \brief Removes malicious characters from a (POST) string. */
2177 function validate($string)
2179   return (strip_tags(str_replace('\0', '', $string)));
2183 /*! \brief Evaluate the current GOsa version from the build in revision string */
2184 function get_gosa_version()
2186   global $svn_revision, $svn_path;
2188   /* Extract informations */
2189   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
2191   /* Release or development? */
2192   if (preg_match('%/gosa/trunk/%', $svn_path)){
2193     return (sprintf(_("GOsa development snapshot (Rev %s)"), bold($revision)));
2194   } else {
2195     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
2196     return (sprintf(_("GOsa $release"), $revision));
2197   }
2201 /*! \brief Recursively delete a path in the file system
2202  *
2203  * Will delete the given path and all its files recursively.
2204  * Can also follow links if told so.
2205  *
2206  * \param string 'path'
2207  * \param boolean 'followLinks' TRUE to follow links, FALSE (default)
2208  * for not following links
2209  */
2210 function rmdirRecursive($path, $followLinks=false) {
2211   $dir= opendir($path);
2212   while($entry= readdir($dir)) {
2213     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
2214       unlink($path."/".$entry);
2215     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
2216       rmdirRecursive($path."/".$entry);
2217     }
2218   }
2219   closedir($dir);
2220   return rmdir($path);
2224 /*! \brief Get directory content information
2225  *
2226  * Returns the content of a directory as an array in an
2227  * ascended sorted manner.
2228  *
2229  * \param string 'path'
2230  * \param boolean weither to sort the content descending.
2231  */
2232 function scan_directory($path,$sort_desc=false)
2234   $ret = false;
2236   /* is this a dir ? */
2237   if(is_dir($path)) {
2239     /* is this path a readable one */
2240     if(is_readable($path)){
2242       /* Get contents and write it into an array */   
2243       $ret = array();    
2245       $dir = opendir($path);
2247       /* Is this a correct result ?*/
2248       if($dir){
2249         while($fp = readdir($dir))
2250           $ret[]= $fp;
2251       }
2252     }
2253   }
2254   /* Sort array ascending , like scandir */
2255   sort($ret);
2257   /* Sort descending if parameter is sort_desc is set */
2258   if($sort_desc) {
2259     $ret = array_reverse($ret);
2260   }
2262   return($ret);
2266 /*! \brief Clean the smarty compile dir */
2267 function clean_smarty_compile_dir($directory)
2269   global $svn_revision;
2271   if(is_dir($directory) && is_readable($directory)) {
2272     // Set revision filename to REVISION
2273     $revision_file= $directory."/REVISION";
2275     /* Is there a stamp containing the current revision? */
2276     if(!file_exists($revision_file)) {
2277       // create revision file
2278       create_revision($revision_file, $svn_revision);
2279     } else {
2280       # check for "$config->...['CONFIG']/revision" and the
2281       # contents should match the revision number
2282       if(!compare_revision($revision_file, $svn_revision)){
2283         // If revision differs, clean compile directory
2284         foreach(scan_directory($directory) as $file) {
2285           if(($file==".")||($file=="..")) continue;
2286           if( is_file($directory."/".$file) &&
2287               is_writable($directory."/".$file)) {
2288             // delete file
2289             if(!unlink($directory."/".$file)) {
2290               msg_dialog::display(_("Internal error"), sprintf(_("File %s cannot be deleted!"), bold($directory."/".$file)), ERROR_DIALOG);
2291               // This should never be reached
2292             }
2293           } elseif(is_dir($directory."/".$file) &&
2294               is_writable($directory."/".$file)) {
2295             // Just recursively delete it
2296             rmdirRecursive($directory."/".$file);
2297           }
2298         }
2299         // We should now create a fresh revision file
2300         clean_smarty_compile_dir($directory);
2301       } else {
2302         // Revision matches, nothing to do
2303       }
2304     }
2305   } else {
2306     // Smarty compile dir is not accessible
2307     // (Smarty will warn about this)
2308   }
2312 function create_revision($revision_file, $revision)
2314   $result= false;
2316   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2317     if($fh= fopen($revision_file, "w")) {
2318       if(fwrite($fh, $revision)) {
2319         $result= true;
2320       }
2321     }
2322     fclose($fh);
2323   } else {
2324     msg_dialog::display(_("Internal error"), _("Cannot write revision file!"), ERROR_DIALOG);
2325   }
2327   return $result;
2331 function compare_revision($revision_file, $revision)
2333   // false means revision differs
2334   $result= false;
2336   if(file_exists($revision_file) && is_readable($revision_file)) {
2337     // Open file
2338     if($fh= fopen($revision_file, "r")) {
2339       // Compare File contents with current revision
2340       if($revision == fread($fh, filesize($revision_file))) {
2341         $result= true;
2342       }
2343     } else {
2344       msg_dialog::display(_("Internal error"), _("Cannot write revision file!"), ERROR_DIALOG);
2345     }
2346     // Close file
2347     fclose($fh);
2348   }
2350   return $result;
2354 /*! \brief Return HTML for a progressbar
2355  *
2356  * \code
2357  * $smarty->assign("installprogress", progressbar($current_progress_in_percent),100,15,true); 
2358  * \endcode
2359  *
2360  * \param int 'percentage' Value to display
2361  * \param int 'width' width of the resulting output
2362  * \param int 'height' height of the resulting output
2363  * \param boolean 'showtext' weither to show the percentage in the progressbar or not
2364  * */
2365 function progressbar($percentage, $width= 200, $height= 14, $showText= false, $colorize= true, $id= "")
2367   $text= "";
2368   $class= "";
2369   $style= "width:${width}px;height:${height}px;";
2371   // Fix percentage range
2372   $percentage= floor($percentage);
2373   if ($percentage > 100) {
2374     $percentage= 100;
2375   }
2376   if ($percentage < 0) {
2377     $percentage= 0;
2378   }
2380   // Only show text if we're above 10px height
2381   if ($showText && $height>10){
2382     $text= $percentage."%";
2383   }
2385   // Set font size
2386   $style.= "font-size:".($height-3)."px;";
2388   // Set color
2389   if ($colorize){
2390     if ($percentage < 70) {
2391       $class= " progress-low";
2392     } elseif ($percentage < 80) {
2393       $class= " progress-mid";
2394     } elseif ($percentage < 90) {
2395       $class= " progress-high";
2396     } else {
2397       $class= " progress-full";
2398     }
2399   }
2400   
2401   // Apply gradients
2402   $hoffset= floor($height / 2) + 4;
2403   $woffset= floor(($width+5) * (100-$percentage) / 100);
2404   foreach (array("-moz-box-shadow", "-webkit-box-shadow", "box-shadow") as $type) {
2405     $style.="$type:
2406                    0 0 2px rgba(255, 255, 255, 0.4) inset,
2407                    0 4px 6px rgba(255, 255, 255, 0.4) inset,
2408                    0 ".$hoffset."px 0 -2px rgba(255, 255, 255, 0.2) inset,
2409                    -".$woffset."px 0 0 -2px rgba(255, 255, 255, 0.2) inset,
2410                    -".($woffset+1)."px 0 0 -2px rgba(0, 0, 0, 0.6) inset,
2411                    0pt ".($hoffset+1)."px 8px rgba(0, 0, 0, 0.3) inset,
2412                    0pt 1px 0px rgba(0, 0, 0, 0.2);";
2413   }
2415   // Set ID
2416   if ($id != ""){
2417     $id= "id='$id'";
2418   }
2420   return "<div class='progress$class' $id style='$style'>$text</div>";
2424 /*! \brief Lookup a key in an array case-insensitive
2425  *
2426  * Given an associative array this can lookup the value of
2427  * a certain key, regardless of the case.
2428  *
2429  * \code
2430  * $items = array ('FOO' => 'blub', 'bar' => 'blub');
2431  * array_key_ics('foo', $items); # Returns 'blub'
2432  * array_key_ics('BAR', $items); # Returns 'blub'
2433  * \endcode
2434  *
2435  * \param string 'key' needle
2436  * \param array 'items' haystack
2437  */
2438 function array_key_ics($ikey, $items)
2440   $tmp= array_change_key_case($items, CASE_LOWER);
2441   $ikey= strtolower($ikey);
2442   if (isset($tmp[$ikey])){
2443     return($tmp[$ikey]);
2444   }
2446   return ('');
2450 /*! \brief Determine if two arrays are different
2451  *
2452  * \param array 'src'
2453  * \param array 'dst'
2454  * \return boolean TRUE or FALSE
2455  * */
2456 function array_differs($src, $dst)
2458   /* If the count is differing, the arrays differ */
2459   if (count ($src) != count ($dst)){
2460     return (TRUE);
2461   }
2463   return (count(array_diff($src, $dst)) != 0);
2467 function saveFilter($a_filter, $values)
2469   if (isset($_POST['regexit'])){
2470     $a_filter["regex"]= $_POST['regexit'];
2472     foreach($values as $type){
2473       if (isset($_POST[$type])) {
2474         $a_filter[$type]= "checked";
2475       } else {
2476         $a_filter[$type]= "";
2477       }
2478     }
2479   }
2481   /* React on alphabet links if needed */
2482   if (isset($_GET['search'])){
2483     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2484     if ($s == "**"){
2485       $s= "*";
2486     }
2487     $a_filter['regex']= $s;
2488   }
2490   return ($a_filter);
2494 /*! \brief Escape all LDAP filter relevant characters */
2495 function normalizeLdap($input)
2497   return (addcslashes($input, '()|'));
2501 /*! \brief Return the gosa base directory */
2502 function get_base_dir()
2504   global $BASE_DIR;
2506   return $BASE_DIR;
2510 /*! \brief Test weither we are allowed to read the object */
2511 function obj_is_readable($dn, $object, $attribute)
2513   global $ui;
2515   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2519 /*! \brief Test weither we are allowed to change the object */
2520 function obj_is_writable($dn, $object, $attribute)
2522   global $ui;
2524   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2528 /*! \brief Explode a DN into its parts
2529  *
2530  * Similar to explode (http://php.net/explode), but a bit more specific
2531  * for the needs when splitting, exploding LDAP DNs.
2532  *
2533  * \param string 'dn' the DN to split
2534  * \param config-object a config object. only neeeded if DN shall be verified in the LDAP
2535  * \param boolean verify_in_ldap check weither DN is valid
2536  *
2537  */
2538 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2540   /* Initialize variables */
2541   $ret  = array("count" => 0);  // Set count to 0
2542   $next = true;                 // if false, then skip next loops and return
2543   $cnt  = 0;                    // Current number of loops
2544   $max  = 100;                  // Just for security, prevent looops
2545   $ldap = NULL;                 // To check if created result a valid
2546   $keep = "";                   // save last failed parse string
2548   /* Check each parsed dn in ldap ? */
2549   if($config!==NULL && $verify_in_ldap){
2550     $ldap = $config->get_ldap_link();
2551   }
2553   /* Lets start */
2554   $called = false;
2555   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2557     $cnt ++;
2558     if(!preg_match("/,/",$dn)){
2559       $next = false;
2560     }
2561     $object = preg_replace("/[,].*$/","",$dn);
2562     $dn     = preg_replace("/^[^,]+,/","",$dn);
2564     $called = true;
2566     /* Check if current dn is valid */
2567     if($ldap!==NULL){
2568       $ldap->cd($dn);
2569       $ldap->cat($dn,array("dn"));
2570       if($ldap->count()){
2571         $ret[]  = $keep.$object;
2572         $keep   = "";
2573       }else{
2574         $keep  .= $object.",";
2575       }
2576     }else{
2577       $ret[]  = $keep.$object;
2578       $keep   = "";
2579     }
2580   }
2582   /* No dn was posted */
2583   if($cnt == 0 && !empty($dn)){
2584     $ret[] = $dn;
2585   }
2587   /* Append the rest */
2588   $test = $keep.$dn;
2589   if($called && !empty($test)){
2590     $ret[] = $keep.$dn;
2591   }
2592   $ret['count'] = count($ret) - 1;
2594   return($ret);
2598 function get_base_from_hook($dn, $attrib)
2600   global $config;
2602   if ($config->get_cfg_value("core","baseIdHook") != ""){
2603     
2604     /* Call hook script - if present */
2605     $command= $config->get_cfg_value("core","baseIdHook");
2607     if ($command != ""){
2608       $command.= " '".LDAP::fix($dn)."' $attrib";
2609       if (check_command($command)){
2610         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2611         exec($command, $output);
2612         if (preg_match("/^[0-9]+$/", $output[0])){
2613           return ($output[0]);
2614         } else {
2615           msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2616           return ($config->get_cfg_value("core","uidNumberBase"));
2617         }
2618       } else {
2619         msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2620         return ($config->get_cfg_value("core","uidNumberBase"));
2621       }
2623     } else {
2625       msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2626       return ($config->get_cfg_value("core","uidNumberBase"));
2628     }
2629   }
2633 /*! \brief Check if schema version matches the requirements */
2634 function check_schema_version($class, $version)
2636   return preg_match("/\(v$version\)/", $class['DESC']);
2640 /*! \brief Check if LDAP schema matches the requirements */
2641 function check_schema($cfg,$rfc2307bis = FALSE)
2643   $messages= array();
2645   /* Get objectclasses */
2646   $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2647   $objectclasses = $ldap->get_objectclasses();
2648   if(count($objectclasses) == 0){
2649     msg_dialog::display(_("Warning"), _("Cannot read schema information from LDAP. Schema validation is not possible!"), WARNING_DIALOG);
2650   }
2652   /* This is the default block used for each entry.
2653    *  to avoid unset indexes.
2654    */
2655   $def_check = array("REQUIRED_VERSION" => "0",
2656       "SCHEMA_FILES"     => array(),
2657       "CLASSES_REQUIRED" => array(),
2658       "STATUS"           => FALSE,
2659       "IS_MUST_HAVE"     => FALSE,
2660       "MSG"              => "",
2661       "INFO"             => "");
2663   /* The gosa base schema */
2664   $checks['gosaObject'] = $def_check;
2665   $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2666   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa-samba3.schema");
2667   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2668   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2670   /* GOsa Account class */
2671   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.6";
2672   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa-samba3.schema");
2673   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2674   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2675   $checks["gosaAccount"]["INFO"]            = _("This class is used to make users appear in GOsa.");
2677   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2678   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2679   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa-samba3.schema");
2680   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2681   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2682   $checks["gosaLockEntry"]["INFO"]             = _("This class is used to lock entries in order to prevent multiple edits at a time.");
2684   /* Some other checks */
2685   foreach(array(
2686         "gosaCacheEntry"        => array("version" => "2.6.1", "class" => "gosaAccount"),
2687         "gosaDepartment"        => array("version" => "2.6.1", "class" => "gosaAccount"),
2688         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2689         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2690         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2691         "gosaUserTemplate"      => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2692         "gosaMailAccount"       => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa-samba3.schema"),
2693         "gosaProxyAccount"      => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa-samba3.schema"),
2694         "gosaApplication"       => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2695         "gosaApplicationGroup"  => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2696         "GOhard"                => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2697         "gotoTerminal"          => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2698         "goServer"              => array("version" => "2.6.1", "class" => "server","file" => "goserver.schema"),
2699         "goTerminalServer"      => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2700         "goShareServer"         => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2701         "goNtpServer"           => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2702         "goSyslogServer"        => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2703         "goLdapServer"          => array("version" => "2.6.1", "class" => "goServer"),
2704         "goCupsServer"          => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2705         "goImapServer"          => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa-samba3.schema"),
2706         "goKrbServer"           => array("version" => "2.6.1", "class" => "goServer"),
2707         "goFaxServer"           => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2708         ) as $name => $values){
2710           $checks[$name] = $def_check;
2711           if(isset($values['version'])){
2712             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2713           }
2714           if(isset($values['file'])){
2715             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2716           }
2717           if (isset($values['class'])) {
2718             $checks[$name]["CLASSES_REQUIRED"] = is_array($values['class'])?$values['class']:array($values['class']);
2719           }
2720         }
2721   foreach($checks as $name => $value){
2722     foreach($value['CLASSES_REQUIRED'] as $class){
2724       if(!isset($objectclasses[$name])){
2725         if($value['IS_MUST_HAVE']){
2726           $checks[$name]['STATUS'] = FALSE;
2727           $checks[$name]['MSG']    = sprintf(_("Required object class %s is missing!"), bold($class));
2728         } else {
2729           $checks[$name]['STATUS'] = TRUE;
2730           $checks[$name]['MSG']    = sprintf(_("Optional object class %s is missing!"), bold($class));
2731         }
2732       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2733         $checks[$name]['STATUS'] = FALSE;
2735         $checks[$name]['MSG'] = sprintf(_("Wrong version of required object class %s (!=%s) detected!"), bold($class), bold($value['REQUIRED_VERSION']));
2736       }else{
2737         $checks[$name]['STATUS'] = TRUE;
2738         $checks[$name]['MSG'] = sprintf(_("Class available"));
2739       }
2740     }
2741   }
2743   $tmp = $objectclasses;
2745   /* The gosa base schema */
2746   $checks['posixGroup'] = $def_check;
2747   $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2748   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa-samba3.schema","gosa-samba2.schema");
2749   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2750   $checks['posixGroup']['STATUS']           = TRUE;
2751   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2752   $checks['posixGroup']['MSG']              = "";
2753   $checks['posixGroup']['INFO']             = "";
2755   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2756   if(isset($tmp['posixGroup'])){
2758     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2759       $checks['posixGroup']['STATUS']           = FALSE;
2760       $checks['posixGroup']['MSG']              = _("RFC 2307bis group schema is enabled, but the current LDAP configuration does not support it!");
2761       $checks['posixGroup']['INFO']             = _("To use RFC 2307bis groups, the objectClass 'posixGroup' must be AUXILIARY.");
2762     }
2763     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2764       $checks['posixGroup']['STATUS']           = FALSE;
2765       $checks['posixGroup']['MSG']              = _("RFC 2307bis group schema is disabled, but the current LDAP configuration supports it!");
2766       $checks['posixGroup']['INFO']             = _("To correct this, the objectClass 'posixGroup' must be STRUCTURAL.");
2767     }
2768   }
2770   return($checks);
2774 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2776   $tmp = array(
2777         "de_DE" => "German",
2778         "fr_FR" => "French",
2779         "it_IT" => "Italian",
2780         "es_ES" => "Spanish",
2781         "en_US" => "English",
2782         "nl_NL" => "Dutch",
2783         "pl_PL" => "Polish",
2784         "pt_BR" => "Brazilian Portuguese",
2785         #"sv_SE" => "Swedish",
2786         "zh_CN" => "Chinese",
2787         "vi_VN" => "Vietnamese",
2788         "ru_RU" => "Russian");
2789   
2790   $tmp2= array(
2791         "de_DE" => _("German"),
2792         "fr_FR" => _("French"),
2793         "it_IT" => _("Italian"),
2794         "es_ES" => _("Spanish"),
2795         "en_US" => _("English"),
2796         "nl_NL" => _("Dutch"),
2797         "pl_PL" => _("Polish"),
2798         "pt_BR" => _("Brazilian Portuguese"),
2799         #"sv_SE" => _("Swedish"),
2800         "zh_CN" => _("Chinese"),
2801         "vi_VN" => _("Vietnamese"),
2802         "ru_RU" => _("Russian"));
2804   $ret = array();
2805   if($languages_in_own_language){
2807     $old_lang = setlocale(LC_ALL, 0);
2809     /* If the locale wasn't correclty set before, there may be an incorrect
2810         locale returned. Something like this: 
2811           C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2812         Extract the locale name from this string and use it to restore old locale.
2813      */
2814     if(preg_match("/LC_CTYPE/",$old_lang)){
2815       $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2816     }
2817     
2818     foreach($tmp as $key => $name){
2819       $lang = $key.".UTF-8";
2820       setlocale(LC_ALL, $lang);
2821       if($strip_region_tag){
2822         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2823       }else{
2824         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2825       }
2826     }
2827     setlocale(LC_ALL, $old_lang);
2828   }else{
2829     foreach($tmp as $key => $name){
2830       if($strip_region_tag){
2831         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2832       }else{
2833         $ret[$key] = _($name);
2834       }
2835     }
2836   }
2837   return($ret);
2841 /*! \brief Returns contents of the given POST variable and check magic quotes settings
2842  *
2843  * Depending on the magic quotes settings this returns a stripclashed'ed version of
2844  * a certain POST variable.
2845  *
2846  * \param string 'name' the POST var to return ($_POST[$name])
2847  * \return string
2848  * */
2849 function get_post($name)
2851   if(!isset($_POST[$name])){
2852     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2853     return(FALSE);
2854   }
2856   if(get_magic_quotes_gpc()){
2857     return(stripcslashes(validate($_POST[$name])));
2858   }else{
2859     return(validate($_POST[$name]));
2860   }
2864 /*! \brief Return class name in correct case */
2865 function get_correct_class_name($cls)
2867   global $class_mapping;
2868   if(isset($class_mapping) && is_array($class_mapping)){
2869     foreach($class_mapping as $class => $file){
2870       if(preg_match("/^".$cls."$/i",$class)){
2871         return($class);
2872       }
2873     }
2874   }
2875   return(FALSE);
2879 /*! \brief Change the password of a given DN
2880  * 
2881  * Change the password of a given DN with the specified hash.
2882  *
2883  * \param string 'dn' the DN whose password shall be changed
2884  * \param string 'password' the password
2885  * \param int mode
2886  * \param string 'hash' which hash to use to encrypt it, default is empty
2887  * for cleartext storage.
2888  * \return boolean TRUE on success FALSE on error
2889  */
2890 function change_password ($dn, $password, $mode=0, $hash= "")
2892   global $config;
2893   $newpass= "";
2895   /* Convert to lower. Methods are lowercase */
2896   $hash= strtolower($hash);
2898   // Get all available encryption Methods
2900   // NON STATIC CALL :)
2901   $methods = new passwordMethod(session::get('config'),$dn);
2902   $available = $methods->get_available_methods();
2904   // read current password entry for $dn, to detect the encryption Method
2905   $ldap       = $config->get_ldap_link();
2906   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2907   $attrs      = $ldap->fetch ();
2909   /* Is ensure that clear passwords will stay clear */
2910   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2911     $hash = "clear";
2912   }
2914   // Detect the encryption Method
2915   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2917     /* Check for supported algorithm */
2918     mt_srand((double) microtime()*1000000);
2920     /* Extract used hash */
2921     if ($hash == ""){
2922       $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2923     } else {
2924       $test = new $available[$hash]($config,$dn);
2925       $test->set_hash($hash);
2926     }
2928   } else {
2929     // User MD5 by default
2930     $hash= "md5";
2931     $test = new  $available['md5']($config, $dn);
2932   }
2934   if($test instanceOf passwordMethod){
2936     $deactivated = $test->is_locked($config,$dn);
2938     /* Feed password backends with information */
2939     $test->dn= $dn;
2940     $test->attrs= $attrs;
2941     $newpass= $test->generate_hash($password);
2943     // Update shadow timestamp?
2944     if (isset($attrs["shadowLastChange"][0])){
2945       $shadow= (int)(date("U") / 86400);
2946     } else {
2947       $shadow= 0;
2948     }
2950     // Write back modified entry
2951     $ldap->cd($dn);
2952     $attrs= array();
2954     // Not for groups
2955     if ($mode == 0){
2956       // Create SMB Password
2957       $attrs= generate_smb_nt_hash($password);
2959       if ($shadow != 0){
2960         $attrs['shadowLastChange']= $shadow;
2961       }
2962     }
2964     $attrs['userPassword']= array();
2965     $attrs['userPassword']= $newpass;
2967     $ldap->modify($attrs);
2969     /* Read ! if user was deactivated */
2970     if($deactivated){
2971       $test->lock_account($config,$dn);
2972     }
2974     new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2976     if (!$ldap->success()) {
2977       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2978     } else {
2980       /* Run backend method for change/create */
2981       if(!$test->set_password($password)){
2982         return(FALSE);
2983       }
2985       /* Find postmodify entries for this class */
2986       $command= $config->get_cfg_value("password","postmodify");
2988       if ($command != ""){
2989         /* Walk through attribute list */
2990         $command= preg_replace("/%userPassword/", $password, $command);
2991         $command= preg_replace("/%dn/", $dn, $command);
2993         if (check_command($command)){
2994           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2995           exec($command);
2996         } else {
2997           $message= sprintf(_("Command %s specified as post modify action for plugin %s does not exist!"), bold($command), bold("password"));
2998           msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2999         }
3000       }
3001     }
3002     return(TRUE);
3003   }
3007 /*! \brief Generate samba hashes
3008  *
3009  * Given a certain password this constructs an array like
3010  * array['sambaLMPassword'] etc.
3011  *
3012  * \param string 'password'
3013  * \return array contains several keys for lmPassword, ntPassword, pwdLastSet, etc. depending
3014  * on the samba version
3015  */
3016 function generate_smb_nt_hash($password)
3018   global $config;
3020   # Try to use gosa-si?
3021   if ($config->get_cfg_value("core","gosaSupportURI") != ""){
3022         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
3023     if (isset($res['XML']['HASH'])){
3024         $hash= $res['XML']['HASH'];
3025     } else {
3026       $hash= "";
3027     }
3029     if ($hash == "") {
3030       msg_dialog::display(_("Configuration error"), _("Cannot generate SAMBA hash!"), ERROR_DIALOG);
3031       return ("");
3032     }
3033   } else {
3034           $tmp= $config->get_cfg_value("core",'sambaHashHook')." ".escapeshellarg($password);
3035           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
3037           exec($tmp, $ar);
3038           flush();
3039           reset($ar);
3040           $hash= current($ar);
3042     if ($hash == "") {
3043       msg_dialog::display(_("Configuration error"), sprintf(_("Generating SAMBA hash by running %s failed: check %s!"), bold($config->get_cfg_value("core",'sambaHashHook'), bold("sambaHashHook"))), ERROR_DIALOG);
3044       return ("");
3045     }
3046   }
3048   list($lm,$nt)= explode(":", trim($hash));
3050   $attrs['sambaLMPassword']= $lm;
3051   $attrs['sambaNTPassword']= $nt;
3052   $attrs['sambaPwdLastSet']= date('U');
3053   $attrs['sambaBadPasswordCount']= "0";
3054   $attrs['sambaBadPasswordTime']= "0";
3055   return($attrs);
3059 /*! \brief Get the Change Sequence Number of a certain DN
3060  *
3061  * To verify if a given object has been changed outside of Gosa
3062  * in the meanwhile, this function can be used to get the entryCSN
3063  * from the LDAP directory. It uses the attribute as configured
3064  * in modificationDetectionAttribute
3065  *
3066  * \param string 'dn'
3067  * \return either the result or "" in any other case
3068  */
3069 function getEntryCSN($dn)
3071   global $config;
3072   if(empty($dn) || !is_object($config)){
3073     return("");
3074   }
3076   /* Get attribute that we should use as serial number */
3077   $attr= $config->get_cfg_value("core","modificationDetectionAttribute");
3078   if($attr != ""){
3079     $ldap = $config->get_ldap_link();
3080     $ldap->cat($dn,array($attr));
3081     $csn = $ldap->fetch();
3082     if(isset($csn[$attr][0])){
3083       return($csn[$attr][0]);
3084     }
3085   }
3086   return("");
3090 /*! \brief Add (a) given objectClass(es) to an attrs entry
3091  * 
3092  * The function adds the specified objectClass(es) to the given
3093  * attrs entry.
3094  *
3095  * \param mixed 'classes' Either a single objectClass or several objectClasses
3096  * as an array
3097  * \param array 'attrs' The attrs array to be modified.
3098  *
3099  * */
3100 function add_objectClass($classes, &$attrs)
3102   if (is_array($classes)){
3103     $list= $classes;
3104   } else {
3105     $list= array($classes);
3106   }
3108   foreach ($list as $class){
3109     $attrs['objectClass'][]= $class;
3110   }
3114 /*! \brief Removes a given objectClass from the attrs entry
3115  *
3116  * Similar to add_objectClass, except that it removes the given
3117  * objectClasses. See it for the params.
3118  * */
3119 function remove_objectClass($classes, &$attrs)
3121   if (isset($attrs['objectClass'])){
3122     /* Array? */
3123     if (is_array($classes)){
3124       $list= $classes;
3125     } else {
3126       $list= array($classes);
3127     }
3129     $tmp= array();
3130     foreach ($attrs['objectClass'] as $oc) {
3131       foreach ($list as $class){
3132         if (strtolower($oc) != strtolower($class)){
3133           $tmp[]= $oc;
3134         }
3135       }
3136     }
3137     $attrs['objectClass']= $tmp;
3138   }
3142 /*! \brief  Initialize a file download with given content, name and data type. 
3143  *  \param  string data The content to send.
3144  *  \param  string name The name of the file.
3145  *  \param  string type The content identifier, default value is "application/octet-stream";
3146  */
3147 function send_binary_content($data,$name,$type = "application/octet-stream")
3149   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
3150   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
3151   header("Cache-Control: no-cache");
3152   header("Pragma: no-cache");
3153   header("Cache-Control: post-check=0, pre-check=0");
3154   header("Content-type: ".$type."");
3156   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
3158   /* Strip name if it is a complete path */
3159   if (preg_match ("/\//", $name)) {
3160         $name= basename($name);
3161   }
3162   
3163   /* force download dialog */
3164   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
3165     header('Content-Disposition: filename="'.$name.'"');
3166   } else {
3167     header('Content-Disposition: attachment; filename="'.$name.'"');
3168   }
3170   echo $data;
3171   exit();
3175 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
3177   if(is_string($str)){
3178     return(htmlentities($str,$type,$charset));
3179   }elseif(is_array($str)){
3180     foreach($str as $name => $value){
3181       $str[$name] = reverse_html_entities($value,$type,$charset);
3182     }
3183   }
3184   return($str);
3188 /*! \brief Encode special string characters so we can use the string in \
3189            HTML output, without breaking quotes.
3190     \param string The String we want to encode.
3191     \return string The encoded String
3192  */
3193 function xmlentities($str)
3194
3195   if(is_string($str)){
3197     static $asc2uni= array();
3198     if (!count($asc2uni)){
3199       for($i=128;$i<256;$i++){
3200     #    $asc2uni[chr($i)] = "&#x".dechex($i).";";
3201       }
3202     }
3204     $str = str_replace("&", "&amp;", $str);
3205     $str = str_replace("<", "&lt;", $str);
3206     $str = str_replace(">", "&gt;", $str);
3207     $str = str_replace("'", "&apos;", $str);
3208     $str = str_replace("\"", "&quot;", $str);
3209     $str = str_replace("\r", "", $str);
3210     $str = strtr($str,$asc2uni);
3211     return $str;
3212   }elseif(is_array($str)){
3213     foreach($str as $name => $value){
3214       $str[$name] = xmlentities($value);
3215     }
3216   }
3217   return($str);
3221 /*! \brief  Updates all accessTo attributes from a given value to a new one.
3222             For example if a host is renamed.
3223     \param  String  $from The source accessTo name.
3224     \param  String  $to   The destination accessTo name.
3225 */
3226 function update_accessTo($from,$to)
3228   global $config;
3229   $ldap = $config->get_ldap_link();
3230   $ldap->cd($config->current['BASE']);
3231   $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
3232   while($attrs = $ldap->fetch()){
3233     $new_attrs = array("accessTo" => array());
3234     $dn = $attrs['dn'];
3235     for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
3236       $new_attrs['objectClass'][] =  $attrs['objectClass'][$i];
3237     }
3238     for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
3239       if($attrs['accessTo'][$i] == $from){
3240         if(!empty($to)){
3241           $new_attrs['accessTo'][] =  $to;
3242         }
3243       }else{
3244         $new_attrs['accessTo'][] =  $attrs['accessTo'][$i]; 
3245       }
3246     }
3247     $ldap->cd($dn);
3248     $ldap->modify($new_attrs);
3249     if (!$ldap->success()){
3250       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
3251     }
3252     new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
3253   }
3257 /*! \brief Returns a random char */
3258 function get_random_char () {
3259      $randno = rand (0, 63);
3260      if ($randno < 12) {
3261          return (chr ($randno + 46)); // Digits, '/' and '.'
3262      } else if ($randno < 38) {
3263          return (chr ($randno + 53)); // Uppercase
3264      } else {
3265          return (chr ($randno + 59)); // Lowercase
3266      }
3270 function cred_encrypt($input, $password) {
3272   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3273   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3275   return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
3280 function cred_decrypt($input,$password) {
3281   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3282   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3284   return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
3288 function get_object_info()
3290   return(session::get('objectinfo'));
3294 function set_object_info($str = "")
3296   session::set('objectinfo',$str);
3300 function isIpInNet($ip, $net, $mask) {
3301    // Move to long ints
3302    $ip= ip2long($ip);
3303    $net= ip2long($net);
3304    $mask= ip2long($mask);
3306    // Mask given IP with mask. If it returns "net", we're in...
3307    $res= $ip & $mask;
3309    return ($res == $net);
3313 function get_next_id($attrib, $dn)
3315   global $config;
3317   switch ($config->get_cfg_value("core","idAllocationMethod")){
3318     case "pool":
3319       return get_next_id_pool($attrib);
3320     case "traditional":
3321       return get_next_id_traditional($attrib, $dn);
3322   }
3324   msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("unknown idAllocation method!"), ERROR_DIALOG);
3325   return null;
3329 function get_next_id_pool($attrib) {
3330   global $config;
3332   /* Fill informational values */
3333   $min= $config->get_cfg_value("core","${attrib}PoolMin");
3334   $max= $config->get_cfg_value("core","${attrib}PoolMax");
3336   /* Sanity check */
3337   if ($min >= $max) {
3338     msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." ".sprintf(_("%sPoolMin >= %sPoolMax!"), bold($attrib), bold($attrib)), ERROR_DIALOG);
3339     return null;
3340   }
3342   /* ID to skip */
3343   $ldap= $config->get_ldap_link();
3344   $id= null;
3346   /* Try to allocate the ID several times before failing */
3347   $tries= 3;
3348   while ($tries--) {
3350     /* Look for ID map entry */
3351     $ldap->cd ($config->current['BASE']);
3352     $ldap->search ("(&(objectClass=sambaUnixIdPool)($attrib=*))", array("$attrib"));
3354     /* If it does not exist, create one with these defaults */
3355     if ($ldap->count() == 0) {
3356       /* Fill informational values */
3357       $minUserId= $config->get_cfg_value("core","uidNumberPoolMin");
3358       $minGroupId= $config->get_cfg_value("core","gidNumberPoolMin");
3360       /* Add as default */
3361       $attrs= array("objectClass" => array("organizationalUnit", "sambaUnixIdPool"));
3362       $attrs["ou"]= "idmap";
3363       $attrs["uidNumber"]= $minUserId;
3364       $attrs["gidNumber"]= $minGroupId;
3365       $ldap->cd("ou=idmap,".$config->current['BASE']);
3366       $ldap->add($attrs);
3367       if ($ldap->error != "Success") {
3368         msg_dialog::display(_("Error"), _("Cannot create sambaUnixIdPool entry!"), ERROR_DIALOG);
3369         return null;
3370       }
3371       $tries++;
3372       continue;
3373     }
3374     /* Bail out if it's not unique */
3375     if ($ldap->count() != 1) {
3376       msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("sambaUnixIdPool is not unique!"), ERROR_DIALOG);
3377       return null;
3378     }
3380     /* Store old attrib and generate new */
3381     $attrs= $ldap->fetch();
3382     $dn= $ldap->getDN();
3383     $oldAttr= $attrs[$attrib][0];
3384     $newAttr= $oldAttr + 1;
3386     /* Sanity check */
3387     if ($newAttr >= $max) {
3388       msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("no ID available!"), ERROR_DIALOG);
3389       return null;
3390     }
3391     if ($newAttr < $min) {
3392       msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("no ID available!"), ERROR_DIALOG);
3393       return null;
3394     }
3396     #FIXME: PHP is not able to do a modification of "del: .../add: ...", so this
3397     #       is completely unsafe in the moment.
3398     #/* Remove old attr, add new attr */
3399     #$attrs= array($attrib => $oldAttr);
3400     #$ldap->rm($attrs, $dn);
3401     #if ($ldap->error != "Success") {
3402     #  continue;
3403     #}
3404     $ldap->cd($dn);
3405     $ldap->modify(array($attrib => $newAttr));
3406     if ($ldap->error != "Success") {
3407       msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." ".$ldap->get_error(), ERROR_DIALOG);
3408       return null;
3409     } else {
3410       return $oldAttr;
3411     }
3412   }
3414   /* Bail out if we had problems getting the next id */
3415   if (!$tries) {
3416     msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("maximum number of tries exceeded!"), ERROR_DIALOG);
3417   }
3419   return $id;
3423 function get_next_id_traditional($attrib, $dn)
3425   global $config;
3427   $ids= array();
3428   $ldap= $config->get_ldap_link();
3430   $ldap->cd ($config->current['BASE']);
3431   if (preg_match('/gidNumber/i', $attrib)){
3432     $oc= "posixGroup";
3433   } else {
3434     $oc= "posixAccount";
3435   }
3436   $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
3438   /* Get list of ids */
3439   while ($attrs= $ldap->fetch()){
3440     $ids[]= (int)$attrs["$attrib"][0];
3441   }
3443   /* Add the nobody id */
3444   $ids[]= 65534;
3446   /* get the ranges */
3447   $tmp = array('0'=> 1000);
3448   if (preg_match('/posixAccount/', $oc) && $config->get_cfg_value("core","uidNumberBase") != ""){
3449     $tmp= explode('-',$config->get_cfg_value("core","uidNumberBase"));
3450   } elseif($config->get_cfg_value("core","gidNumberBase") != ""){
3451     $tmp= explode('-',$config->get_cfg_value("core","gidNumberBase"));
3452   }
3454   /* Set hwm to max if not set - for backward compatibility */
3455   $lwm= $tmp[0];
3456   if (isset($tmp[1])){
3457     $hwm= $tmp[1];
3458   } else {
3459     $hwm= pow(2,32);
3460   }
3461   /* Find out next free id near to UID_BASE */
3462   if ($config->get_cfg_value("core","baseIdHook") == ""){
3463     $base= $lwm;
3464   } else {
3465     /* Call base hook */
3466     $base= get_base_from_hook($dn, $attrib);
3467   }
3468   for ($id= $base; $id++; $id < pow(2,32)){
3469     if (!in_array($id, $ids)){
3470       return ($id);
3471     }
3472   }
3474   /* Should not happen */
3475   if ($id == $hwm){
3476     msg_dialog::display(_("Error"), _("Cannot allocate free ID!"), ERROR_DIALOG);
3477     exit;
3478   }
3482 /* Mark the occurance of a string with a span */
3483 function mark($needle, $haystack, $ignorecase= true)
3485   $result= "";
3487   while (preg_match('/^(.*)('.preg_quote($needle).')(.*)$/i', $haystack, $matches)) {
3488     $result.= $matches[1]."<span class='mark'>".$matches[2]."</span>";
3489     $haystack= $matches[3];
3490   }
3492   return $result.$haystack;
3496 /* Return an image description using the path */
3497 function image($path, $action= "", $title= "", $align= "middle")
3499   global $config;
3500   global $BASE_DIR;
3501   $label= null;
3503   // Bail out, if there's no style file
3504   if(!session::global_is_set("img-styles")){
3506     // Get theme
3507     if (isset ($config)){
3508       $theme= $config->get_cfg_value("core","theme");
3509     } else {
3511       // Fall back to default theme
3512       $theme= "default";
3513     }
3515     if (!file_exists("$BASE_DIR/ihtml/themes/$theme/img.styles")){
3516       die ("No img.style for this theme found!");
3517     }
3519     session::global_set('img-styles', unserialize(file_get_contents("$BASE_DIR/ihtml/themes/$theme/img.styles")));
3520   }
3521   $styles= session::global_get('img-styles');
3523   /* Extract labels from path */
3524   if (preg_match("/\.png\[(.*)\]$/", $path, $matches)) {
3525     $label= $matches[1];
3526   }
3528   $lbl= "";
3529   if ($label) {
3530     if (isset($styles["images/label-".$label.".png"])) {
3531       $lbl= "<div style='".$styles["images/label-".$label.".png"]."'></div>";
3532     } else {
3533       die("Invalid label specified: $label\n");
3534     }
3536     $path= preg_replace("/\[.*\]$/", "", $path);
3537   }
3539   // Non middle layout?
3540   if ($align == "middle") {
3541     $align= "";
3542   } else {
3543     $align= ";vertical-align:$align";
3544   }
3546   // Clickable image or not?
3547   if ($title != "") {
3548     $title= "title='$title'";
3549   }
3550   if ($action == "") {
3551     return "<div class='img' $title style='".$styles[$path]."$align'>$lbl</div>";
3552   } else {
3553     return "<input type='submit' class='img' id='$action' value='' name='$action' $title style='".$styles[$path]."$align'>";
3554   }
3557 /*! \brief    Encodes a complex string to be useable in HTML posts.
3558  */
3559 function postEncode($str)
3561   return(preg_replace("/=/","_", base64_encode($str)));
3564 /*! \brief    Decodes a string encoded by postEncode
3565  */
3566 function postDecode($str)
3568   return(base64_decode(preg_replace("/_/","=", $str)));
3572 /*! \brief    Generate styled output
3573  */
3574 function bold($str)
3576   return "<span class='highlight'>$str</span>";
3580 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3581 ?>