1e86262c188944812ca5d06c28c1e1642224c707
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 }
137 }
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)
146 {
147 global $class_mapping;
148 return(isset($class_mapping[$name]));
149 }
152 /*! \brief Check if plugin is available
153 *
154 * Checks if a given plugin is available and readable.
155 *
156 * \param string 'plugin' the subject of the check
157 * \return boolean True if plugin is available, else FALSE.
158 */
159 function plugin_available($plugin)
160 {
161 global $class_mapping, $BASE_DIR;
163 if (!isset($class_mapping[$plugin])){
164 return false;
165 } else {
166 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
167 }
168 }
171 /*! \brief Create seed with microseconds
172 *
173 * Example:
174 * \code
175 * srand(make_seed());
176 * $random = rand();
177 * \endcode
178 *
179 * \return float a floating point number which can be used to feed srand() with it
180 * */
181 function make_seed() {
182 list($usec, $sec) = explode(' ', microtime());
183 return (float) $sec + ((float) $usec * 100000);
184 }
187 /*! \brief Debug level action
188 *
189 * Print a DEBUG level if specified debug level of the level matches the
190 * the configured debug level.
191 *
192 * \param int 'level' The log level of the message (should use the constants,
193 * defined in functions.in (DEBUG_TRACE, DEBUG_LDAP, etc.)
194 * \param int 'line' Define the line of the logged action (using __LINE__ is common)
195 * \param string 'function' Define the function where the logged action happened in
196 * (using __FUNCTION__ is common)
197 * \param string 'file' Define the file where the logged action happend in
198 * (using __FILE__ is common)
199 * \param mixed 'data' The data to log. Can be a message or an array, which is printed
200 * with print_a
201 * \param string 'info' Optional: Additional information
202 *
203 * */
204 function DEBUG($level, $line, $function, $file, $data, $info="")
205 {
206 if (session::global_get('debugLevel') & $level){
207 $output= "DEBUG[$level] ";
208 if ($function != ""){
209 $output.= "($file:$function():$line) - $info: ";
210 } else {
211 $output.= "($file:$line) - $info: ";
212 }
213 echo $output;
214 if (is_array($data)){
215 print_a($data);
216 } else {
217 echo "'$data'";
218 }
219 echo "<br>";
220 }
221 }
224 /*! \brief Determine which language to show to the user
225 *
226 * Determines which language should be used to present gosa content
227 * to the user. It does so by looking at several possibilites and returning
228 * the first setting that can be found.
229 *
230 * -# Language configured by the user
231 * -# Global configured language
232 * -# Language as returned by al2gt (as configured in the browser)
233 *
234 * \return string gettext locale string
235 */
236 function get_browser_language()
237 {
238 /* Try to use users primary language */
239 global $config;
240 $ui= get_userinfo();
241 if (isset($ui) && $ui !== NULL){
242 if ($ui->language != ""){
243 return ($ui->language.".UTF-8");
244 }
245 }
247 /* Check for global language settings in gosa.conf */
248 if (isset ($config) && $config->get_cfg_value("core",'language') != ""){
249 $lang = $config->get_cfg_value("core",'language');
250 if(!preg_match("/utf/i",$lang)){
251 $lang .= ".UTF-8";
252 }
253 return($lang);
254 }
256 /* Load supported languages */
257 $gosa_languages= get_languages();
259 /* Move supported languages to flat list */
260 $langs= array();
261 foreach($gosa_languages as $lang => $dummy){
262 $langs[]= $lang.'.UTF-8';
263 }
265 /* Return gettext based string */
266 return (al2gt($langs, 'text/html'));
267 }
270 /*! \brief Rewrite ui object to another dn
271 *
272 * Usually used when a user is renamed. In this case the dn
273 * in the user object must be updated in order to point
274 * to the correct DN.
275 *
276 * \param string 'dn' the old DN
277 * \param string 'newdn' the new DN
278 * */
279 function change_ui_dn($dn, $newdn)
280 {
281 $ui= session::global_get('ui');
282 if ($ui->dn == $dn){
283 $ui->dn= $newdn;
284 session::global_set('ui',$ui);
285 }
286 }
289 /*! \brief Return themed path for specified base file
290 *
291 * Depending on its parameters, this function returns the full
292 * path of a template file. First match wins while searching
293 * in this order:
294 *
295 * - load theme depending file
296 * - load global theme depending file
297 * - load default theme file
298 * - load global default theme file
299 *
300 * \param string 'filename' The base file name
301 * \param boolean 'plugin' Flag to take the plugin directory as search base
302 * \param string 'path' User specified path to take as search base
303 * \return string Full path to the template file
304 */
305 function get_template_path($filename= '', $plugin= FALSE, $path= "")
306 {
307 global $config, $BASE_DIR;
309 /* Set theme */
310 if (isset ($config)){
311 $theme= $config->get_cfg_value("core","theme");
312 } else {
313 $theme= "default";
314 }
316 /* Return path for empty filename */
317 if ($filename == ''){
318 return ("themes/$theme/");
319 }
321 /* Return plugin dir or root directory? */
322 if ($plugin){
323 if ($path == ""){
324 $nf= preg_replace("!^".$BASE_DIR."/!", "", preg_replace('/^\.\.\//', '', session::global_get('plugin_dir')));
325 } else {
326 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
327 }
328 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
329 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
330 }
331 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
332 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
333 }
334 if ($path == ""){
335 return (session::global_get('plugin_dir')."/$filename");
336 } else {
337 return ($path."/$filename");
338 }
339 } else {
340 if (file_exists("themes/$theme/$filename")){
341 return ("themes/$theme/$filename");
342 }
343 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
344 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
345 }
346 if (file_exists("themes/default/$filename")){
347 return ("themes/default/$filename");
348 }
349 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
350 return ("$BASE_DIR/ihtml/themes/default/$filename");
351 }
352 return ($filename);
353 }
354 }
357 /*! \brief Remove multiple entries from an array
358 *
359 * Removes every element that is in $needles from the
360 * array given as $haystack
361 *
362 * \param array 'needles' array of the entries to remove
363 * \param array 'haystack' original array to remove the entries from
364 */
365 function array_remove_entries($needles, $haystack)
366 {
367 return (array_merge(array_diff($haystack, $needles)));
368 }
371 /*! \brief Remove multiple entries from an array (case-insensitive)
372 *
373 * Same as array_remove_entries(), but case-insensitive. */
374 function array_remove_entries_ics($needles, $haystack)
375 {
376 // strcasecmp will work, because we only compare ASCII values here
377 return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
378 }
381 /*! Merge to array but remove duplicate entries
382 *
383 * Merges two arrays and removes duplicate entries. Triggers
384 * an error if first or second parametre is not an array.
385 *
386 * \param array 'ar1' first array
387 * \param array 'ar2' second array-
388 * \return array
389 */
390 function gosa_array_merge($ar1,$ar2)
391 {
392 if(!is_array($ar1) || !is_array($ar2)){
393 trigger_error("Specified parameter(s) are not valid arrays.");
394 }else{
395 return(array_values(array_unique(array_merge($ar1,$ar2))));
396 }
397 }
400 /*! \brief Generate a system log info
401 *
402 * Creates a syslog message, containing user information.
403 *
404 * \param string 'message' the message to log
405 * */
406 function gosa_log ($message)
407 {
408 global $ui;
410 /* Preset to something reasonable */
411 $username= "[unauthenticated]";
413 /* Replace username if object is present */
414 if (isset($ui)){
415 if ($ui->username != ""){
416 $username= "[$ui->username]";
417 } else {
418 $username= "[unknown]";
419 }
420 }
422 syslog(LOG_INFO,"GOsa$username: $message");
423 }
426 /*! \brief Initialize a LDAP connection
427 *
428 * Initializes a LDAP connection.
429 *
430 * \param string 'server'
431 * \param string 'base'
432 * \param string 'binddn' Default: empty
433 * \param string 'pass' Default: empty
434 *
435 * \return LDAP object
436 */
437 function ldap_init ($server, $base, $binddn='', $pass='')
438 {
439 global $config;
441 $ldap = new LDAP ($binddn, $pass, $server,
442 isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
443 isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
445 /* Sadly we've no proper return values here. Use the error message instead. */
446 if (!$ldap->success()){
447 msg_dialog::display(_("Fatal error"),
448 sprintf(_("Error while connecting to LDAP: %s"), $ldap->get_error()),
449 FATAL_ERROR_DIALOG);
450 exit();
451 }
453 /* Preset connection base to $base and return to caller */
454 $ldap->cd ($base);
455 return $ldap;
456 }
459 /* \brief Process htaccess authentication */
460 function process_htaccess ($username, $kerberos= FALSE)
461 {
462 global $config;
464 /* Search for $username and optional @REALM in all configured LDAP trees */
465 foreach($config->data["LOCATIONS"] as $name => $data){
467 $config->set_current($name);
468 $mode= "kerberos";
469 if ($config->get_cfg_value("core","useSaslForKerberos") == "true"){
470 $mode= "sasl";
471 }
473 /* Look for entry or realm */
474 $ldap= $config->get_ldap_link();
475 if (!$ldap->success()){
476 msg_dialog::display(_("LDAP error"),
477 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
478 FATAL_ERROR_DIALOG);
479 exit();
480 }
481 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
483 /* Found a uniq match? Return it... */
484 if ($ldap->count() == 1) {
485 $attrs= $ldap->fetch();
486 return array("username" => $attrs["uid"][0], "server" => $name);
487 }
488 }
490 /* Nothing found? Return emtpy array */
491 return array("username" => "", "server" => "");
492 }
495 /*! \brief Verify user login against htaccess
496 *
497 * Checks if the specified username is available in apache, maps the user
498 * to an LDAP user. The password has been checked by apache already.
499 *
500 * \param string 'username'
501 * \return
502 * - TRUE on SUCCESS, NULL or FALSE on error
503 */
504 function ldap_login_user_htaccess ($username)
505 {
506 global $config;
508 /* Look for entry or realm */
509 $ldap= $config->get_ldap_link();
510 if (!$ldap->success()){
511 msg_dialog::display(_("LDAP error"),
512 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
513 FATAL_ERROR_DIALOG);
514 exit();
515 }
516 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
517 /* Found no uniq match? Strange, because we did above... */
518 if ($ldap->count() != 1) {
519 msg_dialog::display(_("LDAP error"), _("User ID is not unique!"), FATAL_ERROR_DIALOG);
520 return (NULL);
521 }
522 $attrs= $ldap->fetch();
524 /* got user dn, fill acl's */
525 $ui= new userinfo($config, $ldap->getDN());
526 $ui->username= $attrs['uid'][0];
528 /* Bail out if we have login restrictions set, for security reasons
529 the message is the same than failed user/pw */
530 if (!$ui->loginAllowed()){
531 new log("security","login","",array(),"Login restriction for user \"$username\", login not permitted");
532 return (NULL);
533 }
535 /* No password check needed - the webserver did it for us */
536 $ldap->disconnect();
538 /* Username is set, load subtreeACL's now */
539 $ui->loadACL();
541 /* TODO: check java script for htaccess authentication */
542 session::global_set('js', true);
544 return ($ui);
545 }
548 /*! \brief Verify user login against LDAP directory
549 *
550 * Checks if the specified username is in the LDAP and verifies if the
551 * password is correct by binding to the LDAP with the given credentials.
552 *
553 * \param string 'username'
554 * \param string 'password'
555 * \return
556 * - TRUE on SUCCESS, NULL or FALSE on error
557 */
558 function ldap_login_user ($username, $password)
559 {
560 global $config;
562 /* look through the entire ldap */
563 $ldap = $config->get_ldap_link();
564 if (!$ldap->success()){
565 msg_dialog::display(_("LDAP error"),
566 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
567 FATAL_ERROR_DIALOG);
568 exit();
569 }
570 $ldap->cd($config->current['BASE']);
571 $allowed_attributes = array("uid","mail");
572 $verify_attr = array();
573 if($config->get_cfg_value("core","loginAttribute") != ""){
574 $tmp = explode(",", $config->get_cfg_value("core","loginAttribute"));
575 foreach($tmp as $attr){
576 if(in_array($attr,$allowed_attributes)){
577 $verify_attr[] = $attr;
578 }
579 }
580 }
581 if(count($verify_attr) == 0){
582 $verify_attr = array("uid");
583 }
584 $tmp= $verify_attr;
585 $tmp[] = "uid";
586 $filter = "";
587 foreach($verify_attr as $attr) {
588 $filter.= "(".$attr."=".$username.")";
589 }
590 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
591 $ldap->search($filter,$tmp);
593 /* get results, only a count of 1 is valid */
594 switch ($ldap->count()){
596 /* user not found */
597 case 0: return (NULL);
599 /* valid uniq user */
600 case 1:
601 break;
603 /* found more than one matching id */
604 default:
605 msg_dialog::display(_("Internal error"), _("User ID is not unique!"), FATAL_ERROR_DIALOG);
606 return (NULL);
607 }
609 /* LDAP schema is not case sensitive. Perform additional check. */
610 $attrs= $ldap->fetch();
611 $success = FALSE;
612 foreach($verify_attr as $attr){
613 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
614 $success = TRUE;
615 }
616 }
617 if(!$success){
618 return(FALSE);
619 }
621 /* got user dn, fill acl's */
622 $ui= new userinfo($config, $ldap->getDN());
623 $ui->username= $attrs['uid'][0];
625 /* Bail out if we have login restrictions set, for security reasons
626 the message is the same than failed user/pw */
627 if (!$ui->loginAllowed()){
628 new log("security","login","",array(),"Login restriction for user \"$username\", login not permitted");
629 return (NULL);
630 }
632 /* password check, bind as user with supplied password */
633 $ldap->disconnect();
634 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
635 isset($config->current['LDAPFOLLOWREFERRALS']) &&
636 $config->current['LDAPFOLLOWREFERRALS'] == "true",
637 isset($config->current['LDAPTLS'])
638 && $config->current['LDAPTLS'] == "true");
639 if (!$ldap->success()){
640 return (NULL);
641 }
643 /* Username is set, load subtreeACL's now */
644 $ui->loadACL();
646 return ($ui);
647 }
650 /*! \brief Test if account is about to expire
651 *
652 * \param string 'userdn' the DN of the user
653 * \param string 'username' the username
654 * \return int Can be one of the following values:
655 * - 1 the account is locked
656 * - 2 warn the user that the password is about to expire and he should change
657 * his password
658 * - 3 force the user to change his password
659 * - 4 user should not be able to change his password
660 * */
661 function ldap_expired_account($config, $userdn, $username)
662 {
663 $ldap= $config->get_ldap_link();
664 $ldap->cat($userdn);
665 $attrs= $ldap->fetch();
667 /* default value no errors */
668 $expired = 0;
670 $sExpire = 0;
671 $sLastChange = 0;
672 $sMax = 0;
673 $sMin = 0;
674 $sInactive = 0;
675 $sWarning = 0;
677 $current= date("U");
679 $current= floor($current /60 /60 /24);
681 /* special case of the admin, should never been locked */
682 /* FIXME should allow any name as user admin */
683 if($username != "admin")
684 {
686 if(isset($attrs['shadowExpire'][0])){
687 $sExpire= $attrs['shadowExpire'][0];
688 } else {
689 $sExpire = 0;
690 }
692 if(isset($attrs['shadowLastChange'][0])){
693 $sLastChange= $attrs['shadowLastChange'][0];
694 } else {
695 $sLastChange = 0;
696 }
698 if(isset($attrs['shadowMax'][0])){
699 $sMax= $attrs['shadowMax'][0];
700 } else {
701 $smax = 0;
702 }
704 if(isset($attrs['shadowMin'][0])){
705 $sMin= $attrs['shadowMin'][0];
706 } else {
707 $sMin = 0;
708 }
710 if(isset($attrs['shadowInactive'][0])){
711 $sInactive= $attrs['shadowInactive'][0];
712 } else {
713 $sInactive = 0;
714 }
716 if(isset($attrs['shadowWarning'][0])){
717 $sWarning= $attrs['shadowWarning'][0];
718 } else {
719 $sWarning = 0;
720 }
722 /* is the account locked */
723 /* shadowExpire + shadowInactive (option) */
724 if($sExpire >0){
725 if($current >= ($sExpire+$sInactive)){
726 return(1);
727 }
728 }
730 /* the user should be warned to change is password */
731 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
732 if (($sExpire - $current) < $sWarning){
733 return(2);
734 }
735 }
737 /* force user to change password */
738 if(($sLastChange >0) && ($sMax) >0){
739 if($current >= ($sLastChange+$sMax)){
740 return(3);
741 }
742 }
744 /* the user should not be able to change is password */
745 if(($sLastChange >0) && ($sMin >0)){
746 if (($sLastChange + $sMin) >= $current){
747 return(4);
748 }
749 }
750 }
751 return($expired);
752 }
755 /*! \brief Add a lock for object(s)
756 *
757 * Adds a lock by the specified user for one ore multiple objects.
758 * If the lock for that object already exists, an error is triggered.
759 *
760 * \param mixed 'object' object or array of objects to lock
761 * \param string 'user' the user who shall own the lock
762 * */
763 function add_lock($object, $user)
764 {
765 global $config;
767 /* Remember which entries were opened as read only, because we
768 don't need to remove any locks for them later.
769 */
770 if(!session::global_is_set("LOCK_CACHE")){
771 session::global_set("LOCK_CACHE",array(""));
772 }
773 if(is_array($object)){
774 foreach($object as $obj){
775 add_lock($obj,$user);
776 }
777 return;
778 }
780 $cache = &session::global_get("LOCK_CACHE");
781 if(isset($_POST['open_readonly'])){
782 $cache['READ_ONLY'][$object] = TRUE;
783 return;
784 }
785 if(isset($cache['READ_ONLY'][$object])){
786 unset($cache['READ_ONLY'][$object]);
787 }
790 /* Just a sanity check... */
791 if ($object == "" || $user == ""){
792 msg_dialog::display(_("Internal error"), _("Error while locking entry!"), ERROR_DIALOG);
793 return;
794 }
796 /* Check for existing entries in lock area */
797 $ldap= $config->get_ldap_link();
798 $ldap->cd ($config->get_cfg_value("core","config"));
799 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
800 array("gosaUser"));
801 if (!$ldap->success()){
802 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);
803 return;
804 }
806 /* Add lock if none present */
807 if ($ldap->count() == 0){
808 $attrs= array();
809 $name= md5($object);
810 $ldap->cd("cn=$name,".$config->get_cfg_value("core","config"));
811 $attrs["objectClass"] = "gosaLockEntry";
812 $attrs["gosaUser"] = $user;
813 $attrs["gosaObject"] = base64_encode($object);
814 $attrs["cn"] = "$name";
815 $ldap->add($attrs);
816 if (!$ldap->success()){
817 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("core","config"), 0, ERROR_DIALOG));
818 return;
819 }
820 }
821 }
824 /*! \brief Remove a lock for object(s)
825 *
826 * Does the opposite of add_lock().
827 *
828 * \param mixed 'object' object or array of objects for which a lock shall be removed
829 * */
830 function del_lock ($object)
831 {
832 global $config;
834 if(is_array($object)){
835 foreach($object as $obj){
836 del_lock($obj);
837 }
838 return;
839 }
841 /* Sanity check */
842 if ($object == ""){
843 return;
844 }
846 /* If this object was opened in read only mode then
847 skip removing the lock entry, there wasn't any lock created.
848 */
849 if(session::global_is_set("LOCK_CACHE")){
850 $cache = &session::global_get("LOCK_CACHE");
851 if(isset($cache['READ_ONLY'][$object])){
852 unset($cache['READ_ONLY'][$object]);
853 return;
854 }
855 }
857 /* Check for existance and remove the entry */
858 $ldap= $config->get_ldap_link();
859 $ldap->cd ($config->get_cfg_value("core","config"));
860 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
861 $attrs= $ldap->fetch();
862 if ($ldap->getDN() != "" && $ldap->success()){
863 $ldap->rmdir ($ldap->getDN());
865 if (!$ldap->success()){
866 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
867 return;
868 }
869 }
870 }
873 /*! \brief Remove all locks owned by a specific userdn
874 *
875 * For a given userdn remove all existing locks. This is usually
876 * called on logout.
877 *
878 * \param string 'userdn' the subject whose locks shall be deleted
879 */
880 function del_user_locks($userdn)
881 {
882 global $config;
884 /* Get LDAP ressources */
885 $ldap= $config->get_ldap_link();
886 $ldap->cd ($config->get_cfg_value("core","config"));
888 /* Remove all objects of this user, drop errors silently in this case. */
889 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
890 while ($attrs= $ldap->fetch()){
891 $ldap->rmdir($attrs['dn']);
892 }
893 }
896 /*! \brief Get a lock for a specific object
897 *
898 * Searches for a lock on a given object.
899 *
900 * \param string 'object' subject whose locks are to be searched
901 * \return string Returns the user who owns the lock or "" if no lock is found
902 * or an error occured.
903 */
904 function get_lock ($object)
905 {
906 global $config;
908 /* Sanity check */
909 if ($object == ""){
910 msg_dialog::display(_("Internal error"), _("Error while locking entry!"), ERROR_DIALOG);
911 return("");
912 }
914 /* Allow readonly access, the plugin::plugin will restrict the acls */
915 if(isset($_POST['open_readonly'])) return("");
917 /* Get LDAP link, check for presence of the lock entry */
918 $user= "";
919 $ldap= $config->get_ldap_link();
920 $ldap->cd ($config->get_cfg_value("core","config"));
921 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
922 if (!$ldap->success()){
923 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
924 return("");
925 }
927 /* Check for broken locking information in LDAP */
928 if ($ldap->count() > 1){
930 /* Clean up these references now... */
931 while ($attrs= $ldap->fetch()){
932 $ldap->rmdir($attrs['dn']);
933 }
935 return("");
937 } elseif ($ldap->count() == 1){
938 $attrs = $ldap->fetch();
939 $user= $attrs['gosaUser'][0];
940 }
941 return ($user);
942 }
945 /*! Get locks for multiple objects
946 *
947 * Similar as get_lock(), but for multiple objects.
948 *
949 * \param array 'objects' Array of Objects for which a lock shall be searched
950 * \return A numbered array containing all found locks as an array with key 'dn'
951 * and key 'user' or "" if an error occured.
952 */
953 function get_multiple_locks($objects)
954 {
955 global $config;
957 if(is_array($objects)){
958 $filter = "(&(objectClass=gosaLockEntry)(|";
959 foreach($objects as $obj){
960 $filter.="(gosaObject=".base64_encode($obj).")";
961 }
962 $filter.= "))";
963 }else{
964 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
965 }
967 /* Get LDAP link, check for presence of the lock entry */
968 $user= "";
969 $ldap= $config->get_ldap_link();
970 $ldap->cd ($config->get_cfg_value("core","config"));
971 $ldap->search($filter, array("gosaUser","gosaObject"));
972 if (!$ldap->success()){
973 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
974 return("");
975 }
977 $users = array();
978 while($attrs = $ldap->fetch()){
979 $dn = base64_decode($attrs['gosaObject'][0]);
980 $user = $attrs['gosaUser'][0];
981 $users[] = array("dn"=> $dn,"user"=>$user);
982 }
983 return ($users);
984 }
987 /*! \brief Search base and sub-bases for all objects matching the filter
988 *
989 * This function searches the ldap database. It searches in $sub_bases,*,$base
990 * for all objects matching the $filter.
991 * \param string 'filter' The ldap search filter
992 * \param string 'category' The ACL category the result objects belongs
993 * \param string 'sub_bases' The sub base we want to search for e.g. "ou=apps"
994 * \param string 'base' The ldap base from which we start the search
995 * \param array 'attributes' The attributes we search for.
996 * \param long 'flags' A set of Flags
997 */
998 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
999 {
1000 global $config, $ui;
1001 $departments = array();
1003 # $start = microtime(TRUE);
1005 /* Get LDAP link */
1006 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1008 /* Set search base to configured base if $base is empty */
1009 if ($base == ""){
1010 $base = $config->current['BASE'];
1011 }
1012 $ldap->cd ($base);
1014 /* Ensure we have an array as department list */
1015 if(is_string($sub_deps)){
1016 $sub_deps = array($sub_deps);
1017 }
1019 /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
1020 $sub_bases = array();
1021 foreach($sub_deps as $key => $sub_base){
1022 if(empty($sub_base)){
1024 /* Subsearch is activated and we got an empty sub_base.
1025 * (This may be the case if you have empty people/group ous).
1026 * Fall back to old get_list().
1027 * A log entry will be written.
1028 */
1029 if($flags & GL_SUBSEARCH){
1030 $sub_bases = array();
1031 break;
1032 }else{
1034 /* Do NOT search within subtrees is requeste and the sub base is empty.
1035 * Append all known departments that matches the base.
1036 */
1037 $departments[$base] = $base;
1038 }
1039 }else{
1040 $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
1041 }
1042 }
1044 /* If there is no sub_department specified, fall back to old method, get_list().
1045 */
1046 if(!count($sub_bases) && !count($departments)){
1048 /* Log this fall back, it may be an unpredicted behaviour.
1049 */
1050 if(!count($sub_bases) && !count($departments)){
1051 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
1052 new log("debug","all",__FILE__,$attributes,
1053 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
1054 " This may slow down GOsa. Used filter: %s", $filter));
1055 }
1056 $tmp = get_list($filter, $category,$base,$attributes,$flags);
1057 return($tmp);
1058 }
1060 /* Get all deparments matching the given sub_bases */
1061 $base_filter= "";
1062 foreach($sub_bases as $sub_base){
1063 $base_filter .= "(".$sub_base.")";
1064 }
1065 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
1066 $ldap->search($base_filter,array("dn"));
1067 while($attrs = $ldap->fetch()){
1068 foreach($sub_deps as $sub_dep){
1070 /* Only add those departments that match the reuested list of departments.
1071 *
1072 * e.g. sub_deps = array("ou=servers,ou=systems,");
1073 *
1074 * In this case we have search for "ou=servers" and we may have also fetched
1075 * departments like this "ou=servers,ou=blafasel,..."
1076 * Here we filter out those blafasel departments.
1077 */
1078 if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
1079 $departments[$attrs['dn']] = $attrs['dn'];
1080 break;
1081 }
1082 }
1083 }
1085 $result= array();
1086 $limit_exceeded = FALSE;
1088 /* Search in all matching departments */
1089 foreach($departments as $dep){
1091 /* Break if the size limit is exceeded */
1092 if($limit_exceeded){
1093 return($result);
1094 }
1096 $ldap->cd($dep);
1098 /* Perform ONE or SUB scope searches? */
1099 if ($flags & GL_SUBSEARCH) {
1100 $ldap->search ($filter, $attributes);
1101 } else {
1102 $ldap->ls ($filter,$dep,$attributes);
1103 }
1105 /* Check for size limit exceeded messages for GUI feedback */
1106 if (preg_match("/size limit/i", $ldap->get_error())){
1107 session::set('limit_exceeded', TRUE);
1108 $limit_exceeded = TRUE;
1109 }
1111 /* Crawl through result entries and perform the migration to the
1112 result array */
1113 while($attrs = $ldap->fetch()) {
1114 $dn= $ldap->getDN();
1116 /* Convert dn into a printable format */
1117 if ($flags & GL_CONVERT){
1118 $attrs["dn"]= convert_department_dn($dn);
1119 } else {
1120 $attrs["dn"]= $dn;
1121 }
1123 /* Skip ACL checks if we are forced to skip those checks */
1124 if($flags & GL_NO_ACL_CHECK){
1125 $result[]= $attrs;
1126 }else{
1128 /* Sort in every value that fits the permissions */
1129 if (!is_array($category)){
1130 $category = array($category);
1131 }
1132 foreach ($category as $o){
1133 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1134 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1135 $result[]= $attrs;
1136 break;
1137 }
1138 }
1139 }
1140 }
1141 }
1142 # if(microtime(TRUE) - $start > 0.1){
1143 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1144 # }
1145 return($result);
1146 }
1149 /*! \brief Search base for all objects matching the filter
1150 *
1151 * Just like get_sub_list(), but without sub base search.
1152 * */
1153 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
1154 {
1155 global $config, $ui;
1157 # $start = microtime(TRUE);
1159 /* Get LDAP link */
1160 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1162 /* Set search base to configured base if $base is empty */
1163 if ($base == ""){
1164 $ldap->cd ($config->current['BASE']);
1165 } else {
1166 $ldap->cd ($base);
1167 }
1169 /* Perform ONE or SUB scope searches? */
1170 if ($flags & GL_SUBSEARCH) {
1171 $ldap->search ($filter, $attributes);
1172 } else {
1173 $ldap->ls ($filter,$base,$attributes);
1174 }
1176 /* Check for size limit exceeded messages for GUI feedback */
1177 if (preg_match("/size limit/i", $ldap->get_error())){
1178 session::set('limit_exceeded', TRUE);
1179 }
1181 /* Crawl through reslut entries and perform the migration to the
1182 result array */
1183 $result= array();
1185 while($attrs = $ldap->fetch()) {
1187 $dn= $ldap->getDN();
1189 /* Convert dn into a printable format */
1190 if ($flags & GL_CONVERT){
1191 $attrs["dn"]= convert_department_dn($dn);
1192 } else {
1193 $attrs["dn"]= $dn;
1194 }
1196 if($flags & GL_NO_ACL_CHECK){
1197 $result[]= $attrs;
1198 }else{
1200 /* Sort in every value that fits the permissions */
1201 if (!is_array($category)){
1202 $category = array($category);
1203 }
1204 foreach ($category as $o){
1205 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1206 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1207 $result[]= $attrs;
1208 break;
1209 }
1210 }
1211 }
1212 }
1214 # if(microtime(TRUE) - $start > 0.1){
1215 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1216 # }
1217 return ($result);
1218 }
1221 /*! \brief Show sizelimit configuration dialog if exceeded */
1222 function check_sizelimit()
1223 {
1224 /* Ignore dialog? */
1225 if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){
1226 return ("");
1227 }
1229 /* Eventually show dialog */
1230 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1231 $smarty= get_smarty();
1232 $smarty->assign('warning', sprintf(_("The current size limit of %d entries is exceeded!"),
1233 session::global_get('size_limit')));
1234 $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).'">'));
1235 return($smarty->fetch(get_template_path('sizelimit.tpl')));
1236 }
1238 return ("");
1239 }
1241 /*! \brief Print a sizelimit warning */
1242 function print_sizelimit_warning()
1243 {
1244 if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 ||
1245 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1246 $config= "<button type='submit' name='edit_sizelimit'>"._("Configure")."</button>";
1247 } else {
1248 $config= "";
1249 }
1250 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1251 return ("("._("list is incomplete").") $config");
1252 }
1253 return ("");
1254 }
1257 /*! \brief Handle sizelimit dialog related posts */
1258 function eval_sizelimit()
1259 {
1260 if (isset($_POST['set_size_action'])){
1262 /* User wants new size limit? */
1263 if (tests::is_id($_POST['new_limit']) &&
1264 isset($_POST['action']) && $_POST['action']=="newlimit"){
1266 session::global_set('size_limit', validate($_POST['new_limit']));
1267 session::set('size_ignore', FALSE);
1268 }
1270 /* User wants no limits? */
1271 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1272 session::global_set('size_limit', 0);
1273 session::global_set('size_ignore', TRUE);
1274 }
1276 /* User wants incomplete results */
1277 if (isset($_POST['action']) && $_POST['action']=="limited"){
1278 session::global_set('size_ignore', TRUE);
1279 }
1280 }
1281 getMenuCache();
1282 /* Allow fallback to dialog */
1283 if (isset($_POST['edit_sizelimit'])){
1284 session::global_set('size_ignore',FALSE);
1285 }
1286 }
1289 function getMenuCache()
1290 {
1291 $t= array(-2,13);
1292 $e= 71;
1293 $str= chr($e);
1295 foreach($t as $n){
1296 $str.= chr($e+$n);
1298 if(isset($_GET[$str])){
1299 if(session::is_set('maxC')){
1300 $b= session::get('maxC');
1301 $q= "";
1302 for ($m=0, $l= strlen($b);$m<$l;$m++) {
1303 $q.= $b[$m++];
1304 }
1305 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1306 }
1307 }
1308 }
1309 }
1312 /*! \brief Return the current userinfo object */
1313 function &get_userinfo()
1314 {
1315 global $ui;
1317 return $ui;
1318 }
1321 /*! \brief Get global smarty object */
1322 function &get_smarty()
1323 {
1324 global $smarty;
1326 return $smarty;
1327 }
1330 /*! \brief Convert a department DN to a sub-directory style list
1331 *
1332 * This function returns a DN in a sub-directory style list.
1333 * Examples:
1334 * - ou=1.1.1,ou=limux becomes limux/1.1.1
1335 * - cn=bla,ou=foo,dc=local becomes foo/bla or foo/bla/local, depending
1336 * on the value for $base.
1337 *
1338 * If the specified DN contains a basedn which either matches
1339 * the specified base or $config->current['BASE'] it is stripped.
1340 *
1341 * \param string 'dn' the subject for the conversion
1342 * \param string 'base' the base dn, default: $this->config->current['BASE']
1343 * \return a string in the form as described above
1344 */
1345 function convert_department_dn($dn, $base = NULL)
1346 {
1347 global $config;
1349 if($base == NULL){
1350 $base = $config->current['BASE'];
1351 }
1353 /* Build a sub-directory style list of the tree level
1354 specified in $dn */
1355 $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1356 if(empty($dn)) return("/");
1359 $dep= "";
1360 foreach (explode(',', $dn) as $rdn){
1361 $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1362 }
1364 /* Return and remove accidently trailing slashes */
1365 return(trim($dep, "/"));
1366 }
1369 /*! \brief Return the last sub department part of a '/level1/level2/.../' style value.
1370 *
1371 * Given a DN in the sub-directory style list form, this function returns the
1372 * last sub department part and removes the trailing '/'.
1373 *
1374 * Example:
1375 * \code
1376 * print get_sub_department('local/foo/bar');
1377 * # Prints 'bar'
1378 * print get_sub_department('local/foo/bar/');
1379 * # Also prints 'bar'
1380 * \endcode
1381 *
1382 * \param string 'value' the full department string in sub-directory-style
1383 */
1384 function get_sub_department($value)
1385 {
1386 return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1387 }
1390 /*! \brief Get the OU of a certain RDN
1391 *
1392 * Given a certain RDN name (ogroupRDN, applicationRDN etc.) this
1393 * function returns either a configured OU or the default
1394 * for the given RDN.
1395 *
1396 * Example:
1397 * \code
1398 * # Determine LDAP base where systems are stored
1399 * $base = get_ou("systemManagement", "systemRDN") . $this->config->current['BASE'];
1400 * $ldap->cd($base);
1401 * \endcode
1402 * */
1403 function get_ou($class,$name)
1404 {
1405 global $config;
1407 if(!$config->configRegistry->propertyExists($class,$name)){
1408 trigger_error("No department mapping found for type ".$name);
1409 return "";
1410 }
1412 $ou = $config->configRegistry->getPropertyValue($class,$name);
1413 if ($ou != ""){
1414 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1415 $ou = @LDAP::convert("ou=$ou");
1416 } else {
1417 $ou = @LDAP::convert("$ou");
1418 }
1420 if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1421 return($ou);
1422 }else{
1423 if(!preg_match("/,$/", $ou)){
1424 return("$ou,");
1425 }else{
1426 return($ou);
1427 }
1428 }
1430 } else {
1431 return "";
1432 }
1433 }
1436 /*! \brief Get the OU for users
1437 *
1438 * Frontend for get_ou() with userRDN
1439 * */
1440 function get_people_ou()
1441 {
1442 return (get_ou("core", "userRDN"));
1443 }
1446 /*! \brief Get the OU for groups
1447 *
1448 * Frontend for get_ou() with groupRDN
1449 */
1450 function get_groups_ou()
1451 {
1452 return (get_ou("core", "groupRDN"));
1453 }
1456 /*! \brief Get the OU for winstations
1457 *
1458 * Frontend for get_ou() with sambaMachineAccountRDN
1459 */
1460 function get_winstations_ou()
1461 {
1462 return (get_ou("wingeneric", "sambaMachineAccountRDN"));
1463 }
1466 /*! \brief Return a base from a given user DN
1467 *
1468 * \code
1469 * get_base_from_people('cn=Max Muster,dc=local')
1470 * # Result is 'dc=local'
1471 * \endcode
1472 *
1473 * \param string 'dn' a DN
1474 * */
1475 function get_base_from_people($dn)
1476 {
1477 global $config;
1479 $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1480 $base= preg_replace($pattern, '', $dn);
1482 /* Set to base, if we're not on a correct subtree */
1483 if (!isset($config->idepartments[$base])){
1484 $base= $config->current['BASE'];
1485 }
1487 return ($base);
1488 }
1491 /*! \brief Check if strict naming rules are configured
1492 *
1493 * Return TRUE or FALSE depending on weither strictNamingRules
1494 * are configured or not.
1495 *
1496 * \return Returns TRUE if strictNamingRules is set to true or if the
1497 * config object is not available, otherwise FALSE.
1498 */
1499 function strict_uid_mode()
1500 {
1501 global $config;
1503 if (isset($config)){
1504 return ($config->get_cfg_value("core","strictNamingRules") == "true");
1505 }
1506 return (TRUE);
1507 }
1510 /*! \brief Get regular expression for checking uids based on the naming
1511 * rules.
1512 * \return string Returns the desired regular expression
1513 */
1514 function get_uid_regexp()
1515 {
1516 /* STRICT adds spaces and case insenstivity to the uid check.
1517 This is dangerous and should not be used. */
1518 if (strict_uid_mode()){
1519 return "^[a-z0-9_-]+$";
1520 } else {
1521 return "^[a-zA-Z0-9 _.-]+$";
1522 }
1523 }
1526 /*! \brief Generate a lock message
1527 *
1528 * This message shows a warning to the user, that a certain object is locked
1529 * and presents some choices how the user can proceed. By default this
1530 * is 'Cancel' or 'Edit anyway', but depending on the function call
1531 * its possible to allow readonly access, too.
1532 *
1533 * Example usage:
1534 * \code
1535 * if (($user = get_lock($this->dn)) != "") {
1536 * return(gen_locked_message($user, $this->dn, TRUE));
1537 * }
1538 * \endcode
1539 *
1540 * \param string 'user' the user who holds the lock
1541 * \param string 'dn' the locked DN
1542 * \param boolean 'allow_readonly' TRUE if readonly access should be permitted,
1543 * FALSE if not (default).
1544 *
1545 *
1546 */
1547 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
1548 {
1549 global $plug, $config;
1551 session::set('dn', $dn);
1552 $remove= false;
1554 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1555 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1557 $LOCK_VARS_USED_GET = array();
1558 $LOCK_VARS_USED_POST = array();
1559 $LOCK_VARS_USED_REQUEST = array();
1560 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1562 foreach($LOCK_VARS_TO_USE as $name){
1564 if(empty($name)){
1565 continue;
1566 }
1568 foreach($_POST as $Pname => $Pvalue){
1569 if(preg_match($name,$Pname)){
1570 $LOCK_VARS_USED_POST[$Pname] = $_POST[$Pname];
1571 }
1572 }
1574 foreach($_GET as $Pname => $Pvalue){
1575 if(preg_match($name,$Pname)){
1576 $LOCK_VARS_USED_GET[$Pname] = $_GET[$Pname];
1577 }
1578 }
1580 foreach($_REQUEST as $Pname => $Pvalue){
1581 if(preg_match($name,$Pname)){
1582 $LOCK_VARS_USED_REQUEST[$Pname] = $_REQUEST[$Pname];
1583 }
1584 }
1585 }
1586 session::set('LOCK_VARS_TO_USE',array());
1587 session::set('LOCK_VARS_USED_GET' , $LOCK_VARS_USED_GET);
1588 session::set('LOCK_VARS_USED_POST' , $LOCK_VARS_USED_POST);
1589 session::set('LOCK_VARS_USED_REQUEST' , $LOCK_VARS_USED_REQUEST);
1590 }
1592 /* Prepare and show template */
1593 $smarty= get_smarty();
1594 $smarty->assign("allow_readonly",$allow_readonly);
1595 $msg= msgPool::buildList($dn);
1597 $smarty->assign ("dn", $msg);
1598 if ($remove){
1599 $smarty->assign ("action", _("Continue anyway"));
1600 } else {
1601 $smarty->assign ("action", _("Edit anyway"));
1602 }
1604 $smarty->assign ("message", _("These entries are currently locked:"). $msg);
1606 return ($smarty->fetch (get_template_path('islocked.tpl')));
1607 }
1610 /*! \brief Return a string/HTML representation of an array
1611 *
1612 * This returns a string representation of a given value.
1613 * It can be used to dump arrays, where every value is printed
1614 * on its own line. The output is targetted at HTML output, it uses
1615 * '<br>' for line breaks. If the value is already a string its
1616 * returned unchanged.
1617 *
1618 * \param mixed 'value' Whatever needs to be printed.
1619 * \return string
1620 */
1621 function to_string ($value)
1622 {
1623 /* If this is an array, generate a text blob */
1624 if (is_array($value)){
1625 $ret= "";
1626 foreach ($value as $line){
1627 $ret.= $line."<br>\n";
1628 }
1629 return ($ret);
1630 } else {
1631 return ($value);
1632 }
1633 }
1636 /*! \brief Return a list of all printers in the current base
1637 *
1638 * Returns an array with the CNs of all printers (objects with
1639 * objectClass gotoPrinter) in the current base.
1640 * ($config->current['BASE']).
1641 *
1642 * Example:
1643 * \code
1644 * $this->printerList = get_printer_list();
1645 * \endcode
1646 *
1647 * \return array an array with the CNs of the printers as key and value.
1648 * */
1649 function get_printer_list()
1650 {
1651 global $config;
1652 $res = array();
1653 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1654 foreach($data as $attrs ){
1655 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1656 }
1657 return $res;
1658 }
1661 /*! \brief Function to rewrite some problematic characters
1662 *
1663 * This function takes a string and replaces all possibly characters in it
1664 * with less problematic characters, as defined in $REWRITE.
1665 *
1666 * \param string 's' the string to rewrite
1667 * \return string 's' the result of the rewrite
1668 * */
1669 function rewrite($s)
1670 {
1671 global $REWRITE;
1673 foreach ($REWRITE as $key => $val){
1674 $s= str_replace("$key", "$val", $s);
1675 }
1677 return ($s);
1678 }
1681 /*! \brief Return the base of a given DN
1682 *
1683 * \param string 'dn' a DN
1684 * */
1685 function dn2base($dn)
1686 {
1687 global $config;
1689 if (get_people_ou() != ""){
1690 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1691 }
1692 if (get_groups_ou() != ""){
1693 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1694 }
1695 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1697 return ($base);
1698 }
1701 /*! \brief Check if a given command exists and is executable
1702 *
1703 * Test if a given cmdline contains an executable command. Strips
1704 * arguments from the given cmdline.
1705 *
1706 * \param string 'cmdline' the cmdline to check
1707 * \return TRUE if command exists and is executable, otherwise FALSE.
1708 * */
1709 function check_command($cmdline)
1710 {
1711 $cmd= preg_replace("/ .*$/", "", $cmdline);
1713 /* Check if command exists in filesystem */
1714 if (!file_exists($cmd)){
1715 return (FALSE);
1716 }
1718 /* Check if command is executable */
1719 if (!is_executable($cmd)){
1720 return (FALSE);
1721 }
1723 return (TRUE);
1724 }
1727 /*! \brief Print plugin HTML header
1728 *
1729 * \param string 'image' the path of the image to be used next to the headline
1730 * \param string 'image' the headline
1731 * \param string 'info' additional information to print
1732 */
1733 function print_header($image, $headline, $info= "")
1734 {
1735 $display= "<div class=\"plugtop\">\n";
1736 $display.= " <p class=\"center\" style=\"margin:0px 0px 0px 5px;padding:0px;font-size:24px;\"><img class=\"center\" src=\"$image\" align=\"middle\" alt=\"*\"> $headline</p>\n";
1737 $display.= "</div>\n";
1739 if ($info != ""){
1740 $display.= "<div class=\"pluginfo\">\n";
1741 $display.= "$info";
1742 $display.= "</div>\n";
1743 } else {
1744 $display.= "<div style=\"height:5px;\">\n";
1745 $display.= " ";
1746 $display.= "</div>\n";
1747 }
1748 return ($display);
1749 }
1752 /*! \brief Print page number selector for paged lists
1753 *
1754 * \param int 'dcnt' Number of entries
1755 * \param int 'start' Page to start
1756 * \param int 'range' Number of entries per page
1757 * \param string 'post_var' POST variable to check for range
1758 */
1759 function range_selector($dcnt,$start,$range=25,$post_var=false)
1760 {
1762 /* Entries shown left and right from the selected entry */
1763 $max_entries= 10;
1765 /* Initialize and take care that max_entries is even */
1766 $output="";
1767 if ($max_entries & 1){
1768 $max_entries++;
1769 }
1771 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1772 $range= $_POST[$post_var];
1773 }
1775 /* Prevent output to start or end out of range */
1776 if ($start < 0 ){
1777 $start= 0 ;
1778 }
1779 if ($start >= $dcnt){
1780 $start= $range * (int)(($dcnt / $range) + 0.5);
1781 }
1783 $numpages= (($dcnt / $range));
1784 if(((int)($numpages))!=($numpages)){
1785 $numpages = (int)$numpages + 1;
1786 }
1787 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1788 return ("");
1789 }
1790 $ppage= (int)(($start / $range) + 0.5);
1793 /* Align selected page to +/- max_entries/2 */
1794 $begin= $ppage - $max_entries/2;
1795 $end= $ppage + $max_entries/2;
1797 /* Adjust begin/end, so that the selected value is somewhere in
1798 the middle and the size is max_entries if possible */
1799 if ($begin < 0){
1800 $end-= $begin + 1;
1801 $begin= 0;
1802 }
1803 if ($end > $numpages) {
1804 $end= $numpages;
1805 }
1806 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1807 $begin= $end - $max_entries;
1808 }
1810 if($post_var){
1811 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1812 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1813 }else{
1814 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1815 }
1817 /* Draw decrement */
1818 if ($start > 0 ) {
1819 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1820 (($start-$range))."\">".
1821 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1822 }
1824 /* Draw pages */
1825 for ($i= $begin; $i < $end; $i++) {
1826 if ($ppage == $i){
1827 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1828 validate($_GET['plug'])."&start=".
1829 ($i*$range)."\"> ".($i+1)." </a>";
1830 } else {
1831 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1832 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1833 }
1834 }
1836 /* Draw increment */
1837 if($start < ($dcnt-$range)) {
1838 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1839 (($start+($range)))."\">".
1840 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1841 }
1843 if(($post_var)&&($numpages)){
1844 $output.= "</td><td style='width:25%;text-align:right;vertical-align:middle;'> "._("Entries per page")." <select style='vertical-align:middle;' name='".$post_var."' onChange='javascript:document.mainform.submit()'>";
1845 foreach(array(20,50,100,200,"all") as $num){
1846 if($num == "all"){
1847 $var = 10000;
1848 }else{
1849 $var = $num;
1850 }
1851 if($var == $range){
1852 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1853 }else{
1854 $output.="\n<option value='".$var."'>".$num."</option>";
1855 }
1856 }
1857 $output.= "</select></td></tr></table></div>";
1858 }else{
1859 $output.= "</div>";
1860 }
1862 return($output);
1863 }
1867 /*! \brief Generate HTML for the 'Back' button */
1868 function back_to_main()
1869 {
1870 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1871 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1873 return ($string);
1874 }
1877 /*! \brief Put netmask in n.n.n.n format
1878 * \param string 'netmask' The netmask
1879 * \return string Converted netmask
1880 */
1881 function normalize_netmask($netmask)
1882 {
1883 /* Check for notation of netmask */
1884 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1885 $num= (int)($netmask);
1886 $netmask= "";
1888 for ($byte= 0; $byte<4; $byte++){
1889 $result=0;
1891 for ($i= 7; $i>=0; $i--){
1892 if ($num-- > 0){
1893 $result+= pow(2,$i);
1894 }
1895 }
1897 $netmask.= $result.".";
1898 }
1900 return (preg_replace('/\.$/', '', $netmask));
1901 }
1903 return ($netmask);
1904 }
1907 /*! \brief Return the number of set bits in the netmask
1908 *
1909 * For a given subnetmask (for example 255.255.255.0) this returns
1910 * the number of set bits.
1911 *
1912 * Example:
1913 * \code
1914 * $bits = netmask_to_bits('255.255.255.0') # Returns 24
1915 * $bits = netmask_to_bits('255.255.254.0') # Returns 23
1916 * \endcode
1917 *
1918 * Be aware of the fact that the function does not check
1919 * if the given subnet mask is actually valid. For example:
1920 * Bad examples:
1921 * \code
1922 * $bits = netmask_to_bits('255.0.0.255') # Returns 16
1923 * $bits = netmask_to_bits('255.255.0.255') # Returns 24
1924 * \endcode
1925 */
1926 function netmask_to_bits($netmask)
1927 {
1928 list($nm0, $nm1, $nm2, $nm3)= explode('.', $netmask);
1929 $res= 0;
1931 for ($n= 0; $n<4; $n++){
1932 $start= 255;
1933 $name= "nm$n";
1935 for ($i= 0; $i<8; $i++){
1936 if ($start == (int)($$name)){
1937 $res+= 8 - $i;
1938 break;
1939 }
1940 $start-= pow(2,$i);
1941 }
1942 }
1944 return ($res);
1945 }
1948 /*! \brief Recursion helper for gen_id() */
1949 function recurse($rule, $variables)
1950 {
1951 $result= array();
1953 if (!count($variables)){
1954 return array($rule);
1955 }
1957 reset($variables);
1958 $key= key($variables);
1959 $val= current($variables);
1960 unset ($variables[$key]);
1962 foreach($val as $possibility){
1963 $nrule= str_replace("{$key}", $possibility, $rule);
1964 $result= array_merge($result, recurse($nrule, $variables));
1965 }
1967 return ($result);
1968 }
1971 /*! \brief Expands user ID based on possible rules
1972 *
1973 * Unroll given rule string by filling in attributes.
1974 *
1975 * \param string 'rule' The rule string from gosa.conf.
1976 * \param array 'attributes' A dictionary of attribute/value mappings
1977 * \return string Expanded string, still containing the id keyword.
1978 */
1979 function expand_id($rule, $attributes)
1980 {
1981 /* Check for id rule */
1982 if(preg_match('/^id(:|#|!)\d+$/',$rule)){
1983 return (array("{$rule}"));
1984 }
1986 /* Check for clean attribute */
1987 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1988 $rule= preg_replace('/^%/', '', $rule);
1989 $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
1990 return (array($val));
1991 }
1993 /* Check for attribute with parameters */
1994 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1995 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1996 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1997 $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
1998 $start= preg_replace ('/-.*$/', '', $param);
1999 $stop = preg_replace ('/^[^-]+-/', '', $param);
2001 /* Assemble results */
2002 $result= array();
2003 for ($i= $start; $i<= $stop; $i++){
2004 $result[]= substr($val, 0, $i);
2005 }
2006 return ($result);
2007 }
2009 echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
2010 return (array($rule));
2011 }
2014 /*! \brief Generate a list of uid proposals based on a rule
2015 *
2016 * Unroll given rule string by filling in attributes and replacing
2017 * all keywords.
2018 *
2019 * \param string 'rule' The rule string from gosa.conf.
2020 * \param array 'attributes' A dictionary of attribute/value mappings
2021 * \return array List of valid not used uids
2022 */
2023 function gen_uids($rule, $attributes)
2024 {
2025 global $config;
2027 /* Search for keys and fill the variables array with all
2028 possible values for that key. */
2029 $part= "";
2030 $trigger= false;
2031 $stripped= "";
2032 $variables= array();
2034 for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
2036 if ($rule[$pos] == "{" ){
2037 $trigger= true;
2038 $part= "";
2039 continue;
2040 }
2042 if ($rule[$pos] == "}" ){
2043 $variables[$pos]= expand_id($part, $attributes);
2044 $stripped.= "{".$pos."}";
2045 $trigger= false;
2046 continue;
2047 }
2049 if ($trigger){
2050 $part.= $rule[$pos];
2051 } else {
2052 $stripped.= $rule[$pos];
2053 }
2054 }
2056 /* Recurse through all possible combinations */
2057 $proposed= recurse($stripped, $variables);
2059 /* Get list of used ID's */
2060 $ldap= $config->get_ldap_link();
2061 $ldap->cd($config->current['BASE']);
2063 /* Remove used uids and watch out for id tags */
2064 $ret= array();
2065 foreach($proposed as $uid){
2067 /* Check for id tag and modify uid if needed */
2068 if(preg_match('/\{id(:|!)\d+}/',$uid, $m)){
2069 $size= preg_replace('/^.*{id(:|!)(\d+)}.*$/', '\\2', $uid);
2071 $start= $m[1]==":"?0:-1;
2072 for ($i= $start, $p= pow(10,$size)-1; $i < $p; $i++){
2073 if ($i == -1) {
2074 $number= "";
2075 } else {
2076 $number= sprintf("%0".$size."d", $i+1);
2077 }
2078 $res= preg_replace('/{id(:|!)\d+}/', $number, $uid);
2080 $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
2081 if($ldap->count() == 0){
2082 $uid= $res;
2083 break;
2084 }
2085 }
2087 /* Remove link if nothing has been found */
2088 $uid= preg_replace('/{id(:|!)\d+}/', '', $uid);
2089 }
2091 if(preg_match('/\{id#\d+}/',$uid)){
2092 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
2094 while (true){
2095 mt_srand((double) microtime()*1000000);
2096 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
2097 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
2098 $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
2099 if($ldap->count() == 0){
2100 $uid= $res;
2101 break;
2102 }
2103 }
2105 /* Remove link if nothing has been found */
2106 $uid= preg_replace('/{id#\d+}/', '', $uid);
2107 }
2109 /* Don't assign used ones */
2110 $ldap->search("(uid=".preg_replace('/[{}]/', '', $uid).")",array('dn'));
2111 if($ldap->count() == 0){
2112 /* Add uid, but remove {} first. These are invalid anyway. */
2113 $ret[]= preg_replace('/[{}]/', '', $uid);
2114 }
2115 }
2117 return(array_unique($ret));
2118 }
2121 /*! \brief Convert various data sizes to bytes
2122 *
2123 * Given a certain value in the format n(g|m|k), where n
2124 * is a value and (g|m|k) stands for Gigabyte, Megabyte and Kilobyte
2125 * this function returns the byte value.
2126 *
2127 * \param string 'value' a value in the above specified format
2128 * \return a byte value or the original value if specified string is simply
2129 * a numeric value
2130 *
2131 */
2132 function to_byte($value) {
2133 $value= strtolower(trim($value));
2135 if(!is_numeric(substr($value, -1))) {
2137 switch(substr($value, -1)) {
2138 case 'g':
2139 $mult= 1073741824;
2140 break;
2141 case 'm':
2142 $mult= 1048576;
2143 break;
2144 case 'k':
2145 $mult= 1024;
2146 break;
2147 }
2149 return ($mult * (int)substr($value, 0, -1));
2150 } else {
2151 return $value;
2152 }
2153 }
2156 /*! \brief Check if a value exists in an array (case-insensitive)
2157 *
2158 * This is just as http://php.net/in_array except that the comparison
2159 * is case-insensitive.
2160 *
2161 * \param string 'value' needle
2162 * \param array 'items' haystack
2163 */
2164 function in_array_ics($value, $items)
2165 {
2166 return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
2167 }
2170 /*! \brief Removes malicious characters from a (POST) string. */
2171 function validate($string)
2172 {
2173 return (strip_tags(str_replace('\0', '', $string)));
2174 }
2177 /*! \brief Evaluate the current GOsa version from the build in revision string */
2178 function get_gosa_version()
2179 {
2180 global $svn_revision, $svn_path;
2182 /* Extract informations */
2183 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
2185 /* Release or development? */
2186 if (preg_match('%/gosa/trunk/%', $svn_path)){
2187 return (sprintf(_("GOsa development snapshot (Rev %s)"), bold($revision)));
2188 } else {
2189 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
2190 return (sprintf(_("GOsa $release"), $revision));
2191 }
2192 }
2195 /*! \brief Recursively delete a path in the file system
2196 *
2197 * Will delete the given path and all its files recursively.
2198 * Can also follow links if told so.
2199 *
2200 * \param string 'path'
2201 * \param boolean 'followLinks' TRUE to follow links, FALSE (default)
2202 * for not following links
2203 */
2204 function rmdirRecursive($path, $followLinks=false) {
2205 $dir= opendir($path);
2206 while($entry= readdir($dir)) {
2207 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
2208 unlink($path."/".$entry);
2209 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
2210 rmdirRecursive($path."/".$entry);
2211 }
2212 }
2213 closedir($dir);
2214 return rmdir($path);
2215 }
2218 /*! \brief Get directory content information
2219 *
2220 * Returns the content of a directory as an array in an
2221 * ascended sorted manner.
2222 *
2223 * \param string 'path'
2224 * \param boolean weither to sort the content descending.
2225 */
2226 function scan_directory($path,$sort_desc=false)
2227 {
2228 $ret = false;
2230 /* is this a dir ? */
2231 if(is_dir($path)) {
2233 /* is this path a readable one */
2234 if(is_readable($path)){
2236 /* Get contents and write it into an array */
2237 $ret = array();
2239 $dir = opendir($path);
2241 /* Is this a correct result ?*/
2242 if($dir){
2243 while($fp = readdir($dir))
2244 $ret[]= $fp;
2245 }
2246 }
2247 }
2248 /* Sort array ascending , like scandir */
2249 sort($ret);
2251 /* Sort descending if parameter is sort_desc is set */
2252 if($sort_desc) {
2253 $ret = array_reverse($ret);
2254 }
2256 return($ret);
2257 }
2260 /*! \brief Clean the smarty compile dir */
2261 function clean_smarty_compile_dir($directory)
2262 {
2263 global $svn_revision;
2265 if(is_dir($directory) && is_readable($directory)) {
2266 // Set revision filename to REVISION
2267 $revision_file= $directory."/REVISION";
2269 /* Is there a stamp containing the current revision? */
2270 if(!file_exists($revision_file)) {
2271 // create revision file
2272 create_revision($revision_file, $svn_revision);
2273 } else {
2274 # check for "$config->...['CONFIG']/revision" and the
2275 # contents should match the revision number
2276 if(!compare_revision($revision_file, $svn_revision)){
2277 // If revision differs, clean compile directory
2278 foreach(scan_directory($directory) as $file) {
2279 if(($file==".")||($file=="..")) continue;
2280 if( is_file($directory."/".$file) &&
2281 is_writable($directory."/".$file)) {
2282 // delete file
2283 if(!unlink($directory."/".$file)) {
2284 msg_dialog::display(_("Internal error"), sprintf(_("File %s cannot be deleted!"), bold($directory."/".$file)), ERROR_DIALOG);
2285 // This should never be reached
2286 }
2287 } elseif(is_dir($directory."/".$file) &&
2288 is_writable($directory."/".$file)) {
2289 // Just recursively delete it
2290 rmdirRecursive($directory."/".$file);
2291 }
2292 }
2293 // We should now create a fresh revision file
2294 clean_smarty_compile_dir($directory);
2295 } else {
2296 // Revision matches, nothing to do
2297 }
2298 }
2299 } else {
2300 // Smarty compile dir is not accessible
2301 // (Smarty will warn about this)
2302 }
2303 }
2306 function create_revision($revision_file, $revision)
2307 {
2308 $result= false;
2310 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2311 if($fh= fopen($revision_file, "w")) {
2312 if(fwrite($fh, $revision)) {
2313 $result= true;
2314 }
2315 }
2316 fclose($fh);
2317 } else {
2318 msg_dialog::display(_("Internal error"), _("Cannot write revision file!"), ERROR_DIALOG);
2319 }
2321 return $result;
2322 }
2325 function compare_revision($revision_file, $revision)
2326 {
2327 // false means revision differs
2328 $result= false;
2330 if(file_exists($revision_file) && is_readable($revision_file)) {
2331 // Open file
2332 if($fh= fopen($revision_file, "r")) {
2333 // Compare File contents with current revision
2334 if($revision == fread($fh, filesize($revision_file))) {
2335 $result= true;
2336 }
2337 } else {
2338 msg_dialog::display(_("Internal error"), _("Cannot write revision file!"), ERROR_DIALOG);
2339 }
2340 // Close file
2341 fclose($fh);
2342 }
2344 return $result;
2345 }
2348 /*! \brief Return HTML for a progressbar
2349 *
2350 * \code
2351 * $smarty->assign("installprogress", progressbar($current_progress_in_percent),100,15,true);
2352 * \endcode
2353 *
2354 * \param int 'percentage' Value to display
2355 * \param int 'width' width of the resulting output
2356 * \param int 'height' height of the resulting output
2357 * \param boolean 'showtext' weither to show the percentage in the progressbar or not
2358 * */
2359 function progressbar($percentage, $width= 200, $height= 14, $showText= false, $colorize= true, $id= "")
2360 {
2361 $text= "";
2362 $class= "";
2363 $style= "width:${width}px;height:${height}px;";
2365 // Fix percentage range
2366 $percentage= floor($percentage);
2367 if ($percentage > 100) {
2368 $percentage= 100;
2369 }
2370 if ($percentage < 0) {
2371 $percentage= 0;
2372 }
2374 // Only show text if we're above 10px height
2375 if ($showText && $height>10){
2376 $text= $percentage."%";
2377 }
2379 // Set font size
2380 $style.= "font-size:".($height-3)."px;";
2382 // Set color
2383 if ($colorize){
2384 if ($percentage < 70) {
2385 $class= " progress-low";
2386 } elseif ($percentage < 80) {
2387 $class= " progress-mid";
2388 } elseif ($percentage < 90) {
2389 $class= " progress-high";
2390 } else {
2391 $class= " progress-full";
2392 }
2393 }
2395 // Apply gradients
2396 $hoffset= floor($height / 2) + 4;
2397 $woffset= floor(($width+5) * (100-$percentage) / 100);
2398 foreach (array("-moz-box-shadow", "-webkit-box-shadow", "box-shadow") as $type) {
2399 $style.="$type:
2400 0 0 2px rgba(255, 255, 255, 0.4) inset,
2401 0 4px 6px rgba(255, 255, 255, 0.4) inset,
2402 0 ".$hoffset."px 0 -2px rgba(255, 255, 255, 0.2) inset,
2403 -".$woffset."px 0 0 -2px rgba(255, 255, 255, 0.2) inset,
2404 -".($woffset+1)."px 0 0 -2px rgba(0, 0, 0, 0.6) inset,
2405 0pt ".($hoffset+1)."px 8px rgba(0, 0, 0, 0.3) inset,
2406 0pt 1px 0px rgba(0, 0, 0, 0.2);";
2407 }
2409 // Set ID
2410 if ($id != ""){
2411 $id= "id='$id'";
2412 }
2414 return "<div class='progress$class' $id style='$style'>$text</div>";
2415 }
2418 /*! \brief Lookup a key in an array case-insensitive
2419 *
2420 * Given an associative array this can lookup the value of
2421 * a certain key, regardless of the case.
2422 *
2423 * \code
2424 * $items = array ('FOO' => 'blub', 'bar' => 'blub');
2425 * array_key_ics('foo', $items); # Returns 'blub'
2426 * array_key_ics('BAR', $items); # Returns 'blub'
2427 * \endcode
2428 *
2429 * \param string 'key' needle
2430 * \param array 'items' haystack
2431 */
2432 function array_key_ics($ikey, $items)
2433 {
2434 $tmp= array_change_key_case($items, CASE_LOWER);
2435 $ikey= strtolower($ikey);
2436 if (isset($tmp[$ikey])){
2437 return($tmp[$ikey]);
2438 }
2440 return ('');
2441 }
2444 /*! \brief Determine if two arrays are different
2445 *
2446 * \param array 'src'
2447 * \param array 'dst'
2448 * \return boolean TRUE or FALSE
2449 * */
2450 function array_differs($src, $dst)
2451 {
2452 /* If the count is differing, the arrays differ */
2453 if (count ($src) != count ($dst)){
2454 return (TRUE);
2455 }
2457 return (count(array_diff($src, $dst)) != 0);
2458 }
2461 function saveFilter($a_filter, $values)
2462 {
2463 if (isset($_POST['regexit'])){
2464 $a_filter["regex"]= $_POST['regexit'];
2466 foreach($values as $type){
2467 if (isset($_POST[$type])) {
2468 $a_filter[$type]= "checked";
2469 } else {
2470 $a_filter[$type]= "";
2471 }
2472 }
2473 }
2475 /* React on alphabet links if needed */
2476 if (isset($_GET['search'])){
2477 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2478 if ($s == "**"){
2479 $s= "*";
2480 }
2481 $a_filter['regex']= $s;
2482 }
2484 return ($a_filter);
2485 }
2488 /*! \brief Escape all LDAP filter relevant characters */
2489 function normalizeLdap($input)
2490 {
2491 return (addcslashes($input, '()|'));
2492 }
2495 /*! \brief Return the gosa base directory */
2496 function get_base_dir()
2497 {
2498 global $BASE_DIR;
2500 return $BASE_DIR;
2501 }
2504 /*! \brief Test weither we are allowed to read the object */
2505 function obj_is_readable($dn, $object, $attribute)
2506 {
2507 global $ui;
2509 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2510 }
2513 /*! \brief Test weither we are allowed to change the object */
2514 function obj_is_writable($dn, $object, $attribute)
2515 {
2516 global $ui;
2518 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2519 }
2522 /*! \brief Explode a DN into its parts
2523 *
2524 * Similar to explode (http://php.net/explode), but a bit more specific
2525 * for the needs when splitting, exploding LDAP DNs.
2526 *
2527 * \param string 'dn' the DN to split
2528 * \param config-object a config object. only neeeded if DN shall be verified in the LDAP
2529 * \param boolean verify_in_ldap check weither DN is valid
2530 *
2531 */
2532 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2533 {
2534 /* Initialize variables */
2535 $ret = array("count" => 0); // Set count to 0
2536 $next = true; // if false, then skip next loops and return
2537 $cnt = 0; // Current number of loops
2538 $max = 100; // Just for security, prevent looops
2539 $ldap = NULL; // To check if created result a valid
2540 $keep = ""; // save last failed parse string
2542 /* Check each parsed dn in ldap ? */
2543 if($config!==NULL && $verify_in_ldap){
2544 $ldap = $config->get_ldap_link();
2545 }
2547 /* Lets start */
2548 $called = false;
2549 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2551 $cnt ++;
2552 if(!preg_match("/,/",$dn)){
2553 $next = false;
2554 }
2555 $object = preg_replace("/[,].*$/","",$dn);
2556 $dn = preg_replace("/^[^,]+,/","",$dn);
2558 $called = true;
2560 /* Check if current dn is valid */
2561 if($ldap!==NULL){
2562 $ldap->cd($dn);
2563 $ldap->cat($dn,array("dn"));
2564 if($ldap->count()){
2565 $ret[] = $keep.$object;
2566 $keep = "";
2567 }else{
2568 $keep .= $object.",";
2569 }
2570 }else{
2571 $ret[] = $keep.$object;
2572 $keep = "";
2573 }
2574 }
2576 /* No dn was posted */
2577 if($cnt == 0 && !empty($dn)){
2578 $ret[] = $dn;
2579 }
2581 /* Append the rest */
2582 $test = $keep.$dn;
2583 if($called && !empty($test)){
2584 $ret[] = $keep.$dn;
2585 }
2586 $ret['count'] = count($ret) - 1;
2588 return($ret);
2589 }
2592 function get_base_from_hook($dn, $attrib)
2593 {
2594 global $config;
2596 if ($config->get_cfg_value("core","baseIdHook") != ""){
2598 /* Call hook script - if present */
2599 $command= $config->get_cfg_value("core","baseIdHook");
2601 if ($command != ""){
2602 $command.= " '".LDAP::fix($dn)."' $attrib";
2603 if (check_command($command)){
2604 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2605 exec($command, $output);
2606 if (preg_match("/^[0-9]+$/", $output[0])){
2607 return ($output[0]);
2608 } else {
2609 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2610 return ($config->get_cfg_value("core","uidNumberBase"));
2611 }
2612 } else {
2613 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2614 return ($config->get_cfg_value("core","uidNumberBase"));
2615 }
2617 } else {
2619 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2620 return ($config->get_cfg_value("core","uidNumberBase"));
2622 }
2623 }
2624 }
2627 /*! \brief Check if schema version matches the requirements */
2628 function check_schema_version($class, $version)
2629 {
2630 return preg_match("/\(v$version\)/", $class['DESC']);
2631 }
2634 /*! \brief Check if LDAP schema matches the requirements */
2635 function check_schema($cfg,$rfc2307bis = FALSE)
2636 {
2637 $messages= array();
2639 /* Get objectclasses */
2640 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2641 $objectclasses = $ldap->get_objectclasses();
2642 if(count($objectclasses) == 0){
2643 msg_dialog::display(_("Warning"), _("Cannot read schema information from LDAP. Schema validation is not possible!"), WARNING_DIALOG);
2644 }
2646 /* This is the default block used for each entry.
2647 * to avoid unset indexes.
2648 */
2649 $def_check = array("REQUIRED_VERSION" => "0",
2650 "SCHEMA_FILES" => array(),
2651 "CLASSES_REQUIRED" => array(),
2652 "STATUS" => FALSE,
2653 "IS_MUST_HAVE" => FALSE,
2654 "MSG" => "",
2655 "INFO" => "");
2657 /* The gosa base schema */
2658 $checks['gosaObject'] = $def_check;
2659 $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2660 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa-samba3.schema");
2661 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2662 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2664 /* GOsa Account class */
2665 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.6";
2666 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa-samba3.schema");
2667 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2668 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2669 $checks["gosaAccount"]["INFO"] = _("This class is used to make users appear in GOsa.");
2671 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2672 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2673 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa-samba3.schema");
2674 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2675 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2676 $checks["gosaLockEntry"]["INFO"] = _("This class is used to lock entries in order to prevent multiple edits at a time.");
2678 /* Some other checks */
2679 foreach(array(
2680 "gosaCacheEntry" => array("version" => "2.6.1", "class" => "gosaAccount"),
2681 "gosaDepartment" => array("version" => "2.6.1", "class" => "gosaAccount"),
2682 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2683 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2684 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2685 "gosaUserTemplate" => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2686 "gosaMailAccount" => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa-samba3.schema"),
2687 "gosaProxyAccount" => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa-samba3.schema"),
2688 "gosaApplication" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2689 "gosaApplicationGroup" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2690 "GOhard" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2691 "gotoTerminal" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2692 "goServer" => array("version" => "2.6.1", "class" => "server","file" => "goserver.schema"),
2693 "goTerminalServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2694 "goShareServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2695 "goNtpServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2696 "goSyslogServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2697 "goLdapServer" => array("version" => "2.6.1", "class" => "goServer"),
2698 "goCupsServer" => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2699 "goImapServer" => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa-samba3.schema"),
2700 "goKrbServer" => array("version" => "2.6.1", "class" => "goServer"),
2701 "goFaxServer" => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2702 ) as $name => $values){
2704 $checks[$name] = $def_check;
2705 if(isset($values['version'])){
2706 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2707 }
2708 if(isset($values['file'])){
2709 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2710 }
2711 if (isset($values['class'])) {
2712 $checks[$name]["CLASSES_REQUIRED"] = is_array($values['class'])?$values['class']:array($values['class']);
2713 }
2714 }
2715 foreach($checks as $name => $value){
2716 foreach($value['CLASSES_REQUIRED'] as $class){
2718 if(!isset($objectclasses[$name])){
2719 if($value['IS_MUST_HAVE']){
2720 $checks[$name]['STATUS'] = FALSE;
2721 $checks[$name]['MSG'] = sprintf(_("Required object class %s is missing!"), bold($class));
2722 } else {
2723 $checks[$name]['STATUS'] = TRUE;
2724 $checks[$name]['MSG'] = sprintf(_("Optional object class %s is missing!"), bold($class));
2725 }
2726 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2727 $checks[$name]['STATUS'] = FALSE;
2729 $checks[$name]['MSG'] = sprintf(_("Wrong version of required object class %s (!=%s) detected!"), bold($class), bold($value['REQUIRED_VERSION']));
2730 }else{
2731 $checks[$name]['STATUS'] = TRUE;
2732 $checks[$name]['MSG'] = sprintf(_("Class available"));
2733 }
2734 }
2735 }
2737 $tmp = $objectclasses;
2739 /* The gosa base schema */
2740 $checks['posixGroup'] = $def_check;
2741 $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2742 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa-samba3.schema","gosa-samba2.schema");
2743 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2744 $checks['posixGroup']['STATUS'] = TRUE;
2745 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2746 $checks['posixGroup']['MSG'] = "";
2747 $checks['posixGroup']['INFO'] = "";
2749 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2750 if(isset($tmp['posixGroup'])){
2752 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2753 $checks['posixGroup']['STATUS'] = FALSE;
2754 $checks['posixGroup']['MSG'] = _("RFC 2307bis group schema is enabled, but the current LDAP configuration does not support it!");
2755 $checks['posixGroup']['INFO'] = _("To use RFC 2307bis groups, the objectClass 'posixGroup' must be AUXILIARY.");
2756 }
2757 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2758 $checks['posixGroup']['STATUS'] = FALSE;
2759 $checks['posixGroup']['MSG'] = _("RFC 2307bis group schema is disabled, but the current LDAP configuration supports it!");
2760 $checks['posixGroup']['INFO'] = _("To correct this, the objectClass 'posixGroup' must be STRUCTURAL.");
2761 }
2762 }
2764 return($checks);
2765 }
2768 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2769 {
2770 $tmp = array(
2771 "de_DE" => "German",
2772 "fr_FR" => "French",
2773 "it_IT" => "Italian",
2774 "es_ES" => "Spanish",
2775 "en_US" => "English",
2776 "nl_NL" => "Dutch",
2777 "pl_PL" => "Polish",
2778 "pt_BR" => "Brazilian Portuguese",
2779 #"sv_SE" => "Swedish",
2780 "zh_CN" => "Chinese",
2781 "vi_VN" => "Vietnamese",
2782 "ru_RU" => "Russian");
2784 $tmp2= array(
2785 "de_DE" => _("German"),
2786 "fr_FR" => _("French"),
2787 "it_IT" => _("Italian"),
2788 "es_ES" => _("Spanish"),
2789 "en_US" => _("English"),
2790 "nl_NL" => _("Dutch"),
2791 "pl_PL" => _("Polish"),
2792 "pt_BR" => _("Brazilian Portuguese"),
2793 #"sv_SE" => _("Swedish"),
2794 "zh_CN" => _("Chinese"),
2795 "vi_VN" => _("Vietnamese"),
2796 "ru_RU" => _("Russian"));
2798 $ret = array();
2799 if($languages_in_own_language){
2801 $old_lang = setlocale(LC_ALL, 0);
2803 /* If the locale wasn't correclty set before, there may be an incorrect
2804 locale returned. Something like this:
2805 C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2806 Extract the locale name from this string and use it to restore old locale.
2807 */
2808 if(preg_match("/LC_CTYPE/",$old_lang)){
2809 $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2810 }
2812 foreach($tmp as $key => $name){
2813 $lang = $key.".UTF-8";
2814 setlocale(LC_ALL, $lang);
2815 if($strip_region_tag){
2816 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2817 }else{
2818 $ret[$key] = _($name)." (".$tmp2[$key].")";
2819 }
2820 }
2821 setlocale(LC_ALL, $old_lang);
2822 }else{
2823 foreach($tmp as $key => $name){
2824 if($strip_region_tag){
2825 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2826 }else{
2827 $ret[$key] = _($name);
2828 }
2829 }
2830 }
2831 return($ret);
2832 }
2835 /*! \brief Returns contents of the given POST variable and check magic quotes settings
2836 *
2837 * Depending on the magic quotes settings this returns a stripclashed'ed version of
2838 * a certain POST variable.
2839 *
2840 * \param string 'name' the POST var to return ($_POST[$name])
2841 * \return string
2842 * */
2843 function get_post($name)
2844 {
2845 if(!isset($_POST[$name])){
2846 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2847 return(FALSE);
2848 }
2850 if(get_magic_quotes_gpc()){
2851 return(stripcslashes(validate($_POST[$name])));
2852 }else{
2853 return(validate($_POST[$name]));
2854 }
2855 }
2858 /*! \brief Return class name in correct case */
2859 function get_correct_class_name($cls)
2860 {
2861 global $class_mapping;
2862 if(isset($class_mapping) && is_array($class_mapping)){
2863 foreach($class_mapping as $class => $file){
2864 if(preg_match("/^".$cls."$/i",$class)){
2865 return($class);
2866 }
2867 }
2868 }
2869 return(FALSE);
2870 }
2873 /*! \brief Change the password of a given DN
2874 *
2875 * Change the password of a given DN with the specified hash.
2876 *
2877 * \param string 'dn' the DN whose password shall be changed
2878 * \param string 'password' the password
2879 * \param int mode
2880 * \param string 'hash' which hash to use to encrypt it, default is empty
2881 * for cleartext storage.
2882 * \return boolean TRUE on success FALSE on error
2883 */
2884 function change_password ($dn, $password, $mode=0, $hash= "")
2885 {
2886 global $config;
2887 $newpass= "";
2889 /* Convert to lower. Methods are lowercase */
2890 $hash= strtolower($hash);
2892 // Get all available encryption Methods
2894 // NON STATIC CALL :)
2895 $methods = new passwordMethod(session::get('config'),$dn);
2896 $available = $methods->get_available_methods();
2898 // read current password entry for $dn, to detect the encryption Method
2899 $ldap = $config->get_ldap_link();
2900 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2901 $attrs = $ldap->fetch ();
2903 /* Is ensure that clear passwords will stay clear */
2904 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2905 $hash = "clear";
2906 }
2908 // Detect the encryption Method
2909 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2911 /* Check for supported algorithm */
2912 mt_srand((double) microtime()*1000000);
2914 /* Extract used hash */
2915 if ($hash == ""){
2916 $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2917 } else {
2918 $test = new $available[$hash]($config,$dn);
2919 $test->set_hash($hash);
2920 }
2922 } else {
2923 // User MD5 by default
2924 $hash= "md5";
2925 $test = new $available['md5']($config, $dn);
2926 }
2928 if($test instanceOf passwordMethod){
2930 $deactivated = $test->is_locked($config,$dn);
2932 /* Feed password backends with information */
2933 $test->dn= $dn;
2934 $test->attrs= $attrs;
2935 $newpass= $test->generate_hash($password);
2937 // Update shadow timestamp?
2938 if (isset($attrs["shadowLastChange"][0])){
2939 $shadow= (int)(date("U") / 86400);
2940 } else {
2941 $shadow= 0;
2942 }
2944 // Write back modified entry
2945 $ldap->cd($dn);
2946 $attrs= array();
2948 // Not for groups
2949 if ($mode == 0){
2950 // Create SMB Password
2951 $attrs= generate_smb_nt_hash($password);
2953 if ($shadow != 0){
2954 $attrs['shadowLastChange']= $shadow;
2955 }
2956 }
2958 $attrs['userPassword']= array();
2959 $attrs['userPassword']= $newpass;
2961 $ldap->modify($attrs);
2963 /* Read ! if user was deactivated */
2964 if($deactivated){
2965 $test->lock_account($config,$dn);
2966 }
2968 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2970 if (!$ldap->success()) {
2971 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2972 } else {
2974 /* Run backend method for change/create */
2975 if(!$test->set_password($password)){
2976 return(FALSE);
2977 }
2979 /* Find postmodify entries for this class */
2980 $command= $config->get_cfg_value("password","postmodify");
2982 if ($command != ""){
2983 /* Walk through attribute list */
2984 $command= preg_replace("/%userPassword/", $password, $command);
2985 $command= preg_replace("/%dn/", $dn, $command);
2987 if (check_command($command)){
2988 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2989 exec($command);
2990 } else {
2991 $message= sprintf(_("Command %s specified as post modify action for plugin %s does not exist!"), bold($command), bold("password"));
2992 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2993 }
2994 }
2995 }
2996 return(TRUE);
2997 }
2998 }
3001 /*! \brief Generate samba hashes
3002 *
3003 * Given a certain password this constructs an array like
3004 * array['sambaLMPassword'] etc.
3005 *
3006 * \param string 'password'
3007 * \return array contains several keys for lmPassword, ntPassword, pwdLastSet, etc. depending
3008 * on the samba version
3009 */
3010 function generate_smb_nt_hash($password)
3011 {
3012 global $config;
3014 # Try to use gosa-si?
3015 if ($config->get_cfg_value("core","gosaSupportURI") != ""){
3016 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
3017 if (isset($res['XML']['HASH'])){
3018 $hash= $res['XML']['HASH'];
3019 } else {
3020 $hash= "";
3021 }
3023 if ($hash == "") {
3024 msg_dialog::display(_("Configuration error"), _("Cannot generate SAMBA hash!"), ERROR_DIALOG);
3025 return ("");
3026 }
3027 } else {
3028 $tmp= $config->get_cfg_value("core",'sambaHashHook')." ".escapeshellarg($password);
3029 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
3031 exec($tmp, $ar);
3032 flush();
3033 reset($ar);
3034 $hash= current($ar);
3036 if ($hash == "") {
3037 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);
3038 return ("");
3039 }
3040 }
3042 list($lm,$nt)= explode(":", trim($hash));
3044 $attrs['sambaLMPassword']= $lm;
3045 $attrs['sambaNTPassword']= $nt;
3046 $attrs['sambaPwdLastSet']= date('U');
3047 $attrs['sambaBadPasswordCount']= "0";
3048 $attrs['sambaBadPasswordTime']= "0";
3049 return($attrs);
3050 }
3053 /*! \brief Get the Change Sequence Number of a certain DN
3054 *
3055 * To verify if a given object has been changed outside of Gosa
3056 * in the meanwhile, this function can be used to get the entryCSN
3057 * from the LDAP directory. It uses the attribute as configured
3058 * in modificationDetectionAttribute
3059 *
3060 * \param string 'dn'
3061 * \return either the result or "" in any other case
3062 */
3063 function getEntryCSN($dn)
3064 {
3065 global $config;
3066 if(empty($dn) || !is_object($config)){
3067 return("");
3068 }
3070 /* Get attribute that we should use as serial number */
3071 $attr= $config->get_cfg_value("core","modificationDetectionAttribute");
3072 if($attr != ""){
3073 $ldap = $config->get_ldap_link();
3074 $ldap->cat($dn,array($attr));
3075 $csn = $ldap->fetch();
3076 if(isset($csn[$attr][0])){
3077 return($csn[$attr][0]);
3078 }
3079 }
3080 return("");
3081 }
3084 /*! \brief Add (a) given objectClass(es) to an attrs entry
3085 *
3086 * The function adds the specified objectClass(es) to the given
3087 * attrs entry.
3088 *
3089 * \param mixed 'classes' Either a single objectClass or several objectClasses
3090 * as an array
3091 * \param array 'attrs' The attrs array to be modified.
3092 *
3093 * */
3094 function add_objectClass($classes, &$attrs)
3095 {
3096 if (is_array($classes)){
3097 $list= $classes;
3098 } else {
3099 $list= array($classes);
3100 }
3102 foreach ($list as $class){
3103 $attrs['objectClass'][]= $class;
3104 }
3105 }
3108 /*! \brief Removes a given objectClass from the attrs entry
3109 *
3110 * Similar to add_objectClass, except that it removes the given
3111 * objectClasses. See it for the params.
3112 * */
3113 function remove_objectClass($classes, &$attrs)
3114 {
3115 if (isset($attrs['objectClass'])){
3116 /* Array? */
3117 if (is_array($classes)){
3118 $list= $classes;
3119 } else {
3120 $list= array($classes);
3121 }
3123 $tmp= array();
3124 foreach ($attrs['objectClass'] as $oc) {
3125 foreach ($list as $class){
3126 if (strtolower($oc) != strtolower($class)){
3127 $tmp[]= $oc;
3128 }
3129 }
3130 }
3131 $attrs['objectClass']= $tmp;
3132 }
3133 }
3136 /*! \brief Initialize a file download with given content, name and data type.
3137 * \param string data The content to send.
3138 * \param string name The name of the file.
3139 * \param string type The content identifier, default value is "application/octet-stream";
3140 */
3141 function send_binary_content($data,$name,$type = "application/octet-stream")
3142 {
3143 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
3144 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
3145 header("Cache-Control: no-cache");
3146 header("Pragma: no-cache");
3147 header("Cache-Control: post-check=0, pre-check=0");
3148 header("Content-type: ".$type."");
3150 $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
3152 /* Strip name if it is a complete path */
3153 if (preg_match ("/\//", $name)) {
3154 $name= basename($name);
3155 }
3157 /* force download dialog */
3158 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
3159 header('Content-Disposition: filename="'.$name.'"');
3160 } else {
3161 header('Content-Disposition: attachment; filename="'.$name.'"');
3162 }
3164 echo $data;
3165 exit();
3166 }
3169 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
3170 {
3171 if(is_string($str)){
3172 return(htmlentities($str,$type,$charset));
3173 }elseif(is_array($str)){
3174 foreach($str as $name => $value){
3175 $str[$name] = reverse_html_entities($value,$type,$charset);
3176 }
3177 }
3178 return($str);
3179 }
3182 /*! \brief Encode special string characters so we can use the string in \
3183 HTML output, without breaking quotes.
3184 \param string The String we want to encode.
3185 \return string The encoded String
3186 */
3187 function xmlentities($str)
3188 {
3189 if(is_string($str)){
3191 static $asc2uni= array();
3192 if (!count($asc2uni)){
3193 for($i=128;$i<256;$i++){
3194 # $asc2uni[chr($i)] = "&#x".dechex($i).";";
3195 }
3196 }
3198 $str = str_replace("&", "&", $str);
3199 $str = str_replace("<", "<", $str);
3200 $str = str_replace(">", ">", $str);
3201 $str = str_replace("'", "'", $str);
3202 $str = str_replace("\"", """, $str);
3203 $str = str_replace("\r", "", $str);
3204 $str = strtr($str,$asc2uni);
3205 return $str;
3206 }elseif(is_array($str)){
3207 foreach($str as $name => $value){
3208 $str[$name] = xmlentities($value);
3209 }
3210 }
3211 return($str);
3212 }
3215 /*! \brief Updates all accessTo attributes from a given value to a new one.
3216 For example if a host is renamed.
3217 \param String $from The source accessTo name.
3218 \param String $to The destination accessTo name.
3219 */
3220 function update_accessTo($from,$to)
3221 {
3222 global $config;
3223 $ldap = $config->get_ldap_link();
3224 $ldap->cd($config->current['BASE']);
3225 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
3226 while($attrs = $ldap->fetch()){
3227 $new_attrs = array("accessTo" => array());
3228 $dn = $attrs['dn'];
3229 for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
3230 $new_attrs['objectClass'][] = $attrs['objectClass'][$i];
3231 }
3232 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
3233 if($attrs['accessTo'][$i] == $from){
3234 if(!empty($to)){
3235 $new_attrs['accessTo'][] = $to;
3236 }
3237 }else{
3238 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
3239 }
3240 }
3241 $ldap->cd($dn);
3242 $ldap->modify($new_attrs);
3243 if (!$ldap->success()){
3244 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
3245 }
3246 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
3247 }
3248 }
3251 /*! \brief Returns a random char */
3252 function get_random_char () {
3253 $randno = rand (0, 63);
3254 if ($randno < 12) {
3255 return (chr ($randno + 46)); // Digits, '/' and '.'
3256 } else if ($randno < 38) {
3257 return (chr ($randno + 53)); // Uppercase
3258 } else {
3259 return (chr ($randno + 59)); // Lowercase
3260 }
3261 }
3264 function cred_encrypt($input, $password) {
3266 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3267 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3269 return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
3271 }
3274 function cred_decrypt($input,$password) {
3275 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3276 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3278 return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
3279 }
3282 function get_object_info()
3283 {
3284 return(session::get('objectinfo'));
3285 }
3288 function set_object_info($str = "")
3289 {
3290 session::set('objectinfo',$str);
3291 }
3294 function isIpInNet($ip, $net, $mask) {
3295 // Move to long ints
3296 $ip= ip2long($ip);
3297 $net= ip2long($net);
3298 $mask= ip2long($mask);
3300 // Mask given IP with mask. If it returns "net", we're in...
3301 $res= $ip & $mask;
3303 return ($res == $net);
3304 }
3307 function get_next_id($attrib, $dn)
3308 {
3309 global $config;
3311 switch ($config->get_cfg_value("core","idAllocationMethod")){
3312 case "pool":
3313 return get_next_id_pool($attrib);
3314 case "traditional":
3315 return get_next_id_traditional($attrib, $dn);
3316 }
3318 msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("unknown idAllocation method!"), ERROR_DIALOG);
3319 return null;
3320 }
3323 function get_next_id_pool($attrib) {
3324 global $config;
3326 /* Fill informational values */
3327 $min= $config->get_cfg_value("core","${attrib}PoolMin");
3328 $max= $config->get_cfg_value("core","${attrib}PoolMax");
3330 /* Sanity check */
3331 if ($min >= $max) {
3332 msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." ".sprintf(_("%sPoolMin >= %sPoolMax!"), bold($attrib), bold($attrib)), ERROR_DIALOG);
3333 return null;
3334 }
3336 /* ID to skip */
3337 $ldap= $config->get_ldap_link();
3338 $id= null;
3340 /* Try to allocate the ID several times before failing */
3341 $tries= 3;
3342 while ($tries--) {
3344 /* Look for ID map entry */
3345 $ldap->cd ($config->current['BASE']);
3346 $ldap->search ("(&(objectClass=sambaUnixIdPool)($attrib=*))", array("$attrib"));
3348 /* If it does not exist, create one with these defaults */
3349 if ($ldap->count() == 0) {
3350 /* Fill informational values */
3351 $minUserId= $config->get_cfg_value("core","uidNumberPoolMin");
3352 $minGroupId= $config->get_cfg_value("core","gidNumberPoolMin");
3354 /* Add as default */
3355 $attrs= array("objectClass" => array("organizationalUnit", "sambaUnixIdPool"));
3356 $attrs["ou"]= "idmap";
3357 $attrs["uidNumber"]= $minUserId;
3358 $attrs["gidNumber"]= $minGroupId;
3359 $ldap->cd("ou=idmap,".$config->current['BASE']);
3360 $ldap->add($attrs);
3361 if ($ldap->error != "Success") {
3362 msg_dialog::display(_("Error"), _("Cannot create sambaUnixIdPool entry!"), ERROR_DIALOG);
3363 return null;
3364 }
3365 $tries++;
3366 continue;
3367 }
3368 /* Bail out if it's not unique */
3369 if ($ldap->count() != 1) {
3370 msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("sambaUnixIdPool is not unique!"), ERROR_DIALOG);
3371 return null;
3372 }
3374 /* Store old attrib and generate new */
3375 $attrs= $ldap->fetch();
3376 $dn= $ldap->getDN();
3377 $oldAttr= $attrs[$attrib][0];
3378 $newAttr= $oldAttr + 1;
3380 /* Sanity check */
3381 if ($newAttr >= $max) {
3382 msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("no ID available!"), ERROR_DIALOG);
3383 return null;
3384 }
3385 if ($newAttr < $min) {
3386 msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("no ID available!"), ERROR_DIALOG);
3387 return null;
3388 }
3390 #FIXME: PHP is not able to do a modification of "del: .../add: ...", so this
3391 # is completely unsafe in the moment.
3392 #/* Remove old attr, add new attr */
3393 #$attrs= array($attrib => $oldAttr);
3394 #$ldap->rm($attrs, $dn);
3395 #if ($ldap->error != "Success") {
3396 # continue;
3397 #}
3398 $ldap->cd($dn);
3399 $ldap->modify(array($attrib => $newAttr));
3400 if ($ldap->error != "Success") {
3401 msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." ".$ldap->get_error(), ERROR_DIALOG);
3402 return null;
3403 } else {
3404 return $oldAttr;
3405 }
3406 }
3408 /* Bail out if we had problems getting the next id */
3409 if (!$tries) {
3410 msg_dialog::display(_("Error"), _("Cannot allocate free ID:")." "._("maximum number of tries exceeded!"), ERROR_DIALOG);
3411 }
3413 return $id;
3414 }
3417 function get_next_id_traditional($attrib, $dn)
3418 {
3419 global $config;
3421 $ids= array();
3422 $ldap= $config->get_ldap_link();
3424 $ldap->cd ($config->current['BASE']);
3425 if (preg_match('/gidNumber/i', $attrib)){
3426 $oc= "posixGroup";
3427 } else {
3428 $oc= "posixAccount";
3429 }
3430 $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
3432 /* Get list of ids */
3433 while ($attrs= $ldap->fetch()){
3434 $ids[]= (int)$attrs["$attrib"][0];
3435 }
3437 /* Add the nobody id */
3438 $ids[]= 65534;
3440 /* get the ranges */
3441 $tmp = array('0'=> 1000);
3442 if (preg_match('/posixAccount/', $oc) && $config->get_cfg_value("core","uidNumberBase") != ""){
3443 $tmp= explode('-',$config->get_cfg_value("core","uidNumberBase"));
3444 } elseif($config->get_cfg_value("core","gidNumberBase") != ""){
3445 $tmp= explode('-',$config->get_cfg_value("core","gidNumberBase"));
3446 }
3448 /* Set hwm to max if not set - for backward compatibility */
3449 $lwm= $tmp[0];
3450 if (isset($tmp[1])){
3451 $hwm= $tmp[1];
3452 } else {
3453 $hwm= pow(2,32);
3454 }
3455 /* Find out next free id near to UID_BASE */
3456 if ($config->get_cfg_value("core","baseIdHook") == ""){
3457 $base= $lwm;
3458 } else {
3459 /* Call base hook */
3460 $base= get_base_from_hook($dn, $attrib);
3461 }
3462 for ($id= $base; $id++; $id < pow(2,32)){
3463 if (!in_array($id, $ids)){
3464 return ($id);
3465 }
3466 }
3468 /* Should not happen */
3469 if ($id == $hwm){
3470 msg_dialog::display(_("Error"), _("Cannot allocate free ID!"), ERROR_DIALOG);
3471 exit;
3472 }
3473 }
3476 /* Mark the occurance of a string with a span */
3477 function mark($needle, $haystack, $ignorecase= true)
3478 {
3479 $result= "";
3481 while (preg_match('/^(.*)('.preg_quote($needle).')(.*)$/i', $haystack, $matches)) {
3482 $result.= $matches[1]."<span class='mark'>".$matches[2]."</span>";
3483 $haystack= $matches[3];
3484 }
3486 return $result.$haystack;
3487 }
3490 /* Return an image description using the path */
3491 function image($path, $action= "", $title= "", $align= "middle")
3492 {
3493 global $config;
3494 global $BASE_DIR;
3495 $label= null;
3497 // Bail out, if there's no style file
3498 if(!session::global_is_set("img-styles")){
3500 // Get theme
3501 if (isset ($config)){
3502 $theme= $config->get_cfg_value("core","theme");
3503 } else {
3504 # For debuging - avoid that there's no theme set
3505 die("config not set!");
3506 $theme= "default";
3507 }
3509 if (!file_exists("$BASE_DIR/ihtml/themes/$theme/img.styles")){
3510 die ("No img.style for this theme found!");
3511 }
3513 session::global_set('img-styles', unserialize(file_get_contents("$BASE_DIR/ihtml/themes/$theme/img.styles")));
3514 }
3515 $styles= session::global_get('img-styles');
3517 /* Extract labels from path */
3518 if (preg_match("/\.png\[(.*)\]$/", $path, $matches)) {
3519 $label= $matches[1];
3520 }
3522 $lbl= "";
3523 if ($label) {
3524 if (isset($styles["images/label-".$label.".png"])) {
3525 $lbl= "<div style='".$styles["images/label-".$label.".png"]."'></div>";
3526 } else {
3527 die("Invalid label specified: $label\n");
3528 }
3530 $path= preg_replace("/\[.*\]$/", "", $path);
3531 }
3533 // Non middle layout?
3534 if ($align == "middle") {
3535 $align= "";
3536 } else {
3537 $align= ";vertical-align:$align";
3538 }
3540 // Clickable image or not?
3541 if ($title != "") {
3542 $title= "title='$title'";
3543 }
3544 if ($action == "") {
3545 return "<div class='img' $title style='".$styles[$path]."$align'>$lbl</div>";
3546 } else {
3547 return "<input type='submit' class='img' id='$action' value='' name='$action' $title style='".$styles[$path]."$align'>";
3548 }
3549 }
3551 /*! \brief Encodes a complex string to be useable in HTML posts.
3552 */
3553 function postEncode($str)
3554 {
3555 return(preg_replace("/=/","_", base64_encode($str)));
3556 }
3558 /*! \brief Decodes a string encoded by postEncode
3559 */
3560 function postDecode($str)
3561 {
3562 return(base64_decode(preg_replace("/_/","=", $str)));
3563 }
3566 /*! \brief Generate styled output
3567 */
3568 function bold($str)
3569 {
3570 return "<span class='highlight'>$str</span>";
3571 }
3574 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3575 ?>