Code

Updated function.inc -> update_accessTo
[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     // Extract the relevant part out of the svn url
2192     $release= preg_replace('%^.*/gosa/(.*)/include/functions.inc.*$%', '\1', $svn_path);
2194     // Remove stuff which is not interesting
2195     if(preg_match("/gosa-core/i", $release)) $release = preg_replace("/[\/]gosa-core/i","",$release);
2197     // A Tagged Version
2198     if(preg_match("#/tags/#i", $svn_path)){
2199         $release = preg_replace("/tags[\/]*/i","",$release);
2200         $release = preg_replace("/\//","",$release) ;
2201         return (sprintf(_("GOsa %s"),$release));
2202     }
2204     // A Branched Version
2205     if(preg_match("#/branches/#i", $svn_path)){
2206         $release = preg_replace("/branches[\/]*/i","",$release);
2207         $release = preg_replace("/\//","",$release) ;
2208         return (sprintf(_("GOsa %s snapshot (Rev %s)"),$release , bold($revision)));
2209     }
2211     // The trunk version
2212     if(preg_match("#/trunk/#i", $svn_path)){
2213         return (sprintf(_("GOsa development snapshot (Rev %s)"), bold($revision)));
2214     }
2216     return (sprintf(_("GOsa $release"), $revision));
2220 /*! \brief Recursively delete a path in the file system
2221  *
2222  * Will delete the given path and all its files recursively.
2223  * Can also follow links if told so.
2224  *
2225  * \param string 'path'
2226  * \param boolean 'followLinks' TRUE to follow links, FALSE (default)
2227  * for not following links
2228  */
2229 function rmdirRecursive($path, $followLinks=false) {
2230   $dir= opendir($path);
2231   while($entry= readdir($dir)) {
2232     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
2233       unlink($path."/".$entry);
2234     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
2235       rmdirRecursive($path."/".$entry);
2236     }
2237   }
2238   closedir($dir);
2239   return rmdir($path);
2243 /*! \brief Get directory content information
2244  *
2245  * Returns the content of a directory as an array in an
2246  * ascended sorted manner.
2247  *
2248  * \param string 'path'
2249  * \param boolean weither to sort the content descending.
2250  */
2251 function scan_directory($path,$sort_desc=false)
2253   $ret = false;
2255   /* is this a dir ? */
2256   if(is_dir($path)) {
2258     /* is this path a readable one */
2259     if(is_readable($path)){
2261       /* Get contents and write it into an array */   
2262       $ret = array();    
2264       $dir = opendir($path);
2266       /* Is this a correct result ?*/
2267       if($dir){
2268         while($fp = readdir($dir))
2269           $ret[]= $fp;
2270       }
2271     }
2272   }
2273   /* Sort array ascending , like scandir */
2274   sort($ret);
2276   /* Sort descending if parameter is sort_desc is set */
2277   if($sort_desc) {
2278     $ret = array_reverse($ret);
2279   }
2281   return($ret);
2285 /*! \brief Clean the smarty compile dir */
2286 function clean_smarty_compile_dir($directory)
2288   global $svn_revision;
2290   if(is_dir($directory) && is_readable($directory)) {
2291     // Set revision filename to REVISION
2292     $revision_file= $directory."/REVISION";
2294     /* Is there a stamp containing the current revision? */
2295     if(!file_exists($revision_file)) {
2296       // create revision file
2297       create_revision($revision_file, $svn_revision);
2298     } else {
2299       # check for "$config->...['CONFIG']/revision" and the
2300       # contents should match the revision number
2301       if(!compare_revision($revision_file, $svn_revision)){
2302         // If revision differs, clean compile directory
2303         foreach(scan_directory($directory) as $file) {
2304           if(($file==".")||($file=="..")) continue;
2305           if( is_file($directory."/".$file) &&
2306               is_writable($directory."/".$file)) {
2307             // delete file
2308             if(!unlink($directory."/".$file)) {
2309               msg_dialog::display(_("Internal error"), sprintf(_("File %s cannot be deleted!"), bold($directory."/".$file)), ERROR_DIALOG);
2310               // This should never be reached
2311             }
2312           } elseif(is_dir($directory."/".$file) &&
2313               is_writable($directory."/".$file)) {
2314             // Just recursively delete it
2315             rmdirRecursive($directory."/".$file);
2316           }
2317         }
2318         // We should now create a fresh revision file
2319         clean_smarty_compile_dir($directory);
2320       } else {
2321         // Revision matches, nothing to do
2322       }
2323     }
2324   } else {
2325     // Smarty compile dir is not accessible
2326     // (Smarty will warn about this)
2327   }
2331 function create_revision($revision_file, $revision)
2333   $result= false;
2335   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2336     if($fh= fopen($revision_file, "w")) {
2337       if(fwrite($fh, $revision)) {
2338         $result= true;
2339       }
2340     }
2341     fclose($fh);
2342   } else {
2343     msg_dialog::display(_("Internal error"), _("Cannot write revision file!"), ERROR_DIALOG);
2344   }
2346   return $result;
2350 function compare_revision($revision_file, $revision)
2352   // false means revision differs
2353   $result= false;
2355   if(file_exists($revision_file) && is_readable($revision_file)) {
2356     // Open file
2357     if($fh= fopen($revision_file, "r")) {
2358       // Compare File contents with current revision
2359       if($revision == fread($fh, filesize($revision_file))) {
2360         $result= true;
2361       }
2362     } else {
2363       msg_dialog::display(_("Internal error"), _("Cannot write revision file!"), ERROR_DIALOG);
2364     }
2365     // Close file
2366     fclose($fh);
2367   }
2369   return $result;
2373 /*! \brief Return HTML for a progressbar
2374  *
2375  * \code
2376  * $smarty->assign("installprogress", progressbar($current_progress_in_percent),100,15,true); 
2377  * \endcode
2378  *
2379  * \param int 'percentage' Value to display
2380  * \param int 'width' width of the resulting output
2381  * \param int 'height' height of the resulting output
2382  * \param boolean 'showtext' weither to show the percentage in the progressbar or not
2383  * */
2384 function progressbar($percentage, $width= 200, $height= 14, $showText= false, $colorize= true, $id= "")
2386   $text= "";
2387   $class= "";
2388   $style= "width:${width}px;height:${height}px;";
2390   // Fix percentage range
2391   $percentage= floor($percentage);
2392   if ($percentage > 100) {
2393     $percentage= 100;
2394   }
2395   if ($percentage < 0) {
2396     $percentage= 0;
2397   }
2399   // Only show text if we're above 10px height
2400   if ($showText && $height>10){
2401     $text= $percentage."%";
2402   }
2404   // Set font size
2405   $style.= "font-size:".($height-3)."px;";
2407   // Set color
2408   if ($colorize){
2409     if ($percentage < 70) {
2410       $class= " progress-low";
2411     } elseif ($percentage < 80) {
2412       $class= " progress-mid";
2413     } elseif ($percentage < 90) {
2414       $class= " progress-high";
2415     } else {
2416       $class= " progress-full";
2417     }
2418   }
2419   
2420   // Apply gradients
2421   $hoffset= floor($height / 2) + 4;
2422   $woffset= floor(($width+5) * (100-$percentage) / 100);
2423   foreach (array("-moz-box-shadow", "-webkit-box-shadow", "box-shadow") as $type) {
2424     $style.="$type:
2425                    0 0 2px rgba(255, 255, 255, 0.4) inset,
2426                    0 4px 6px rgba(255, 255, 255, 0.4) inset,
2427                    0 ".$hoffset."px 0 -2px rgba(255, 255, 255, 0.2) inset,
2428                    -".$woffset."px 0 0 -2px rgba(255, 255, 255, 0.2) inset,
2429                    -".($woffset+1)."px 0 0 -2px rgba(0, 0, 0, 0.6) inset,
2430                    0pt ".($hoffset+1)."px 8px rgba(0, 0, 0, 0.3) inset,
2431                    0pt 1px 0px rgba(0, 0, 0, 0.2);";
2432   }
2434   // Set ID
2435   if ($id != ""){
2436     $id= "id='$id'";
2437   }
2439   return "<div class='progress$class' $id style='$style'>$text</div>";
2443 /*! \brief Lookup a key in an array case-insensitive
2444  *
2445  * Given an associative array this can lookup the value of
2446  * a certain key, regardless of the case.
2447  *
2448  * \code
2449  * $items = array ('FOO' => 'blub', 'bar' => 'blub');
2450  * array_key_ics('foo', $items); # Returns 'blub'
2451  * array_key_ics('BAR', $items); # Returns 'blub'
2452  * \endcode
2453  *
2454  * \param string 'key' needle
2455  * \param array 'items' haystack
2456  */
2457 function array_key_ics($ikey, $items)
2459   $tmp= array_change_key_case($items, CASE_LOWER);
2460   $ikey= strtolower($ikey);
2461   if (isset($tmp[$ikey])){
2462     return($tmp[$ikey]);
2463   }
2465   return ('');
2469 /*! \brief Determine if two arrays are different
2470  *
2471  * \param array 'src'
2472  * \param array 'dst'
2473  * \return boolean TRUE or FALSE
2474  * */
2475 function array_differs($src, $dst)
2477   /* If the count is differing, the arrays differ */
2478   if (count ($src) != count ($dst)){
2479     return (TRUE);
2480   }
2482   return (count(array_diff($src, $dst)) != 0);
2486 function saveFilter($a_filter, $values)
2488   if (isset($_POST['regexit'])){
2489     $a_filter["regex"]= $_POST['regexit'];
2491     foreach($values as $type){
2492       if (isset($_POST[$type])) {
2493         $a_filter[$type]= "checked";
2494       } else {
2495         $a_filter[$type]= "";
2496       }
2497     }
2498   }
2500   /* React on alphabet links if needed */
2501   if (isset($_GET['search'])){
2502     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2503     if ($s == "**"){
2504       $s= "*";
2505     }
2506     $a_filter['regex']= $s;
2507   }
2509   return ($a_filter);
2513 /*! \brief Escape all LDAP filter relevant characters */
2514 function normalizeLdap($input)
2516   return (addcslashes($input, '()|'));
2520 /*! \brief Return the gosa base directory */
2521 function get_base_dir()
2523   global $BASE_DIR;
2525   return $BASE_DIR;
2529 /*! \brief Test weither we are allowed to read the object */
2530 function obj_is_readable($dn, $object, $attribute)
2532   global $ui;
2534   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2538 /*! \brief Test weither we are allowed to change the object */
2539 function obj_is_writable($dn, $object, $attribute)
2541   global $ui;
2543   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2547 /*! \brief Explode a DN into its parts
2548  *
2549  * Similar to explode (http://php.net/explode), but a bit more specific
2550  * for the needs when splitting, exploding LDAP DNs.
2551  *
2552  * \param string 'dn' the DN to split
2553  * \param config-object a config object. only neeeded if DN shall be verified in the LDAP
2554  * \param boolean verify_in_ldap check weither DN is valid
2555  *
2556  */
2557 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2559   /* Initialize variables */
2560   $ret  = array("count" => 0);  // Set count to 0
2561   $next = true;                 // if false, then skip next loops and return
2562   $cnt  = 0;                    // Current number of loops
2563   $max  = 100;                  // Just for security, prevent looops
2564   $ldap = NULL;                 // To check if created result a valid
2565   $keep = "";                   // save last failed parse string
2567   /* Check each parsed dn in ldap ? */
2568   if($config!==NULL && $verify_in_ldap){
2569     $ldap = $config->get_ldap_link();
2570   }
2572   /* Lets start */
2573   $called = false;
2574   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2576     $cnt ++;
2577     if(!preg_match("/,/",$dn)){
2578       $next = false;
2579     }
2580     $object = preg_replace("/[,].*$/","",$dn);
2581     $dn     = preg_replace("/^[^,]+,/","",$dn);
2583     $called = true;
2585     /* Check if current dn is valid */
2586     if($ldap!==NULL){
2587       $ldap->cd($dn);
2588       $ldap->cat($dn,array("dn"));
2589       if($ldap->count()){
2590         $ret[]  = $keep.$object;
2591         $keep   = "";
2592       }else{
2593         $keep  .= $object.",";
2594       }
2595     }else{
2596       $ret[]  = $keep.$object;
2597       $keep   = "";
2598     }
2599   }
2601   /* No dn was posted */
2602   if($cnt == 0 && !empty($dn)){
2603     $ret[] = $dn;
2604   }
2606   /* Append the rest */
2607   $test = $keep.$dn;
2608   if($called && !empty($test)){
2609     $ret[] = $keep.$dn;
2610   }
2611   $ret['count'] = count($ret) - 1;
2613   return($ret);
2617 function get_base_from_hook($dn, $attrib)
2619   global $config;
2621   if ($config->get_cfg_value("core","baseIdHook") != ""){
2622     
2623     /* Call hook script - if present */
2624     $command= $config->get_cfg_value("core","baseIdHook");
2626     if ($command != ""){
2627       $command.= " '".LDAP::fix($dn)."' $attrib";
2628       if (check_command($command)){
2629         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2630         exec($command, $output);
2631         if (preg_match("/^[0-9]+$/", $output[0])){
2632           return ($output[0]);
2633         } else {
2634           msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2635           return ($config->get_cfg_value("core","uidNumberBase"));
2636         }
2637       } else {
2638         msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2639         return ($config->get_cfg_value("core","uidNumberBase"));
2640       }
2642     } else {
2644       msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2645       return ($config->get_cfg_value("core","uidNumberBase"));
2647     }
2648   }
2652 /*! \brief Check if schema version matches the requirements */
2653 function check_schema_version($class, $version)
2655   return preg_match("/\(v$version\)/", $class['DESC']);
2659 /*! \brief Check if LDAP schema matches the requirements */
2660 function check_schema($cfg,$rfc2307bis = FALSE)
2662   $messages= array();
2664   /* Get objectclasses */
2665   $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2666   $objectclasses = $ldap->get_objectclasses();
2667   if(count($objectclasses) == 0){
2668     msg_dialog::display(_("Warning"), _("Cannot read schema information from LDAP. Schema validation is not possible!"), WARNING_DIALOG);
2669   }
2671   /* This is the default block used for each entry.
2672    *  to avoid unset indexes.
2673    */
2674   $def_check = array("REQUIRED_VERSION" => "0",
2675       "SCHEMA_FILES"     => array(),
2676       "CLASSES_REQUIRED" => array(),
2677       "STATUS"           => FALSE,
2678       "IS_MUST_HAVE"     => FALSE,
2679       "MSG"              => "",
2680       "INFO"             => "");
2682   /* The gosa base schema */
2683   $checks['gosaObject'] = $def_check;
2684   $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2685   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa-samba3.schema");
2686   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2687   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2689   /* GOsa Account class */
2690   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.6";
2691   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa-samba3.schema");
2692   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2693   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2694   $checks["gosaAccount"]["INFO"]            = _("This class is used to make users appear in GOsa.");
2696   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2697   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2698   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa-samba3.schema");
2699   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2700   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2701   $checks["gosaLockEntry"]["INFO"]             = _("This class is used to lock entries in order to prevent multiple edits at a time.");
2703   /* Some other checks */
2704   foreach(array(
2705         "gosaCacheEntry"        => array("version" => "2.6.1", "class" => "gosaAccount"),
2706         "gosaDepartment"        => array("version" => "2.6.1", "class" => "gosaAccount"),
2707         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2708         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2709         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2710         "gosaUserTemplate"      => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2711         "gosaMailAccount"       => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa-samba3.schema"),
2712         "gosaProxyAccount"      => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa-samba3.schema"),
2713         "gosaApplication"       => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2714         "gosaApplicationGroup"  => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2715         "GOhard"                => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2716         "gotoTerminal"          => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2717         "goServer"              => array("version" => "2.6.1", "class" => "server","file" => "goserver.schema"),
2718         "goTerminalServer"      => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2719         "goShareServer"         => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2720         "goNtpServer"           => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2721         "goSyslogServer"        => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2722         "goLdapServer"          => array("version" => "2.6.1", "class" => "goServer"),
2723         "goCupsServer"          => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2724         "goImapServer"          => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa-samba3.schema"),
2725         "goKrbServer"           => array("version" => "2.6.1", "class" => "goServer"),
2726         "goFaxServer"           => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2727         ) as $name => $values){
2729           $checks[$name] = $def_check;
2730           if(isset($values['version'])){
2731             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2732           }
2733           if(isset($values['file'])){
2734             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2735           }
2736           if (isset($values['class'])) {
2737             $checks[$name]["CLASSES_REQUIRED"] = is_array($values['class'])?$values['class']:array($values['class']);
2738           }
2739         }
2740   foreach($checks as $name => $value){
2741     foreach($value['CLASSES_REQUIRED'] as $class){
2743       if(!isset($objectclasses[$name])){
2744         if($value['IS_MUST_HAVE']){
2745           $checks[$name]['STATUS'] = FALSE;
2746           $checks[$name]['MSG']    = sprintf(_("Required object class %s is missing!"), bold($class));
2747         } else {
2748           $checks[$name]['STATUS'] = TRUE;
2749           $checks[$name]['MSG']    = sprintf(_("Optional object class %s is missing!"), bold($class));
2750         }
2751       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2752         $checks[$name]['STATUS'] = FALSE;
2754         $checks[$name]['MSG'] = sprintf(_("Wrong version of required object class %s (!=%s) detected!"), bold($class), bold($value['REQUIRED_VERSION']));
2755       }else{
2756         $checks[$name]['STATUS'] = TRUE;
2757         $checks[$name]['MSG'] = sprintf(_("Class available"));
2758       }
2759     }
2760   }
2762   $tmp = $objectclasses;
2764   /* The gosa base schema */
2765   $checks['posixGroup'] = $def_check;
2766   $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2767   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa-samba3.schema","gosa-samba2.schema");
2768   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2769   $checks['posixGroup']['STATUS']           = TRUE;
2770   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2771   $checks['posixGroup']['MSG']              = "";
2772   $checks['posixGroup']['INFO']             = "";
2774   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2775   if(isset($tmp['posixGroup'])){
2777     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2778       $checks['posixGroup']['STATUS']           = FALSE;
2779       $checks['posixGroup']['MSG']              = _("RFC 2307bis group schema is enabled, but the current LDAP configuration does not support it!");
2780       $checks['posixGroup']['INFO']             = _("To use RFC 2307bis groups, the objectClass 'posixGroup' must be AUXILIARY.");
2781     }
2782     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2783       $checks['posixGroup']['STATUS']           = FALSE;
2784       $checks['posixGroup']['MSG']              = _("RFC 2307bis group schema is disabled, but the current LDAP configuration supports it!");
2785       $checks['posixGroup']['INFO']             = _("To correct this, the objectClass 'posixGroup' must be STRUCTURAL.");
2786     }
2787   }
2789   return($checks);
2793 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2795   $tmp = array(
2796         "de_DE" => "German",
2797         "fr_FR" => "French",
2798         "it_IT" => "Italian",
2799         "es_ES" => "Spanish",
2800         "en_US" => "English",
2801         "nl_NL" => "Dutch",
2802         "pl_PL" => "Polish",
2803         "pt_BR" => "Brazilian Portuguese",
2804         #"sv_SE" => "Swedish",
2805         "zh_CN" => "Chinese",
2806         "vi_VN" => "Vietnamese",
2807         "ru_RU" => "Russian");
2808   
2809   $tmp2= array(
2810         "de_DE" => _("German"),
2811         "fr_FR" => _("French"),
2812         "it_IT" => _("Italian"),
2813         "es_ES" => _("Spanish"),
2814         "en_US" => _("English"),
2815         "nl_NL" => _("Dutch"),
2816         "pl_PL" => _("Polish"),
2817         "pt_BR" => _("Brazilian Portuguese"),
2818         #"sv_SE" => _("Swedish"),
2819         "zh_CN" => _("Chinese"),
2820         "vi_VN" => _("Vietnamese"),
2821         "ru_RU" => _("Russian"));
2823   $ret = array();
2824   if($languages_in_own_language){
2826     $old_lang = setlocale(LC_ALL, 0);
2828     /* If the locale wasn't correclty set before, there may be an incorrect
2829         locale returned. Something like this: 
2830           C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2831         Extract the locale name from this string and use it to restore old locale.
2832      */
2833     if(preg_match("/LC_CTYPE/",$old_lang)){
2834       $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2835     }
2836     
2837     foreach($tmp as $key => $name){
2838       $lang = $key.".UTF-8";
2839       setlocale(LC_ALL, $lang);
2840       if($strip_region_tag){
2841         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2842       }else{
2843         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2844       }
2845     }
2846     setlocale(LC_ALL, $old_lang);
2847   }else{
2848     foreach($tmp as $key => $name){
2849       if($strip_region_tag){
2850         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2851       }else{
2852         $ret[$key] = _($name);
2853       }
2854     }
2855   }
2856   return($ret);
2860 /*! \brief Returns contents of the given POST variable and check magic quotes settings
2861  *
2862  * Depending on the magic quotes settings this returns a stripclashed'ed version of
2863  * a certain POST variable.
2864  *
2865  * \param string 'name' the POST var to return ($_POST[$name])
2866  * \return string
2867  * */
2868 function get_post($name)
2870   if(!isset($_POST[$name])){
2871     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2872     return(FALSE);
2873   }
2875   if(get_magic_quotes_gpc()){
2876     return(stripcslashes(validate($_POST[$name])));
2877   }else{
2878     return(validate($_POST[$name]));
2879   }
2883 /*! \brief Return class name in correct case */
2884 function get_correct_class_name($cls)
2886   global $class_mapping;
2887   if(isset($class_mapping) && is_array($class_mapping)){
2888     foreach($class_mapping as $class => $file){
2889       if(preg_match("/^".$cls."$/i",$class)){
2890         return($class);
2891       }
2892     }
2893   }
2894   return(FALSE);
2898 /*! \brief Change the password of a given DN
2899  * 
2900  * Change the password of a given DN with the specified hash.
2901  *
2902  * \param string 'dn' the DN whose password shall be changed
2903  * \param string 'password' the password
2904  * \param int mode
2905  * \param string 'hash' which hash to use to encrypt it, default is empty
2906  * for cleartext storage.
2907  * \return boolean TRUE on success FALSE on error
2908  */
2909 function change_password ($dn, $password, $mode=0, $hash= "")
2911   global $config;
2912   $newpass= "";
2914   /* Convert to lower. Methods are lowercase */
2915   $hash= strtolower($hash);
2917   // Get all available encryption Methods
2919   // NON STATIC CALL :)
2920   $methods = new passwordMethod(session::get('config'),$dn);
2921   $available = $methods->get_available_methods();
2923   // read current password entry for $dn, to detect the encryption Method
2924   $ldap       = $config->get_ldap_link();
2925   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2926   $attrs      = $ldap->fetch ();
2928   /* Is ensure that clear passwords will stay clear */
2929   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2930     $hash = "clear";
2931   }
2933   // Detect the encryption Method
2934   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2936     /* Check for supported algorithm */
2937     mt_srand((double) microtime()*1000000);
2939     /* Extract used hash */
2940     if ($hash == ""){
2941       $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2942     } else {
2943       $test = new $available[$hash]($config,$dn);
2944       $test->set_hash($hash);
2945     }
2947   } else {
2948     // User MD5 by default
2949     $hash= "md5";
2950     $test = new  $available['md5']($config, $dn);
2951   }
2953   if($test instanceOf passwordMethod){
2955     $deactivated = $test->is_locked($config,$dn);
2957     /* Feed password backends with information */
2958     $test->dn= $dn;
2959     $test->attrs= $attrs;
2960     $newpass= $test->generate_hash($password);
2962     // Update shadow timestamp?
2963     if (isset($attrs["shadowLastChange"][0])){
2964       $shadow= (int)(date("U") / 86400);
2965     } else {
2966       $shadow= 0;
2967     }
2969     // Write back modified entry
2970     $ldap->cd($dn);
2971     $attrs= array();
2973     // Not for groups
2974     if ($mode == 0){
2975       // Create SMB Password
2976       $attrs= generate_smb_nt_hash($password);
2978       if ($shadow != 0){
2979         $attrs['shadowLastChange']= $shadow;
2980       }
2981     }
2983     $attrs['userPassword']= array();
2984     $attrs['userPassword']= $newpass;
2986     $ldap->modify($attrs);
2988     /* Read ! if user was deactivated */
2989     if($deactivated){
2990       $test->lock_account($config,$dn);
2991     }
2993     new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2995     if (!$ldap->success()) {
2996       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2997     } else {
2999       /* Run backend method for change/create */
3000       if(!$test->set_password($password)){
3001         return(FALSE);
3002       }
3004       /* Find postmodify entries for this class */
3005       $command= $config->get_cfg_value("password","postmodify");
3007       if ($command != ""){
3008         /* Walk through attribute list */
3009         $command= preg_replace("/%userPassword/", $password, $command);
3010         $command= preg_replace("/%dn/", $dn, $command);
3012         if (check_command($command)){
3013           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
3014           exec($command);
3015         } else {
3016           $message= sprintf(_("Command %s specified as post modify action for plugin %s does not exist!"), bold($command), bold("password"));
3017           msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
3018         }
3019       }
3020     }
3021     return(TRUE);
3022   }
3026 /*! \brief Generate samba hashes
3027  *
3028  * Given a certain password this constructs an array like
3029  * array['sambaLMPassword'] etc.
3030  *
3031  * \param string 'password'
3032  * \return array contains several keys for lmPassword, ntPassword, pwdLastSet, etc. depending
3033  * on the samba version
3034  */
3035 function generate_smb_nt_hash($password)
3037   global $config;
3039   // First try to retrieve values via RPC 
3040   if ($config->get_cfg_value("core","gosaRpcServer") != ""){
3042     $rpc = $config->getRpcHandle();
3043     $hash = $rpc->mksmbhash($password);
3044     if(!$rpc->success()){
3045         msg_dialog::display(_("Error"),msgPool::rpcError($rpc->get_error()),ERROR_DIALOG);
3046         return("");
3047     }
3049   }elseif ($config->get_cfg_value("core","gosaSupportURI") != ""){
3051     // Try using gosa-si
3052         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
3053     if (isset($res['XML']['HASH'])){
3054         $hash= $res['XML']['HASH'];
3055     } else {
3056       $hash= "";
3057     }
3059     if ($hash == "") {
3060       msg_dialog::display(_("Configuration error"), _("Cannot generate SAMBA hash!"), ERROR_DIALOG);
3061       return ("");
3062     }
3063   } else {
3064           $tmp= $config->get_cfg_value("core",'sambaHashHook')." ".escapeshellarg($password);
3065           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
3067           exec($tmp, $ar);
3068           flush();
3069           reset($ar);
3070           $hash= current($ar);
3072     if ($hash == "") {
3073       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);
3074       return ("");
3075     }
3076   }
3078   list($lm,$nt)= explode(":", trim($hash));
3080   $attrs['sambaLMPassword']= $lm;
3081   $attrs['sambaNTPassword']= $nt;
3082   $attrs['sambaPwdLastSet']= date('U');
3083   $attrs['sambaBadPasswordCount']= "0";
3084   $attrs['sambaBadPasswordTime']= "0";
3085   return($attrs);
3089 /*! \brief Get the Change Sequence Number of a certain DN
3090  *
3091  * To verify if a given object has been changed outside of Gosa
3092  * in the meanwhile, this function can be used to get the entryCSN
3093  * from the LDAP directory. It uses the attribute as configured
3094  * in modificationDetectionAttribute
3095  *
3096  * \param string 'dn'
3097  * \return either the result or "" in any other case
3098  */
3099 function getEntryCSN($dn)
3101   global $config;
3102   if(empty($dn) || !is_object($config)){
3103     return("");
3104   }
3106   /* Get attribute that we should use as serial number */
3107   $attr= $config->get_cfg_value("core","modificationDetectionAttribute");
3108   if($attr != ""){
3109     $ldap = $config->get_ldap_link();
3110     $ldap->cat($dn,array($attr));
3111     $csn = $ldap->fetch();
3112     if(isset($csn[$attr][0])){
3113       return($csn[$attr][0]);
3114     }
3115   }
3116   return("");
3120 /*! \brief Add (a) given objectClass(es) to an attrs entry
3121  * 
3122  * The function adds the specified objectClass(es) to the given
3123  * attrs entry.
3124  *
3125  * \param mixed 'classes' Either a single objectClass or several objectClasses
3126  * as an array
3127  * \param array 'attrs' The attrs array to be modified.
3128  *
3129  * */
3130 function add_objectClass($classes, &$attrs)
3132   if (is_array($classes)){
3133     $list= $classes;
3134   } else {
3135     $list= array($classes);
3136   }
3138   foreach ($list as $class){
3139     $attrs['objectClass'][]= $class;
3140   }
3144 /*! \brief Removes a given objectClass from the attrs entry
3145  *
3146  * Similar to add_objectClass, except that it removes the given
3147  * objectClasses. See it for the params.
3148  * */
3149 function remove_objectClass($classes, &$attrs)
3151   if (isset($attrs['objectClass'])){
3152     /* Array? */
3153     if (is_array($classes)){
3154       $list= $classes;
3155     } else {
3156       $list= array($classes);
3157     }
3159     $tmp= array();
3160     foreach ($attrs['objectClass'] as $oc) {
3161       foreach ($list as $class){
3162         if (strtolower($oc) != strtolower($class)){
3163           $tmp[]= $oc;
3164         }
3165       }
3166     }
3167     $attrs['objectClass']= $tmp;
3168   }
3172 /*! \brief  Initialize a file download with given content, name and data type. 
3173  *  \param  string data The content to send.
3174  *  \param  string name The name of the file.
3175  *  \param  string type The content identifier, default value is "application/octet-stream";
3176  */
3177 function send_binary_content($data,$name,$type = "application/octet-stream")
3179   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
3180   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
3181   header("Cache-Control: no-cache");
3182   header("Pragma: no-cache");
3183   header("Cache-Control: post-check=0, pre-check=0");
3184   header("Content-type: ".$type."");
3186   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
3188   /* Strip name if it is a complete path */
3189   if (preg_match ("/\//", $name)) {
3190         $name= basename($name);
3191   }
3192   
3193   /* force download dialog */
3194   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
3195     header('Content-Disposition: filename="'.$name.'"');
3196   } else {
3197     header('Content-Disposition: attachment; filename="'.$name.'"');
3198   }
3200   echo $data;
3201   exit();
3205 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
3207   if(is_string($str)){
3208     return(htmlentities($str,$type,$charset));
3209   }elseif(is_array($str)){
3210     foreach($str as $name => $value){
3211       $str[$name] = reverse_html_entities($value,$type,$charset);
3212     }
3213   }
3214   return($str);
3218 /*! \brief Encode special string characters so we can use the string in \
3219            HTML output, without breaking quotes.
3220     \param string The String we want to encode.
3221     \return string The encoded String
3222  */
3223 function xmlentities($str)
3224
3225   if(is_string($str)){
3227     static $asc2uni= array();
3228     if (!count($asc2uni)){
3229       for($i=128;$i<256;$i++){
3230     #    $asc2uni[chr($i)] = "&#x".dechex($i).";";
3231       }
3232     }
3234     $str = str_replace("&", "&amp;", $str);
3235     $str = str_replace("<", "&lt;", $str);
3236     $str = str_replace(">", "&gt;", $str);
3237     $str = str_replace("'", "&apos;", $str);
3238     $str = str_replace("\"", "&quot;", $str);
3239     $str = str_replace("\r", "", $str);
3240     $str = strtr($str,$asc2uni);
3241     return $str;
3242   }elseif(is_array($str)){
3243     foreach($str as $name => $value){
3244       $str[$name] = xmlentities($value);
3245     }
3246   }
3247   return($str);
3251 /*! \brief  Updates all accessTo attributes from a given value to a new one.
3252             For example if a host is renamed.
3253     \param  String  $from The source accessTo name.
3254     \param  String  $to   The destination accessTo name.
3255 */
3256 function update_accessTo($from,$to)
3258   global $config;
3259   $ldap = $config->get_ldap_link();
3260   $ldap->cd($config->current['BASE']);
3261   $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
3262   while($attrs = $ldap->fetch()){
3263     $new_attrs = array("accessTo" => array());
3264     $dn = $attrs['dn'];
3265     for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
3266       if($attrs['accessTo'][$i] == $from){
3267         if(!empty($to)){
3268           $new_attrs['accessTo'][] =  $to;
3269         }
3270       }else{
3271         $new_attrs['accessTo'][] =  $attrs['accessTo'][$i]; 
3272       }
3273     }
3274     $ldap->cd($dn);
3275     $ldap->modify($new_attrs);
3276     if (!$ldap->success()){
3277       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
3278     }
3279     new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
3280   }
3284 /*! \brief Returns a random char */
3285 function get_random_char () {
3286      $randno = rand (0, 63);
3287      if ($randno < 12) {
3288          return (chr ($randno + 46)); // Digits, '/' and '.'
3289      } else if ($randno < 38) {
3290          return (chr ($randno + 53)); // Uppercase
3291      } else {
3292          return (chr ($randno + 59)); // Lowercase
3293      }
3297 function cred_encrypt($input, $password) {
3299   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3300   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3302   return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
3307 function cred_decrypt($input,$password) {
3308   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3309   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3311   return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
3315 function get_object_info()
3317   return(session::get('objectinfo'));
3321 function set_object_info($str = "")
3323   session::set('objectinfo',$str);
3327 function isIpInNet($ip, $net, $mask) {
3328    // Move to long ints
3329    $ip= ip2long($ip);
3330    $net= ip2long($net);
3331    $mask= ip2long($mask);
3333    // Mask given IP with mask. If it returns "net", we're in...
3334    $res= $ip & $mask;
3336    return ($res == $net);
3340 function get_next_id($attrib, $dn)
3342   global $config;
3344   switch ($config->get_cfg_value("core","idAllocationMethod")){
3345     case "pool":
3346       return get_next_id_pool($attrib);
3347     case "traditional":
3348       return get_next_id_traditional($attrib, $dn);
3349   }
3351   msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("unknown idAllocation method!"), ERROR_DIALOG);
3352   return null;
3356 function get_next_id_pool($attrib) {
3357   global $config;
3359   /* Fill informational values */
3360   $min= $config->get_cfg_value("core","${attrib}PoolMin");
3361   $max= $config->get_cfg_value("core","${attrib}PoolMax");
3363   /* Sanity check */
3364   if ($min >= $max) {
3365     msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." ".sprintf(_("%sPoolMin >= %sPoolMax!"), bold($attrib), bold($attrib)), ERROR_DIALOG);
3366     return null;
3367   }
3369   /* ID to skip */
3370   $ldap= $config->get_ldap_link();
3371   $id= null;
3373   /* Try to allocate the ID several times before failing */
3374   $tries= 3;
3375   while ($tries--) {
3377     /* Look for ID map entry */
3378     $ldap->cd ($config->current['BASE']);
3379     $ldap->search ("(&(objectClass=sambaUnixIdPool)($attrib=*))", array("$attrib"));
3381     /* If it does not exist, create one with these defaults */
3382     if ($ldap->count() == 0) {
3383       /* Fill informational values */
3384       $minUserId= $config->get_cfg_value("core","uidNumberPoolMin");
3385       $minGroupId= $config->get_cfg_value("core","gidNumberPoolMin");
3387       /* Add as default */
3388       $attrs= array("objectClass" => array("organizationalUnit", "sambaUnixIdPool"));
3389       $attrs["ou"]= "idmap";
3390       $attrs["uidNumber"]= $minUserId;
3391       $attrs["gidNumber"]= $minGroupId;
3392       $ldap->cd("ou=idmap,".$config->current['BASE']);
3393       $ldap->add($attrs);
3394       if ($ldap->error != "Success") {
3395         msg_dialog::display(_("Error"), _("Cannot create sambaUnixIdPool entry!"), ERROR_DIALOG);
3396         return null;
3397       }
3398       $tries++;
3399       continue;
3400     }
3401     /* Bail out if it's not unique */
3402     if ($ldap->count() != 1) {
3403       msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("sambaUnixIdPool is not unique!"), ERROR_DIALOG);
3404       return null;
3405     }
3407     /* Store old attrib and generate new */
3408     $attrs= $ldap->fetch();
3409     $dn= $ldap->getDN();
3410     $oldAttr= $attrs[$attrib][0];
3411     $newAttr= $oldAttr + 1;
3413     /* Sanity check */
3414     if ($newAttr >= $max) {
3415       msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("no ID available!"), ERROR_DIALOG);
3416       return null;
3417     }
3418     if ($newAttr < $min) {
3419       msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("no ID available!"), ERROR_DIALOG);
3420       return null;
3421     }
3423     #FIXME: PHP is not able to do a modification of "del: .../add: ...", so this
3424     #       is completely unsafe in the moment.
3425     #/* Remove old attr, add new attr */
3426     #$attrs= array($attrib => $oldAttr);
3427     #$ldap->rm($attrs, $dn);
3428     #if ($ldap->error != "Success") {
3429     #  continue;
3430     #}
3431     $ldap->cd($dn);
3432     $ldap->modify(array($attrib => $newAttr));
3433     if ($ldap->error != "Success") {
3434       msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." ".$ldap->get_error(), ERROR_DIALOG);
3435       return null;
3436     } else {
3437       return $oldAttr;
3438     }
3439   }
3441   /* Bail out if we had problems getting the next id */
3442   if (!$tries) {
3443     msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("maximum number of tries exceeded!"), ERROR_DIALOG);
3444   }
3446   return $id;
3450 function get_next_id_traditional($attrib, $dn)
3452   global $config;
3454   $ids= array();
3455   $ldap= $config->get_ldap_link();
3457   $ldap->cd ($config->current['BASE']);
3458   if (preg_match('/gidNumber/i', $attrib)){
3459     $oc= "posixGroup";
3460   } else {
3461     $oc= "posixAccount";
3462   }
3463   $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
3465   /* Get list of ids */
3466   while ($attrs= $ldap->fetch()){
3467     $ids[]= (int)$attrs["$attrib"][0];
3468   }
3470   /* Add the nobody id */
3471   $ids[]= 65534;
3473   /* get the ranges */
3474   $tmp = array('0'=> 1000);
3475   if (preg_match('/posixAccount/', $oc) && $config->get_cfg_value("core","uidNumberBase") != ""){
3476     $tmp= explode('-',$config->get_cfg_value("core","uidNumberBase"));
3477   } elseif($config->get_cfg_value("core","gidNumberBase") != ""){
3478     $tmp= explode('-',$config->get_cfg_value("core","gidNumberBase"));
3479   }
3481   /* Set hwm to max if not set - for backward compatibility */
3482   $lwm= $tmp[0];
3483   if (isset($tmp[1])){
3484     $hwm= $tmp[1];
3485   } else {
3486     $hwm= pow(2,32);
3487   }
3488   /* Find out next free id near to UID_BASE */
3489   if ($config->get_cfg_value("core","baseIdHook") == ""){
3490     $base= $lwm;
3491   } else {
3492     /* Call base hook */
3493     $base= get_base_from_hook($dn, $attrib);
3494   }
3495   for ($id= $base; $id++; $id < pow(2,32)){
3496     if (!in_array($id, $ids)){
3497       return ($id);
3498     }
3499   }
3501   /* Should not happen */
3502   if ($id == $hwm){
3503     msg_dialog::display(_("Error"), _("Cannot allocate free ID!"), ERROR_DIALOG);
3504     exit;
3505   }
3509 /* Mark the occurance of a string with a span */
3510 function mark($needle, $haystack, $ignorecase= true)
3512   $result= "";
3514   while (preg_match('/^(.*)('.preg_quote($needle).')(.*)$/i', $haystack, $matches)) {
3515     $result.= $matches[1]."<span class='mark'>".$matches[2]."</span>";
3516     $haystack= $matches[3];
3517   }
3519   return $result.$haystack;
3523 /* Return an image description using the path */
3524 function image($path, $action= "", $title= "", $align= "middle")
3526   global $config;
3527   global $BASE_DIR;
3528   $label= null;
3530   // Bail out, if there's no style file
3531   if(!session::global_is_set("img-styles")){
3533     // Get theme
3534     if (isset ($config)){
3535       $theme= $config->get_cfg_value("core","theme");
3536     } else {
3538       // Fall back to default theme
3539       $theme= "default";
3540     }
3542     if (!file_exists("$BASE_DIR/ihtml/themes/$theme/img.styles")){
3543       die ("No img.style for this theme found!");
3544     }
3546     session::global_set('img-styles', unserialize(file_get_contents("$BASE_DIR/ihtml/themes/$theme/img.styles")));
3547   }
3548   $styles= session::global_get('img-styles');
3550   /* Extract labels from path */
3551   if (preg_match("/\.png\[(.*)\]$/", $path, $matches)) {
3552     $label= $matches[1];
3553   }
3555   $lbl= "";
3556   if ($label) {
3557     if (isset($styles["images/label-".$label.".png"])) {
3558       $lbl= "<div style='".$styles["images/label-".$label.".png"]."'></div>";
3559     } else {
3560       die("Invalid label specified: $label\n");
3561     }
3563     $path= preg_replace("/\[.*\]$/", "", $path);
3564   }
3566   // Non middle layout?
3567   if ($align == "middle") {
3568     $align= "";
3569   } else {
3570     $align= ";vertical-align:$align";
3571   }
3573   // Clickable image or not?
3574   if ($title != "") {
3575     $title= "title='$title'";
3576   }
3577   if ($action == "") {
3578     return "<div class='img' $title style='".$styles[$path]."$align'>$lbl</div>";
3579   } else {
3580     return "<input type='submit' class='img' id='$action' value='' name='$action' $title style='".$styles[$path]."$align'>";
3581   }
3584 /*! \brief    Encodes a complex string to be useable in HTML posts.
3585  */
3586 function postEncode($str)
3588   return(preg_replace("/=/","_", base64_encode($str)));
3591 /*! \brief    Decodes a string encoded by postEncode
3592  */
3593 function postDecode($str)
3595   return(base64_decode(preg_replace("/_/","=", $str)));
3599 /*! \brief    Generate styled output
3600  */
3601 function bold($str)
3603   return "<span class='highlight'>$str</span>";
3607 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3608 ?>