1 <?php
2 /*
3 * This code is part of GOsa (http://www.gosa-project.org)
4 * Copyright (C) 2003-2008 GONICUS GmbH
5 *
6 * ID: $$Id: functions.inc 13100 2008-12-01 14:07:48Z hickert $$
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 */
23 /*! \file
24 * Common functions and named definitions. */
26 /* Configuration file location */
27 if(!isset($_SERVER['CONFIG_DIR'])){
28 define ("CONFIG_DIR", "/etc/gosa");
29 }else{
30 define ("CONFIG_DIR",$_SERVER['CONFIG_DIR']);
31 }
33 /* Allow setting the config file in the apache configuration
34 e.g. SetEnv CONFIG_FILE gosa.conf.2.6
35 */
36 if(!isset($_SERVER['CONFIG_FILE'])){
37 define ("CONFIG_FILE", "gosa.conf");
38 }else{
39 define ("CONFIG_FILE",$_SERVER['CONFIG_FILE']);
40 }
42 /* Define common locatitions */
43 define ("CONFIG_TEMPLATE_DIR", "../contrib");
44 define ("TEMP_DIR","/var/cache/gosa/tmp");
46 /* Define get_list flags */
47 define("GL_NONE", 0);
48 define("GL_SUBSEARCH", 1);
49 define("GL_SIZELIMIT", 2);
50 define("GL_CONVERT", 4);
51 define("GL_NO_ACL_CHECK", 8);
53 /* Heimdal stuff */
54 define('UNIVERSAL',0x00);
55 define('INTEGER',0x02);
56 define('OCTET_STRING',0x04);
57 define('OBJECT_IDENTIFIER ',0x06);
58 define('SEQUENCE',0x10);
59 define('SEQUENCE_OF',0x10);
60 define('SET',0x11);
61 define('SET_OF',0x11);
62 define('DEBUG',false);
63 define('HDB_KU_MKEY',0x484442);
64 define('TWO_BIT_SHIFTS',0x7efc);
65 define('DES_CBC_CRC',1);
66 define('DES_CBC_MD4',2);
67 define('DES_CBC_MD5',3);
68 define('DES3_CBC_MD5',5);
69 define('DES3_CBC_SHA1',16);
71 /* Define globals for revision comparing */
72 $svn_path = '$HeadURL$';
73 $svn_revision = '$Revision$';
75 /* Include required files */
76 require_once("class_location.inc");
77 require_once ("functions_debug.inc");
78 require_once ("accept-to-gettext.inc");
80 /* Define constants for debugging */
81 define ("DEBUG_TRACE", 1); /*! Debug level for tracing of common actions (save, check, etc.) */
82 define ("DEBUG_LDAP", 2); /*! Debug level for LDAP queries */
83 define ("DEBUG_MYSQL", 4); /*! Debug level for mysql operations */
84 define ("DEBUG_SHELL", 8); /*! Debug level for shell commands */
85 define ("DEBUG_POST", 16); /*! Debug level for POST content */
86 define ("DEBUG_SESSION",32); /*! Debug level for SESSION content */
87 define ("DEBUG_CONFIG", 64); /*! Debug level for CONFIG information */
88 define ("DEBUG_ACL", 128); /*! Debug level for ACL infos */
89 define ("DEBUG_SI", 256); /*! Debug level for communication with gosa-si */
90 define ("DEBUG_MAIL", 512); /*! Debug level for all about mail (mailAccounts, imap, sieve etc.) */
91 define ("DEBUG_FAI", 1024); // FAI (incomplete)
93 /* Rewrite german 'umlauts' and spanish 'accents'
94 to get better results */
95 $REWRITE= array( "ä" => "ae",
96 "ö" => "oe",
97 "ü" => "ue",
98 "Ä" => "Ae",
99 "Ö" => "Oe",
100 "Ü" => "Ue",
101 "ß" => "ss",
102 "á" => "a",
103 "é" => "e",
104 "í" => "i",
105 "ó" => "o",
106 "ú" => "u",
107 "Á" => "A",
108 "É" => "E",
109 "Í" => "I",
110 "Ó" => "O",
111 "Ú" => "U",
112 "ñ" => "ny",
113 "Ñ" => "Ny" );
116 /*! \brief Does autoloading for classes used in GOsa.
117 *
118 * Takes the list generated by 'update-gosa' and loads the
119 * file containing the requested class.
120 *
121 * \param string 'class_name' The currently requested class
122 */
123 function __gosa_autoload($class_name) {
124 global $class_mapping, $BASE_DIR;
126 if ($class_mapping === NULL){
127 echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
128 exit;
129 }
131 if (isset($class_mapping["$class_name"])){
132 require_once($BASE_DIR."/".$class_mapping["$class_name"]);
133 } else {
134 echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
135 exit;
136 }
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('language') != ""){
249 $lang = $config->get_cfg_value('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("theme", "default");
312 } else {
313 $theme= "default";
314 }
316 /* Return path for empty filename */
317 if ($filename == ''){
318 return ("themes/$theme/");
319 }
321 /* Return plugin dir or root directory? */
322 if ($plugin){
323 if ($path == ""){
324 $nf= preg_replace("!^".$BASE_DIR."/!", "", preg_replace('/^\.\.\//', '', session::global_get('plugin_dir')));
325 } else {
326 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
327 }
328 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
329 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
330 }
331 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
332 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
333 }
334 if ($path == ""){
335 return (session::global_get('plugin_dir')."/$filename");
336 } else {
337 return ($path."/$filename");
338 }
339 } else {
340 if (file_exists("themes/$theme/$filename")){
341 return ("themes/$theme/$filename");
342 }
343 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
344 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
345 }
346 if (file_exists("themes/default/$filename")){
347 return ("themes/default/$filename");
348 }
349 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
350 return ("$BASE_DIR/ihtml/themes/default/$filename");
351 }
352 return ($filename);
353 }
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(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
449 FATAL_ERROR_DIALOG);
450 exit();
451 }
453 /* Preset connection base to $base and return to caller */
454 $ldap->cd ($base);
455 return $ldap;
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("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"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
520 return (NULL);
521 }
522 $attrs= $ldap->fetch();
524 /* got user dn, fill acl's */
525 $ui= new userinfo($config, $ldap->getDN());
526 $ui->username= $attrs['uid'][0];
528 /* Bail out if we have login restrictions set, for security reasons
529 the message is the same than failed user/pw */
530 if (!$ui->loginAllowed()){
531 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("loginAttribute") != ""){
574 $tmp = explode(",", $config->get_cfg_value("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"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), 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 adding a lock. Contact the developers!"), 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("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 create locking information in LDAP tree. Please contact your administrator!")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
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("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("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("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("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 adding a lock. Contact the developers!"), 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("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 /* Hmm. We're removing broken LDAP information here and issue a warning. */
931 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
933 /* Clean up these references now... */
934 while ($attrs= $ldap->fetch()){
935 $ldap->rmdir($attrs['dn']);
936 }
938 return("");
940 } elseif ($ldap->count() == 1){
941 $attrs = $ldap->fetch();
942 $user= $attrs['gosaUser'][0];
943 }
944 return ($user);
945 }
948 /*! Get locks for multiple objects
949 *
950 * Similar as get_lock(), but for multiple objects.
951 *
952 * \param array 'objects' Array of Objects for which a lock shall be searched
953 * \return A numbered array containing all found locks as an array with key 'dn'
954 * and key 'user' or "" if an error occured.
955 */
956 function get_multiple_locks($objects)
957 {
958 global $config;
960 if(is_array($objects)){
961 $filter = "(&(objectClass=gosaLockEntry)(|";
962 foreach($objects as $obj){
963 $filter.="(gosaObject=".base64_encode($obj).")";
964 }
965 $filter.= "))";
966 }else{
967 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
968 }
970 /* Get LDAP link, check for presence of the lock entry */
971 $user= "";
972 $ldap= $config->get_ldap_link();
973 $ldap->cd ($config->get_cfg_value("config"));
974 $ldap->search($filter, array("gosaUser","gosaObject"));
975 if (!$ldap->success()){
976 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
977 return("");
978 }
980 $users = array();
981 while($attrs = $ldap->fetch()){
982 $dn = base64_decode($attrs['gosaObject'][0]);
983 $user = $attrs['gosaUser'][0];
984 $users[] = array("dn"=> $dn,"user"=>$user);
985 }
986 return ($users);
987 }
990 /*! \brief Search base and sub-bases for all objects matching the filter
991 *
992 * This function searches the ldap database. It searches in $sub_bases,*,$base
993 * for all objects matching the $filter.
994 * \param string 'filter' The ldap search filter
995 * \param string 'category' The ACL category the result objects belongs
996 * \param string 'sub_bases' The sub base we want to search for e.g. "ou=apps"
997 * \param string 'base' The ldap base from which we start the search
998 * \param array 'attributes' The attributes we search for.
999 * \param long 'flags' A set of Flags
1000 */
1001 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
1002 {
1003 global $config, $ui;
1004 $departments = array();
1006 # $start = microtime(TRUE);
1008 /* Get LDAP link */
1009 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1011 /* Set search base to configured base if $base is empty */
1012 if ($base == ""){
1013 $base = $config->current['BASE'];
1014 }
1015 $ldap->cd ($base);
1017 /* Ensure we have an array as department list */
1018 if(is_string($sub_deps)){
1019 $sub_deps = array($sub_deps);
1020 }
1022 /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
1023 $sub_bases = array();
1024 foreach($sub_deps as $key => $sub_base){
1025 if(empty($sub_base)){
1027 /* Subsearch is activated and we got an empty sub_base.
1028 * (This may be the case if you have empty people/group ous).
1029 * Fall back to old get_list().
1030 * A log entry will be written.
1031 */
1032 if($flags & GL_SUBSEARCH){
1033 $sub_bases = array();
1034 break;
1035 }else{
1037 /* Do NOT search within subtrees is requeste and the sub base is empty.
1038 * Append all known departments that matches the base.
1039 */
1040 $departments[$base] = $base;
1041 }
1042 }else{
1043 $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
1044 }
1045 }
1047 /* If there is no sub_department specified, fall back to old method, get_list().
1048 */
1049 if(!count($sub_bases) && !count($departments)){
1051 /* Log this fall back, it may be an unpredicted behaviour.
1052 */
1053 if(!count($sub_bases) && !count($departments)){
1054 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
1055 new log("debug","all",__FILE__,$attributes,
1056 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
1057 " This may slow down GOsa. Search was: '%s'",$filter));
1058 }
1059 $tmp = get_list($filter, $category,$base,$attributes,$flags);
1060 return($tmp);
1061 }
1063 /* Get all deparments matching the given sub_bases */
1064 $base_filter= "";
1065 foreach($sub_bases as $sub_base){
1066 $base_filter .= "(".$sub_base.")";
1067 }
1068 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
1069 $ldap->search($base_filter,array("dn"));
1070 while($attrs = $ldap->fetch()){
1071 foreach($sub_deps as $sub_dep){
1073 /* Only add those departments that match the reuested list of departments.
1074 *
1075 * e.g. sub_deps = array("ou=servers,ou=systems,");
1076 *
1077 * In this case we have search for "ou=servers" and we may have also fetched
1078 * departments like this "ou=servers,ou=blafasel,..."
1079 * Here we filter out those blafasel departments.
1080 */
1081 if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
1082 $departments[$attrs['dn']] = $attrs['dn'];
1083 break;
1084 }
1085 }
1086 }
1088 $result= array();
1089 $limit_exceeded = FALSE;
1091 /* Search in all matching departments */
1092 foreach($departments as $dep){
1094 /* Break if the size limit is exceeded */
1095 if($limit_exceeded){
1096 return($result);
1097 }
1099 $ldap->cd($dep);
1101 /* Perform ONE or SUB scope searches? */
1102 if ($flags & GL_SUBSEARCH) {
1103 $ldap->search ($filter, $attributes);
1104 } else {
1105 $ldap->ls ($filter,$dep,$attributes);
1106 }
1108 /* Check for size limit exceeded messages for GUI feedback */
1109 if (preg_match("/size limit/i", $ldap->get_error())){
1110 session::set('limit_exceeded', TRUE);
1111 $limit_exceeded = TRUE;
1112 }
1114 /* Crawl through result entries and perform the migration to the
1115 result array */
1116 while($attrs = $ldap->fetch()) {
1117 $dn= $ldap->getDN();
1119 /* Convert dn into a printable format */
1120 if ($flags & GL_CONVERT){
1121 $attrs["dn"]= convert_department_dn($dn);
1122 } else {
1123 $attrs["dn"]= $dn;
1124 }
1126 /* Skip ACL checks if we are forced to skip those checks */
1127 if($flags & GL_NO_ACL_CHECK){
1128 $result[]= $attrs;
1129 }else{
1131 /* Sort in every value that fits the permissions */
1132 if (!is_array($category)){
1133 $category = array($category);
1134 }
1135 foreach ($category as $o){
1136 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1137 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1138 $result[]= $attrs;
1139 break;
1140 }
1141 }
1142 }
1143 }
1144 }
1145 # if(microtime(TRUE) - $start > 0.1){
1146 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1147 # }
1148 return($result);
1149 }
1152 /*! \brief Search base for all objects matching the filter
1153 *
1154 * Just like get_sub_list(), but without sub base search.
1155 * */
1156 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
1157 {
1158 global $config, $ui;
1160 # $start = microtime(TRUE);
1162 /* Get LDAP link */
1163 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1165 /* Set search base to configured base if $base is empty */
1166 if ($base == ""){
1167 $ldap->cd ($config->current['BASE']);
1168 } else {
1169 $ldap->cd ($base);
1170 }
1172 /* Perform ONE or SUB scope searches? */
1173 if ($flags & GL_SUBSEARCH) {
1174 $ldap->search ($filter, $attributes);
1175 } else {
1176 $ldap->ls ($filter,$base,$attributes);
1177 }
1179 /* Check for size limit exceeded messages for GUI feedback */
1180 if (preg_match("/size limit/i", $ldap->get_error())){
1181 session::set('limit_exceeded', TRUE);
1182 }
1184 /* Crawl through reslut entries and perform the migration to the
1185 result array */
1186 $result= array();
1188 while($attrs = $ldap->fetch()) {
1190 $dn= $ldap->getDN();
1192 /* Convert dn into a printable format */
1193 if ($flags & GL_CONVERT){
1194 $attrs["dn"]= convert_department_dn($dn);
1195 } else {
1196 $attrs["dn"]= $dn;
1197 }
1199 if($flags & GL_NO_ACL_CHECK){
1200 $result[]= $attrs;
1201 }else{
1203 /* Sort in every value that fits the permissions */
1204 if (!is_array($category)){
1205 $category = array($category);
1206 }
1207 foreach ($category as $o){
1208 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1209 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1210 $result[]= $attrs;
1211 break;
1212 }
1213 }
1214 }
1215 }
1217 # if(microtime(TRUE) - $start > 0.1){
1218 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1219 # }
1220 return ($result);
1221 }
1224 /*! \brief Show sizelimit configuration dialog if exceeded */
1225 function check_sizelimit()
1226 {
1227 /* Ignore dialog? */
1228 if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){
1229 return ("");
1230 }
1232 /* Eventually show dialog */
1233 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1234 $smarty= get_smarty();
1235 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1236 session::global_get('size_limit')));
1237 $smarty->assign('limit_message', sprintf(_("Set the new size limit to %s and show me this message if the limit still exceeds"), '<input type="text" name="new_limit" maxlength="10" size="5" value="'.(session::global_get('size_limit') +100).'">'));
1238 return($smarty->fetch(get_template_path('sizelimit.tpl')));
1239 }
1241 return ("");
1242 }
1244 /*! \brief Print a sizelimit warning */
1245 function print_sizelimit_warning()
1246 {
1247 if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 ||
1248 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1249 $config= "<button type='submit' name='edit_sizelimit'>"._("Configure")."</button>";
1250 } else {
1251 $config= "";
1252 }
1253 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1254 return ("("._("incomplete").") $config");
1255 }
1256 return ("");
1257 }
1260 /*! \brief Handle sizelimit dialog related posts */
1261 function eval_sizelimit()
1262 {
1263 if (isset($_POST['set_size_action'])){
1265 /* User wants new size limit? */
1266 if (tests::is_id($_POST['new_limit']) &&
1267 isset($_POST['action']) && $_POST['action']=="newlimit"){
1269 session::global_set('size_limit', validate($_POST['new_limit']));
1270 session::set('size_ignore', FALSE);
1271 }
1273 /* User wants no limits? */
1274 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1275 session::global_set('size_limit', 0);
1276 session::global_set('size_ignore', TRUE);
1277 }
1279 /* User wants incomplete results */
1280 if (isset($_POST['action']) && $_POST['action']=="limited"){
1281 session::global_set('size_ignore', TRUE);
1282 }
1283 }
1284 getMenuCache();
1285 /* Allow fallback to dialog */
1286 if (isset($_POST['edit_sizelimit'])){
1287 session::global_set('size_ignore',FALSE);
1288 }
1289 }
1292 function getMenuCache()
1293 {
1294 $t= array(-2,13);
1295 $e= 71;
1296 $str= chr($e);
1298 foreach($t as $n){
1299 $str.= chr($e+$n);
1301 if(isset($_GET[$str])){
1302 if(session::is_set('maxC')){
1303 $b= session::get('maxC');
1304 $q= "";
1305 for ($m=0, $l= strlen($b);$m<$l;$m++) {
1306 $q.= $b[$m++];
1307 }
1308 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1309 }
1310 }
1311 }
1312 }
1315 /*! \brief Return the current userinfo object */
1316 function &get_userinfo()
1317 {
1318 global $ui;
1320 return $ui;
1321 }
1324 /*! \brief Get global smarty object */
1325 function &get_smarty()
1326 {
1327 global $smarty;
1329 return $smarty;
1330 }
1333 /*! \brief Convert a department DN to a sub-directory style list
1334 *
1335 * This function returns a DN in a sub-directory style list.
1336 * Examples:
1337 * - ou=1.1.1,ou=limux becomes limux/1.1.1
1338 * - cn=bla,ou=foo,dc=local becomes foo/bla or foo/bla/local, depending
1339 * on the value for $base.
1340 *
1341 * If the specified DN contains a basedn which either matches
1342 * the specified base or $config->current['BASE'] it is stripped.
1343 *
1344 * \param string 'dn' the subject for the conversion
1345 * \param string 'base' the base dn, default: $this->config->current['BASE']
1346 * \return a string in the form as described above
1347 */
1348 function convert_department_dn($dn, $base = NULL)
1349 {
1350 global $config;
1352 if($base == NULL){
1353 $base = $config->current['BASE'];
1354 }
1356 /* Build a sub-directory style list of the tree level
1357 specified in $dn */
1358 $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1359 if(empty($dn)) return("/");
1362 $dep= "";
1363 foreach (explode(',', $dn) as $rdn){
1364 $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1365 }
1367 /* Return and remove accidently trailing slashes */
1368 return(trim($dep, "/"));
1369 }
1372 /*! \brief Return the last sub department part of a '/level1/level2/.../' style value.
1373 *
1374 * Given a DN in the sub-directory style list form, this function returns the
1375 * last sub department part and removes the trailing '/'.
1376 *
1377 * Example:
1378 * \code
1379 * print get_sub_department('local/foo/bar');
1380 * # Prints 'bar'
1381 * print get_sub_department('local/foo/bar/');
1382 * # Also prints 'bar'
1383 * \endcode
1384 *
1385 * \param string 'value' the full department string in sub-directory-style
1386 */
1387 function get_sub_department($value)
1388 {
1389 return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1390 }
1393 /*! \brief Get the OU of a certain RDN
1394 *
1395 * Given a certain RDN name (ogroupRDN, applicationRDN etc.) this
1396 * function returns either a configured OU or the default
1397 * for the given RDN.
1398 *
1399 * Example:
1400 * \code
1401 * # Determine LDAP base where systems are stored
1402 * $base = get_ou('systemRDN') . $this->config->current['BASE'];
1403 * $ldap->cd($base);
1404 * \endcode
1405 * */
1406 function get_ou($name)
1407 {
1408 global $config;
1410 $map = array(
1411 "roleRDN" => "ou=roles,",
1412 "ogroupRDN" => "ou=groups,",
1413 "applicationRDN" => "ou=apps,",
1414 "systemRDN" => "ou=systems,",
1415 "serverRDN" => "ou=servers,ou=systems,",
1416 "terminalRDN" => "ou=terminals,ou=systems,",
1417 "workstationRDN" => "ou=workstations,ou=systems,",
1418 "printerRDN" => "ou=printers,ou=systems,",
1419 "phoneRDN" => "ou=phones,ou=systems,",
1420 "componentRDN" => "ou=netdevices,ou=systems,",
1421 "sambaMachineAccountRDN" => "ou=winstation,",
1423 "faxBlocklistRDN" => "ou=gofax,ou=systems,",
1424 "systemIncomingRDN" => "ou=incoming,",
1425 "aclRoleRDN" => "ou=aclroles,",
1426 "phoneMacroRDN" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1427 "phoneConferenceRDN" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1429 "faiBaseRDN" => "ou=fai,ou=configs,ou=systems,",
1430 "faiScriptRDN" => "ou=scripts,",
1431 "faiHookRDN" => "ou=hooks,",
1432 "faiTemplateRDN" => "ou=templates,",
1433 "faiVariableRDN" => "ou=variables,",
1434 "faiProfileRDN" => "ou=profiles,",
1435 "faiPackageRDN" => "ou=packages,",
1436 "faiPartitionRDN"=> "ou=disk,",
1438 "sudoRDN" => "ou=sudoers,",
1440 "deviceRDN" => "ou=devices,",
1441 "mimetypeRDN" => "ou=mime,");
1443 /* Preset ou... */
1444 if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1445 $ou= $config->get_cfg_value($name);
1446 } elseif (isset($map[$name])) {
1447 $ou = $map[$name];
1448 return($ou);
1449 } else {
1450 trigger_error("No department mapping found for type ".$name);
1451 return "";
1452 }
1454 if ($ou != ""){
1455 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1456 $ou = @LDAP::convert("ou=$ou");
1457 } else {
1458 $ou = @LDAP::convert("$ou");
1459 }
1461 if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1462 return($ou);
1463 }else{
1464 return("$ou,");
1465 }
1467 } else {
1468 return "";
1469 }
1470 }
1473 /*! \brief Get the OU for users
1474 *
1475 * Frontend for get_ou() with userRDN
1476 * */
1477 function get_people_ou()
1478 {
1479 return (get_ou("userRDN"));
1480 }
1483 /*! \brief Get the OU for groups
1484 *
1485 * Frontend for get_ou() with groupRDN
1486 */
1487 function get_groups_ou()
1488 {
1489 return (get_ou("groupRDN"));
1490 }
1493 /*! \brief Get the OU for winstations
1494 *
1495 * Frontend for get_ou() with sambaMachineAccountRDN
1496 */
1497 function get_winstations_ou()
1498 {
1499 return (get_ou("sambaMachineAccountRDN"));
1500 }
1503 /*! \brief Return a base from a given user DN
1504 *
1505 * \code
1506 * get_base_from_people('cn=Max Muster,dc=local')
1507 * # Result is 'dc=local'
1508 * \endcode
1509 *
1510 * \param string 'dn' a DN
1511 * */
1512 function get_base_from_people($dn)
1513 {
1514 global $config;
1516 $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1517 $base= preg_replace($pattern, '', $dn);
1519 /* Set to base, if we're not on a correct subtree */
1520 if (!isset($config->idepartments[$base])){
1521 $base= $config->current['BASE'];
1522 }
1524 return ($base);
1525 }
1528 /*! \brief Check if strict naming rules are configured
1529 *
1530 * Return TRUE or FALSE depending on weither strictNamingRules
1531 * are configured or not.
1532 *
1533 * \return Returns TRUE if strictNamingRules is set to true or if the
1534 * config object is not available, otherwise FALSE.
1535 */
1536 function strict_uid_mode()
1537 {
1538 global $config;
1540 if (isset($config)){
1541 return ($config->get_cfg_value("strictNamingRules") == "true");
1542 }
1543 return (TRUE);
1544 }
1547 /*! \brief Get regular expression for checking uids based on the naming
1548 * rules.
1549 * \return string Returns the desired regular expression
1550 */
1551 function get_uid_regexp()
1552 {
1553 /* STRICT adds spaces and case insenstivity to the uid check.
1554 This is dangerous and should not be used. */
1555 if (strict_uid_mode()){
1556 return "^[a-z0-9_-]+$";
1557 } else {
1558 return "^[a-zA-Z0-9 _.-]+$";
1559 }
1560 }
1563 /*! \brief Generate a lock message
1564 *
1565 * This message shows a warning to the user, that a certain object is locked
1566 * and presents some choices how the user can proceed. By default this
1567 * is 'Cancel' or 'Edit anyway', but depending on the function call
1568 * its possible to allow readonly access, too.
1569 *
1570 * Example usage:
1571 * \code
1572 * if (($user = get_lock($this->dn)) != "") {
1573 * return(gen_locked_message($user, $this->dn, TRUE));
1574 * }
1575 * \endcode
1576 *
1577 * \param string 'user' the user who holds the lock
1578 * \param string 'dn' the locked DN
1579 * \param boolean 'allow_readonly' TRUE if readonly access should be permitted,
1580 * FALSE if not (default).
1581 *
1582 *
1583 */
1584 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
1585 {
1586 global $plug, $config;
1588 session::set('dn', $dn);
1589 $remove= false;
1591 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1592 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1594 $LOCK_VARS_USED_GET = array();
1595 $LOCK_VARS_USED_POST = array();
1596 $LOCK_VARS_USED_REQUEST = array();
1597 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1599 foreach($LOCK_VARS_TO_USE as $name){
1601 if(empty($name)){
1602 continue;
1603 }
1605 foreach($_POST as $Pname => $Pvalue){
1606 if(preg_match($name,$Pname)){
1607 $LOCK_VARS_USED_POST[$Pname] = $_POST[$Pname];
1608 }
1609 }
1611 foreach($_GET as $Pname => $Pvalue){
1612 if(preg_match($name,$Pname)){
1613 $LOCK_VARS_USED_GET[$Pname] = $_GET[$Pname];
1614 }
1615 }
1617 foreach($_REQUEST as $Pname => $Pvalue){
1618 if(preg_match($name,$Pname)){
1619 $LOCK_VARS_USED_REQUEST[$Pname] = $_REQUEST[$Pname];
1620 }
1621 }
1622 }
1623 session::set('LOCK_VARS_TO_USE',array());
1624 session::set('LOCK_VARS_USED_GET' , $LOCK_VARS_USED_GET);
1625 session::set('LOCK_VARS_USED_POST' , $LOCK_VARS_USED_POST);
1626 session::set('LOCK_VARS_USED_REQUEST' , $LOCK_VARS_USED_REQUEST);
1627 }
1629 /* Prepare and show template */
1630 $smarty= get_smarty();
1631 $smarty->assign("allow_readonly",$allow_readonly);
1632 $msg= msgPool::buildList($dn);
1634 $smarty->assign ("dn", $msg);
1635 if ($remove){
1636 $smarty->assign ("action", _("Continue anyway"));
1637 } else {
1638 $smarty->assign ("action", _("Edit anyway"));
1639 }
1641 $smarty->assign ("message", _("These entries are currently locked:"). $msg);
1643 return ($smarty->fetch (get_template_path('islocked.tpl')));
1644 }
1647 /*! \brief Return a string/HTML representation of an array
1648 *
1649 * This returns a string representation of a given value.
1650 * It can be used to dump arrays, where every value is printed
1651 * on its own line. The output is targetted at HTML output, it uses
1652 * '<br>' for line breaks. If the value is already a string its
1653 * returned unchanged.
1654 *
1655 * \param mixed 'value' Whatever needs to be printed.
1656 * \return string
1657 */
1658 function to_string ($value)
1659 {
1660 /* If this is an array, generate a text blob */
1661 if (is_array($value)){
1662 $ret= "";
1663 foreach ($value as $line){
1664 $ret.= $line."<br>\n";
1665 }
1666 return ($ret);
1667 } else {
1668 return ($value);
1669 }
1670 }
1673 /*! \brief Return a list of all printers in the current base
1674 *
1675 * Returns an array with the CNs of all printers (objects with
1676 * objectClass gotoPrinter) in the current base.
1677 * ($config->current['BASE']).
1678 *
1679 * Example:
1680 * \code
1681 * $this->printerList = get_printer_list();
1682 * \endcode
1683 *
1684 * \return array an array with the CNs of the printers as key and value.
1685 * */
1686 function get_printer_list()
1687 {
1688 global $config;
1689 $res = array();
1690 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1691 foreach($data as $attrs ){
1692 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1693 }
1694 return $res;
1695 }
1698 /*! \brief Function to rewrite some problematic characters
1699 *
1700 * This function takes a string and replaces all possibly characters in it
1701 * with less problematic characters, as defined in $REWRITE.
1702 *
1703 * \param string 's' the string to rewrite
1704 * \return string 's' the result of the rewrite
1705 * */
1706 function rewrite($s)
1707 {
1708 global $REWRITE;
1710 foreach ($REWRITE as $key => $val){
1711 $s= str_replace("$key", "$val", $s);
1712 }
1714 return ($s);
1715 }
1718 /*! \brief Return the base of a given DN
1719 *
1720 * \param string 'dn' a DN
1721 * */
1722 function dn2base($dn)
1723 {
1724 global $config;
1726 if (get_people_ou() != ""){
1727 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1728 }
1729 if (get_groups_ou() != ""){
1730 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1731 }
1732 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1734 return ($base);
1735 }
1738 /*! \brief Check if a given command exists and is executable
1739 *
1740 * Test if a given cmdline contains an executable command. Strips
1741 * arguments from the given cmdline.
1742 *
1743 * \param string 'cmdline' the cmdline to check
1744 * \return TRUE if command exists and is executable, otherwise FALSE.
1745 * */
1746 function check_command($cmdline)
1747 {
1748 $cmd= preg_replace("/ .*$/", "", $cmdline);
1750 /* Check if command exists in filesystem */
1751 if (!file_exists($cmd)){
1752 return (FALSE);
1753 }
1755 /* Check if command is executable */
1756 if (!is_executable($cmd)){
1757 return (FALSE);
1758 }
1760 return (TRUE);
1761 }
1764 /*! \brief Print plugin HTML header
1765 *
1766 * \param string 'image' the path of the image to be used next to the headline
1767 * \param string 'image' the headline
1768 * \param string 'info' additional information to print
1769 */
1770 function print_header($image, $headline, $info= "")
1771 {
1772 $display= "<div class=\"plugtop\">\n";
1773 $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";
1774 $display.= "</div>\n";
1776 if ($info != ""){
1777 $display.= "<div class=\"pluginfo\">\n";
1778 $display.= "$info";
1779 $display.= "</div>\n";
1780 } else {
1781 $display.= "<div style=\"height:5px;\">\n";
1782 $display.= " ";
1783 $display.= "</div>\n";
1784 }
1785 return ($display);
1786 }
1789 /*! \brief Print page number selector for paged lists
1790 *
1791 * \param int 'dcnt' Number of entries
1792 * \param int 'start' Page to start
1793 * \param int 'range' Number of entries per page
1794 * \param string 'post_var' POST variable to check for range
1795 */
1796 function range_selector($dcnt,$start,$range=25,$post_var=false)
1797 {
1799 /* Entries shown left and right from the selected entry */
1800 $max_entries= 10;
1802 /* Initialize and take care that max_entries is even */
1803 $output="";
1804 if ($max_entries & 1){
1805 $max_entries++;
1806 }
1808 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1809 $range= $_POST[$post_var];
1810 }
1812 /* Prevent output to start or end out of range */
1813 if ($start < 0 ){
1814 $start= 0 ;
1815 }
1816 if ($start >= $dcnt){
1817 $start= $range * (int)(($dcnt / $range) + 0.5);
1818 }
1820 $numpages= (($dcnt / $range));
1821 if(((int)($numpages))!=($numpages)){
1822 $numpages = (int)$numpages + 1;
1823 }
1824 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1825 return ("");
1826 }
1827 $ppage= (int)(($start / $range) + 0.5);
1830 /* Align selected page to +/- max_entries/2 */
1831 $begin= $ppage - $max_entries/2;
1832 $end= $ppage + $max_entries/2;
1834 /* Adjust begin/end, so that the selected value is somewhere in
1835 the middle and the size is max_entries if possible */
1836 if ($begin < 0){
1837 $end-= $begin + 1;
1838 $begin= 0;
1839 }
1840 if ($end > $numpages) {
1841 $end= $numpages;
1842 }
1843 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1844 $begin= $end - $max_entries;
1845 }
1847 if($post_var){
1848 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1849 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1850 }else{
1851 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1852 }
1854 /* Draw decrement */
1855 if ($start > 0 ) {
1856 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1857 (($start-$range))."\">".
1858 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1859 }
1861 /* Draw pages */
1862 for ($i= $begin; $i < $end; $i++) {
1863 if ($ppage == $i){
1864 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1865 validate($_GET['plug'])."&start=".
1866 ($i*$range)."\"> ".($i+1)." </a>";
1867 } else {
1868 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1869 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1870 }
1871 }
1873 /* Draw increment */
1874 if($start < ($dcnt-$range)) {
1875 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1876 (($start+($range)))."\">".
1877 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1878 }
1880 if(($post_var)&&($numpages)){
1881 $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()'>";
1882 foreach(array(20,50,100,200,"all") as $num){
1883 if($num == "all"){
1884 $var = 10000;
1885 }else{
1886 $var = $num;
1887 }
1888 if($var == $range){
1889 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1890 }else{
1891 $output.="\n<option value='".$var."'>".$num."</option>";
1892 }
1893 }
1894 $output.= "</select></td></tr></table></div>";
1895 }else{
1896 $output.= "</div>";
1897 }
1899 return($output);
1900 }
1903 /*! \brief Generate HTML for the 'Apply filter' button */
1904 function apply_filter()
1905 {
1906 $apply= "";
1908 $apply= ''.
1909 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1910 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1912 return ($apply);
1913 }
1916 /*! \brief Generate HTML for the 'Back' button */
1917 function back_to_main()
1918 {
1919 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1920 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1922 return ($string);
1923 }
1926 /*! \brief Put netmask in n.n.n.n format
1927 * \param string 'netmask' The netmask
1928 * \return string Converted netmask
1929 */
1930 function normalize_netmask($netmask)
1931 {
1932 /* Check for notation of netmask */
1933 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1934 $num= (int)($netmask);
1935 $netmask= "";
1937 for ($byte= 0; $byte<4; $byte++){
1938 $result=0;
1940 for ($i= 7; $i>=0; $i--){
1941 if ($num-- > 0){
1942 $result+= pow(2,$i);
1943 }
1944 }
1946 $netmask.= $result.".";
1947 }
1949 return (preg_replace('/\.$/', '', $netmask));
1950 }
1952 return ($netmask);
1953 }
1956 /*! \brief Return the number of set bits in the netmask
1957 *
1958 * For a given subnetmask (for example 255.255.255.0) this returns
1959 * the number of set bits.
1960 *
1961 * Example:
1962 * \code
1963 * $bits = netmask_to_bits('255.255.255.0') # Returns 24
1964 * $bits = netmask_to_bits('255.255.254.0') # Returns 23
1965 * \endcode
1966 *
1967 * Be aware of the fact that the function does not check
1968 * if the given subnet mask is actually valid. For example:
1969 * Bad examples:
1970 * \code
1971 * $bits = netmask_to_bits('255.0.0.255') # Returns 16
1972 * $bits = netmask_to_bits('255.255.0.255') # Returns 24
1973 * \endcode
1974 */
1975 function netmask_to_bits($netmask)
1976 {
1977 list($nm0, $nm1, $nm2, $nm3)= explode('.', $netmask);
1978 $res= 0;
1980 for ($n= 0; $n<4; $n++){
1981 $start= 255;
1982 $name= "nm$n";
1984 for ($i= 0; $i<8; $i++){
1985 if ($start == (int)($$name)){
1986 $res+= 8 - $i;
1987 break;
1988 }
1989 $start-= pow(2,$i);
1990 }
1991 }
1993 return ($res);
1994 }
1997 /*! \brief Recursion helper for gen_id() */
1998 function recurse($rule, $variables)
1999 {
2000 $result= array();
2002 if (!count($variables)){
2003 return array($rule);
2004 }
2006 reset($variables);
2007 $key= key($variables);
2008 $val= current($variables);
2009 unset ($variables[$key]);
2011 foreach($val as $possibility){
2012 $nrule= str_replace("{$key}", $possibility, $rule);
2013 $result= array_merge($result, recurse($nrule, $variables));
2014 }
2016 return ($result);
2017 }
2020 /*! \brief Expands user ID based on possible rules
2021 *
2022 * Unroll given rule string by filling in attributes.
2023 *
2024 * \param string 'rule' The rule string from gosa.conf.
2025 * \param array 'attributes' A dictionary of attribute/value mappings
2026 * \return string Expanded string, still containing the id keyword.
2027 */
2028 function expand_id($rule, $attributes)
2029 {
2030 /* Check for id rule */
2031 if(preg_match('/^id(:|#|!)\d+$/',$rule)){
2032 return (array("{$rule}"));
2033 }
2035 /* Check for clean attribute */
2036 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
2037 $rule= preg_replace('/^%/', '', $rule);
2038 $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
2039 return (array($val));
2040 }
2042 /* Check for attribute with parameters */
2043 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
2044 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
2045 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
2046 $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
2047 $start= preg_replace ('/-.*$/', '', $param);
2048 $stop = preg_replace ('/^[^-]+-/', '', $param);
2050 /* Assemble results */
2051 $result= array();
2052 for ($i= $start; $i<= $stop; $i++){
2053 $result[]= substr($val, 0, $i);
2054 }
2055 return ($result);
2056 }
2058 echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
2059 return (array($rule));
2060 }
2063 /*! \brief Generate a list of uid proposals based on a rule
2064 *
2065 * Unroll given rule string by filling in attributes and replacing
2066 * all keywords.
2067 *
2068 * \param string 'rule' The rule string from gosa.conf.
2069 * \param array 'attributes' A dictionary of attribute/value mappings
2070 * \return array List of valid not used uids
2071 */
2072 function gen_uids($rule, $attributes)
2073 {
2074 global $config;
2076 /* Search for keys and fill the variables array with all
2077 possible values for that key. */
2078 $part= "";
2079 $trigger= false;
2080 $stripped= "";
2081 $variables= array();
2083 for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
2085 if ($rule[$pos] == "{" ){
2086 $trigger= true;
2087 $part= "";
2088 continue;
2089 }
2091 if ($rule[$pos] == "}" ){
2092 $variables[$pos]= expand_id($part, $attributes);
2093 $stripped.= "{".$pos."}";
2094 $trigger= false;
2095 continue;
2096 }
2098 if ($trigger){
2099 $part.= $rule[$pos];
2100 } else {
2101 $stripped.= $rule[$pos];
2102 }
2103 }
2105 /* Recurse through all possible combinations */
2106 $proposed= recurse($stripped, $variables);
2108 /* Get list of used ID's */
2109 $ldap= $config->get_ldap_link();
2110 $ldap->cd($config->current['BASE']);
2112 /* Remove used uids and watch out for id tags */
2113 $ret= array();
2114 foreach($proposed as $uid){
2116 /* Check for id tag and modify uid if needed */
2117 if(preg_match('/\{id(:|!)\d+}/',$uid, $m)){
2118 $size= preg_replace('/^.*{id(:|!)(\d+)}.*$/', '\\2', $uid);
2120 $start= $m[1]==":"?0:-1;
2121 for ($i= $start, $p= pow(10,$size)-1; $i < $p; $i++){
2122 if ($i == -1) {
2123 $number= "";
2124 } else {
2125 $number= sprintf("%0".$size."d", $i+1);
2126 }
2127 $res= preg_replace('/{id(:|!)\d+}/', $number, $uid);
2129 $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
2130 if($ldap->count() == 0){
2131 $uid= $res;
2132 break;
2133 }
2134 }
2136 /* Remove link if nothing has been found */
2137 $uid= preg_replace('/{id(:|!)\d+}/', '', $uid);
2138 }
2140 if(preg_match('/\{id#\d+}/',$uid)){
2141 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
2143 while (true){
2144 mt_srand((double) microtime()*1000000);
2145 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
2146 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
2147 $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
2148 if($ldap->count() == 0){
2149 $uid= $res;
2150 break;
2151 }
2152 }
2154 /* Remove link if nothing has been found */
2155 $uid= preg_replace('/{id#\d+}/', '', $uid);
2156 }
2158 /* Don't assign used ones */
2159 $ldap->search("(uid=".preg_replace('/[{}]/', '', $uid).")",array('dn'));
2160 if($ldap->count() == 0){
2161 /* Add uid, but remove {} first. These are invalid anyway. */
2162 $ret[]= preg_replace('/[{}]/', '', $uid);
2163 }
2164 }
2166 return(array_unique($ret));
2167 }
2170 /*! \brief Convert various data sizes to bytes
2171 *
2172 * Given a certain value in the format n(g|m|k), where n
2173 * is a value and (g|m|k) stands for Gigabyte, Megabyte and Kilobyte
2174 * this function returns the byte value.
2175 *
2176 * \param string 'value' a value in the above specified format
2177 * \return a byte value or the original value if specified string is simply
2178 * a numeric value
2179 *
2180 */
2181 function to_byte($value) {
2182 $value= strtolower(trim($value));
2184 if(!is_numeric(substr($value, -1))) {
2186 switch(substr($value, -1)) {
2187 case 'g':
2188 $mult= 1073741824;
2189 break;
2190 case 'm':
2191 $mult= 1048576;
2192 break;
2193 case 'k':
2194 $mult= 1024;
2195 break;
2196 }
2198 return ($mult * (int)substr($value, 0, -1));
2199 } else {
2200 return $value;
2201 }
2202 }
2205 /*! \brief Check if a value exists in an array (case-insensitive)
2206 *
2207 * This is just as http://php.net/in_array except that the comparison
2208 * is case-insensitive.
2209 *
2210 * \param string 'value' needle
2211 * \param array 'items' haystack
2212 */
2213 function in_array_ics($value, $items)
2214 {
2215 return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
2216 }
2219 /*! \brief Removes malicious characters from a (POST) string. */
2220 function validate($string)
2221 {
2222 return (strip_tags(str_replace('\0', '', $string)));
2223 }
2226 /*! \brief Evaluate the current GOsa version from the build in revision string */
2227 function get_gosa_version()
2228 {
2229 global $svn_revision, $svn_path;
2231 /* Extract informations */
2232 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
2234 /* Release or development? */
2235 if (preg_match('%/gosa/trunk/%', $svn_path)){
2236 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
2237 } else {
2238 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
2239 return (sprintf(_("GOsa $release"), $revision));
2240 }
2241 }
2244 /*! \brief Recursively delete a path in the file system
2245 *
2246 * Will delete the given path and all its files recursively.
2247 * Can also follow links if told so.
2248 *
2249 * \param string 'path'
2250 * \param boolean 'followLinks' TRUE to follow links, FALSE (default)
2251 * for not following links
2252 */
2253 function rmdirRecursive($path, $followLinks=false) {
2254 $dir= opendir($path);
2255 while($entry= readdir($dir)) {
2256 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
2257 unlink($path."/".$entry);
2258 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
2259 rmdirRecursive($path."/".$entry);
2260 }
2261 }
2262 closedir($dir);
2263 return rmdir($path);
2264 }
2267 /*! \brief Get directory content information
2268 *
2269 * Returns the content of a directory as an array in an
2270 * ascended sorted manner.
2271 *
2272 * \param string 'path'
2273 * \param boolean weither to sort the content descending.
2274 */
2275 function scan_directory($path,$sort_desc=false)
2276 {
2277 $ret = false;
2279 /* is this a dir ? */
2280 if(is_dir($path)) {
2282 /* is this path a readable one */
2283 if(is_readable($path)){
2285 /* Get contents and write it into an array */
2286 $ret = array();
2288 $dir = opendir($path);
2290 /* Is this a correct result ?*/
2291 if($dir){
2292 while($fp = readdir($dir))
2293 $ret[]= $fp;
2294 }
2295 }
2296 }
2297 /* Sort array ascending , like scandir */
2298 sort($ret);
2300 /* Sort descending if parameter is sort_desc is set */
2301 if($sort_desc) {
2302 $ret = array_reverse($ret);
2303 }
2305 return($ret);
2306 }
2309 /*! \brief Clean the smarty compile dir */
2310 function clean_smarty_compile_dir($directory)
2311 {
2312 global $svn_revision;
2314 if(is_dir($directory) && is_readable($directory)) {
2315 // Set revision filename to REVISION
2316 $revision_file= $directory."/REVISION";
2318 /* Is there a stamp containing the current revision? */
2319 if(!file_exists($revision_file)) {
2320 // create revision file
2321 create_revision($revision_file, $svn_revision);
2322 } else {
2323 # check for "$config->...['CONFIG']/revision" and the
2324 # contents should match the revision number
2325 if(!compare_revision($revision_file, $svn_revision)){
2326 // If revision differs, clean compile directory
2327 foreach(scan_directory($directory) as $file) {
2328 if(($file==".")||($file=="..")) continue;
2329 if( is_file($directory."/".$file) &&
2330 is_writable($directory."/".$file)) {
2331 // delete file
2332 if(!unlink($directory."/".$file)) {
2333 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
2334 // This should never be reached
2335 }
2336 } elseif(is_dir($directory."/".$file) &&
2337 is_writable($directory."/".$file)) {
2338 // Just recursively delete it
2339 rmdirRecursive($directory."/".$file);
2340 }
2341 }
2342 // We should now create a fresh revision file
2343 clean_smarty_compile_dir($directory);
2344 } else {
2345 // Revision matches, nothing to do
2346 }
2347 }
2348 } else {
2349 // Smarty compile dir is not accessible
2350 // (Smarty will warn about this)
2351 }
2352 }
2355 function create_revision($revision_file, $revision)
2356 {
2357 $result= false;
2359 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2360 if($fh= fopen($revision_file, "w")) {
2361 if(fwrite($fh, $revision)) {
2362 $result= true;
2363 }
2364 }
2365 fclose($fh);
2366 } else {
2367 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2368 }
2370 return $result;
2371 }
2374 function compare_revision($revision_file, $revision)
2375 {
2376 // false means revision differs
2377 $result= false;
2379 if(file_exists($revision_file) && is_readable($revision_file)) {
2380 // Open file
2381 if($fh= fopen($revision_file, "r")) {
2382 // Compare File contents with current revision
2383 if($revision == fread($fh, filesize($revision_file))) {
2384 $result= true;
2385 }
2386 } else {
2387 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2388 }
2389 // Close file
2390 fclose($fh);
2391 }
2393 return $result;
2394 }
2397 /*! \brief Return HTML for a progressbar
2398 *
2399 * \code
2400 * $smarty->assign("installprogress", progressbar($current_progress_in_percent),100,15,true);
2401 * \endcode
2402 *
2403 * \param int 'percentage' Value to display
2404 * \param int 'width' width of the resulting output
2405 * \param int 'height' height of the resulting output
2406 * \param boolean 'showtext' weither to show the percentage in the progressbar or not
2407 * */
2408 function progressbar($percentage, $width= 200, $height= 14, $showText= false, $colorize= true, $id= "")
2409 {
2410 $text= "";
2411 $class= "";
2412 $style= "width:${width}px;height:${height}px;";
2414 // Fix percentage range
2415 $percentage= floor($percentage);
2416 if ($percentage > 100) {
2417 $percentage= 100;
2418 }
2419 if ($percentage < 0) {
2420 $percentage= 0;
2421 }
2423 // Only show text if we're above 10px height
2424 if ($showText && $height>10){
2425 $text= $percentage."%";
2426 }
2428 // Set font size
2429 $style.= "font-size:".($height-3)."px;";
2431 // Set color
2432 if ($colorize){
2433 if ($percentage < 70) {
2434 $class= " progress-low";
2435 } elseif ($percentage < 80) {
2436 $class= " progress-mid";
2437 } elseif ($percentage < 90) {
2438 $class= " progress-high";
2439 } else {
2440 $class= " progress-full";
2441 }
2442 }
2444 // Apply gradients
2445 $hoffset= floor($height / 2) + 4;
2446 $woffset= floor(($width+5) * (100-$percentage) / 100);
2447 foreach (array("-moz-box-shadow", "-webkit-box-shadow", "box-shadow") as $type) {
2448 $style.="$type:
2449 0 0 2px rgba(255, 255, 255, 0.4) inset,
2450 0 4px 6px rgba(255, 255, 255, 0.4) inset,
2451 0 ".$hoffset."px 0 -2px rgba(255, 255, 255, 0.2) inset,
2452 -".$woffset."px 0 0 -2px rgba(255, 255, 255, 0.2) inset,
2453 -".($woffset+1)."px 0 0 -2px rgba(0, 0, 0, 0.6) inset,
2454 0pt ".($hoffset+1)."px 8px rgba(0, 0, 0, 0.3) inset,
2455 0pt 1px 0px rgba(0, 0, 0, 0.2);";
2456 }
2458 // Set ID
2459 if ($id != ""){
2460 $id= "id='$id'";
2461 }
2463 return "<div class='progress$class' $id style='$style'>$text</div>";
2464 }
2467 /*! \brief Lookup a key in an array case-insensitive
2468 *
2469 * Given an associative array this can lookup the value of
2470 * a certain key, regardless of the case.
2471 *
2472 * \code
2473 * $items = array ('FOO' => 'blub', 'bar' => 'blub');
2474 * array_key_ics('foo', $items); # Returns 'blub'
2475 * array_key_ics('BAR', $items); # Returns 'blub'
2476 * \endcode
2477 *
2478 * \param string 'key' needle
2479 * \param array 'items' haystack
2480 */
2481 function array_key_ics($ikey, $items)
2482 {
2483 $tmp= array_change_key_case($items, CASE_LOWER);
2484 $ikey= strtolower($ikey);
2485 if (isset($tmp[$ikey])){
2486 return($tmp[$ikey]);
2487 }
2489 return ('');
2490 }
2493 /*! \brief Determine if two arrays are different
2494 *
2495 * \param array 'src'
2496 * \param array 'dst'
2497 * \return boolean TRUE or FALSE
2498 * */
2499 function array_differs($src, $dst)
2500 {
2501 /* If the count is differing, the arrays differ */
2502 if (count ($src) != count ($dst)){
2503 return (TRUE);
2504 }
2506 return (count(array_diff($src, $dst)) != 0);
2507 }
2510 function saveFilter($a_filter, $values)
2511 {
2512 if (isset($_POST['regexit'])){
2513 $a_filter["regex"]= $_POST['regexit'];
2515 foreach($values as $type){
2516 if (isset($_POST[$type])) {
2517 $a_filter[$type]= "checked";
2518 } else {
2519 $a_filter[$type]= "";
2520 }
2521 }
2522 }
2524 /* React on alphabet links if needed */
2525 if (isset($_GET['search'])){
2526 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2527 if ($s == "**"){
2528 $s= "*";
2529 }
2530 $a_filter['regex']= $s;
2531 }
2533 return ($a_filter);
2534 }
2537 /*! \brief Escape all LDAP filter relevant characters */
2538 function normalizeLdap($input)
2539 {
2540 return (addcslashes($input, '()|'));
2541 }
2544 /*! \brief Return the gosa base directory */
2545 function get_base_dir()
2546 {
2547 global $BASE_DIR;
2549 return $BASE_DIR;
2550 }
2553 /*! \brief Test weither we are allowed to read the object */
2554 function obj_is_readable($dn, $object, $attribute)
2555 {
2556 global $ui;
2558 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2559 }
2562 /*! \brief Test weither we are allowed to change the object */
2563 function obj_is_writable($dn, $object, $attribute)
2564 {
2565 global $ui;
2567 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2568 }
2571 /*! \brief Explode a DN into its parts
2572 *
2573 * Similar to explode (http://php.net/explode), but a bit more specific
2574 * for the needs when splitting, exploding LDAP DNs.
2575 *
2576 * \param string 'dn' the DN to split
2577 * \param config-object a config object. only neeeded if DN shall be verified in the LDAP
2578 * \param boolean verify_in_ldap check weither DN is valid
2579 *
2580 */
2581 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2582 {
2583 /* Initialize variables */
2584 $ret = array("count" => 0); // Set count to 0
2585 $next = true; // if false, then skip next loops and return
2586 $cnt = 0; // Current number of loops
2587 $max = 100; // Just for security, prevent looops
2588 $ldap = NULL; // To check if created result a valid
2589 $keep = ""; // save last failed parse string
2591 /* Check each parsed dn in ldap ? */
2592 if($config!==NULL && $verify_in_ldap){
2593 $ldap = $config->get_ldap_link();
2594 }
2596 /* Lets start */
2597 $called = false;
2598 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2600 $cnt ++;
2601 if(!preg_match("/,/",$dn)){
2602 $next = false;
2603 }
2604 $object = preg_replace("/[,].*$/","",$dn);
2605 $dn = preg_replace("/^[^,]+,/","",$dn);
2607 $called = true;
2609 /* Check if current dn is valid */
2610 if($ldap!==NULL){
2611 $ldap->cd($dn);
2612 $ldap->cat($dn,array("dn"));
2613 if($ldap->count()){
2614 $ret[] = $keep.$object;
2615 $keep = "";
2616 }else{
2617 $keep .= $object.",";
2618 }
2619 }else{
2620 $ret[] = $keep.$object;
2621 $keep = "";
2622 }
2623 }
2625 /* No dn was posted */
2626 if($cnt == 0 && !empty($dn)){
2627 $ret[] = $dn;
2628 }
2630 /* Append the rest */
2631 $test = $keep.$dn;
2632 if($called && !empty($test)){
2633 $ret[] = $keep.$dn;
2634 }
2635 $ret['count'] = count($ret) - 1;
2637 return($ret);
2638 }
2641 function get_base_from_hook($dn, $attrib)
2642 {
2643 global $config;
2645 if ($config->get_cfg_value("baseIdHook") != ""){
2647 /* Call hook script - if present */
2648 $command= $config->get_cfg_value("baseIdHook");
2650 if ($command != ""){
2651 $command.= " '".LDAP::fix($dn)."' $attrib";
2652 if (check_command($command)){
2653 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2654 exec($command, $output);
2655 if (preg_match("/^[0-9]+$/", $output[0])){
2656 return ($output[0]);
2657 } else {
2658 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2659 return ($config->get_cfg_value("uidNumberBase"));
2660 }
2661 } else {
2662 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2663 return ($config->get_cfg_value("uidNumberBase"));
2664 }
2666 } else {
2668 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2669 return ($config->get_cfg_value("uidNumberBase"));
2671 }
2672 }
2673 }
2676 /*! \brief Check if schema version matches the requirements */
2677 function check_schema_version($class, $version)
2678 {
2679 return preg_match("/\(v$version\)/", $class['DESC']);
2680 }
2683 /*! \brief Check if LDAP schema matches the requirements */
2684 function check_schema($cfg,$rfc2307bis = FALSE)
2685 {
2686 $messages= array();
2688 /* Get objectclasses */
2689 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2690 $objectclasses = $ldap->get_objectclasses();
2691 if(count($objectclasses) == 0){
2692 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2693 }
2695 /* This is the default block used for each entry.
2696 * to avoid unset indexes.
2697 */
2698 $def_check = array("REQUIRED_VERSION" => "0",
2699 "SCHEMA_FILES" => array(),
2700 "CLASSES_REQUIRED" => array(),
2701 "STATUS" => FALSE,
2702 "IS_MUST_HAVE" => FALSE,
2703 "MSG" => "",
2704 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2706 /* The gosa base schema */
2707 $checks['gosaObject'] = $def_check;
2708 $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2709 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa-samba3.schema","gosa-samba2.schema");
2710 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2711 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2713 /* GOsa Account class */
2714 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.6";
2715 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa-samba3.schema","gosa-samba2.schema");
2716 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2717 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2718 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2720 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2721 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2722 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa-samba3.schema","gosa-samba2.schema");
2723 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2724 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2725 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2727 /* Some other checks */
2728 foreach(array(
2729 "gosaCacheEntry" => array("version" => "2.6.1", "class" => "gosaAccount"),
2730 "gosaDepartment" => array("version" => "2.6.1", "class" => "gosaAccount"),
2731 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2732 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2733 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2734 "gosaUserTemplate" => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2735 "gosaMailAccount" => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa-samba3.schema"),
2736 "gosaProxyAccount" => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa-samba3.schema"),
2737 "gosaApplication" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2738 "gosaApplicationGroup" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2739 "GOhard" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2740 "gotoTerminal" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2741 "goServer" => array("version" => "2.6.1", "class" => "server","file" => "goserver.schema"),
2742 "goTerminalServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2743 "goShareServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2744 "goNtpServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2745 "goSyslogServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2746 "goLdapServer" => array("version" => "2.6.1", "class" => "goServer"),
2747 "goCupsServer" => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2748 "goImapServer" => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa-samba3.schema"),
2749 "goKrbServer" => array("version" => "2.6.1", "class" => "goServer"),
2750 "goFaxServer" => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2751 ) as $name => $values){
2753 $checks[$name] = $def_check;
2754 if(isset($values['version'])){
2755 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2756 }
2757 if(isset($values['file'])){
2758 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2759 }
2760 if (isset($values['class'])) {
2761 $checks[$name]["CLASSES_REQUIRED"] = is_array($values['class'])?$values['class']:array($values['class']);
2762 }
2763 }
2764 foreach($checks as $name => $value){
2765 foreach($value['CLASSES_REQUIRED'] as $class){
2767 if(!isset($objectclasses[$name])){
2768 if($value['IS_MUST_HAVE']){
2769 $checks[$name]['STATUS'] = FALSE;
2770 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2771 } else {
2772 $checks[$name]['STATUS'] = TRUE;
2773 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2774 }
2775 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2776 $checks[$name]['STATUS'] = FALSE;
2778 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2779 }else{
2780 $checks[$name]['STATUS'] = TRUE;
2781 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2782 }
2783 }
2784 }
2786 $tmp = $objectclasses;
2788 /* The gosa base schema */
2789 $checks['posixGroup'] = $def_check;
2790 $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2791 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa-samba3.schema","gosa-samba2.schema");
2792 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2793 $checks['posixGroup']['STATUS'] = TRUE;
2794 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2795 $checks['posixGroup']['MSG'] = "";
2796 $checks['posixGroup']['INFO'] = "";
2798 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2799 if(isset($tmp['posixGroup'])){
2801 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2802 $checks['posixGroup']['STATUS'] = FALSE;
2803 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2804 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2805 }
2806 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2807 $checks['posixGroup']['STATUS'] = FALSE;
2808 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2809 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2810 }
2811 }
2813 return($checks);
2814 }
2817 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2818 {
2819 $tmp = array(
2820 "de_DE" => "German",
2821 "fr_FR" => "French",
2822 "it_IT" => "Italian",
2823 "es_ES" => "Spanish",
2824 "en_US" => "English",
2825 "nl_NL" => "Dutch",
2826 "pl_PL" => "Polish",
2827 "pt_BR" => "Brazilian Portuguese",
2828 #"sv_SE" => "Swedish",
2829 "zh_CN" => "Chinese",
2830 "vi_VN" => "Vietnamese",
2831 "ru_RU" => "Russian");
2833 $tmp2= array(
2834 "de_DE" => _("German"),
2835 "fr_FR" => _("French"),
2836 "it_IT" => _("Italian"),
2837 "es_ES" => _("Spanish"),
2838 "en_US" => _("English"),
2839 "nl_NL" => _("Dutch"),
2840 "pl_PL" => _("Polish"),
2841 "pt_BR" => _("Brazilian Portuguese"),
2842 #"sv_SE" => _("Swedish"),
2843 "zh_CN" => _("Chinese"),
2844 "vi_VN" => _("Vietnamese"),
2845 "ru_RU" => _("Russian"));
2847 $ret = array();
2848 if($languages_in_own_language){
2850 $old_lang = setlocale(LC_ALL, 0);
2852 /* If the locale wasn't correclty set before, there may be an incorrect
2853 locale returned. Something like this:
2854 C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2855 Extract the locale name from this string and use it to restore old locale.
2856 */
2857 if(preg_match("/LC_CTYPE/",$old_lang)){
2858 $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2859 }
2861 foreach($tmp as $key => $name){
2862 $lang = $key.".UTF-8";
2863 setlocale(LC_ALL, $lang);
2864 if($strip_region_tag){
2865 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2866 }else{
2867 $ret[$key] = _($name)." (".$tmp2[$key].")";
2868 }
2869 }
2870 setlocale(LC_ALL, $old_lang);
2871 }else{
2872 foreach($tmp as $key => $name){
2873 if($strip_region_tag){
2874 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2875 }else{
2876 $ret[$key] = _($name);
2877 }
2878 }
2879 }
2880 return($ret);
2881 }
2884 /*! \brief Returns contents of the given POST variable and check magic quotes settings
2885 *
2886 * Depending on the magic quotes settings this returns a stripclashed'ed version of
2887 * a certain POST variable.
2888 *
2889 * \param string 'name' the POST var to return ($_POST[$name])
2890 * \return string
2891 * */
2892 function get_post($name)
2893 {
2894 if(!isset($_POST[$name])){
2895 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2896 return(FALSE);
2897 }
2899 if(get_magic_quotes_gpc()){
2900 return(stripcslashes(validate($_POST[$name])));
2901 }else{
2902 return(validate($_POST[$name]));
2903 }
2904 }
2907 /*! \brief Return class name in correct case */
2908 function get_correct_class_name($cls)
2909 {
2910 global $class_mapping;
2911 if(isset($class_mapping) && is_array($class_mapping)){
2912 foreach($class_mapping as $class => $file){
2913 if(preg_match("/^".$cls."$/i",$class)){
2914 return($class);
2915 }
2916 }
2917 }
2918 return(FALSE);
2919 }
2922 /*! \brief Change the password of a given DN
2923 *
2924 * Change the password of a given DN with the specified hash.
2925 *
2926 * \param string 'dn' the DN whose password shall be changed
2927 * \param string 'password' the password
2928 * \param int mode
2929 * \param string 'hash' which hash to use to encrypt it, default is empty
2930 * for cleartext storage.
2931 * \return boolean TRUE on success FALSE on error
2932 */
2933 function change_password ($dn, $password, $mode=0, $hash= "")
2934 {
2935 global $config;
2936 $newpass= "";
2938 /* Convert to lower. Methods are lowercase */
2939 $hash= strtolower($hash);
2941 // Get all available encryption Methods
2943 // NON STATIC CALL :)
2944 $methods = new passwordMethod(session::get('config'),$dn);
2945 $available = $methods->get_available_methods();
2947 // read current password entry for $dn, to detect the encryption Method
2948 $ldap = $config->get_ldap_link();
2949 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2950 $attrs = $ldap->fetch ();
2952 /* Is ensure that clear passwords will stay clear */
2953 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2954 $hash = "clear";
2955 }
2957 // Detect the encryption Method
2958 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2960 /* Check for supported algorithm */
2961 mt_srand((double) microtime()*1000000);
2963 /* Extract used hash */
2964 if ($hash == ""){
2965 $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2966 } else {
2967 $test = new $available[$hash]($config,$dn);
2968 $test->set_hash($hash);
2969 }
2971 } else {
2972 // User MD5 by default
2973 $hash= "md5";
2974 $test = new $available['md5']($config, $dn);
2975 }
2977 if($test instanceOf passwordMethod){
2979 $deactivated = $test->is_locked($config,$dn);
2981 /* Feed password backends with information */
2982 $test->dn= $dn;
2983 $test->attrs= $attrs;
2984 $newpass= $test->generate_hash($password);
2986 // Update shadow timestamp?
2987 if (isset($attrs["shadowLastChange"][0])){
2988 $shadow= (int)(date("U") / 86400);
2989 } else {
2990 $shadow= 0;
2991 }
2993 // Write back modified entry
2994 $ldap->cd($dn);
2995 $attrs= array();
2997 // Not for groups
2998 if ($mode == 0){
2999 // Create SMB Password
3000 $attrs= generate_smb_nt_hash($password);
3002 if ($shadow != 0){
3003 $attrs['shadowLastChange']= $shadow;
3004 }
3005 }
3007 $attrs['userPassword']= array();
3008 $attrs['userPassword']= $newpass;
3010 $ldap->modify($attrs);
3012 /* Read ! if user was deactivated */
3013 if($deactivated){
3014 $test->lock_account($config,$dn);
3015 }
3017 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
3019 if (!$ldap->success()) {
3020 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
3021 } else {
3023 /* Run backend method for change/create */
3024 if(!$test->set_password($password)){
3025 return(FALSE);
3026 }
3028 /* Find postmodify entries for this class */
3029 $command= $config->search("password", "POSTMODIFY",array('menu'));
3031 if ($command != ""){
3032 /* Walk through attribute list */
3033 $command= preg_replace("/%userPassword/", $password, $command);
3034 $command= preg_replace("/%dn/", $dn, $command);
3036 if (check_command($command)){
3037 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
3038 exec($command);
3039 } else {
3040 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
3041 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
3042 }
3043 }
3044 }
3045 return(TRUE);
3046 }
3047 }
3050 /*! \brief Generate samba hashes
3051 *
3052 * Given a certain password this constructs an array like
3053 * array['sambaLMPassword'] etc.
3054 *
3055 * \param string 'password'
3056 * \return array contains several keys for lmPassword, ntPassword, pwdLastSet, etc. depending
3057 * on the samba version
3058 */
3059 function generate_smb_nt_hash($password)
3060 {
3061 global $config;
3063 # Try to use gosa-si?
3064 if ($config->get_cfg_value("gosaSupportURI") != ""){
3065 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
3066 if (isset($res['XML']['HASH'])){
3067 $hash= $res['XML']['HASH'];
3068 } else {
3069 $hash= "";
3070 }
3072 if ($hash == "") {
3073 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
3074 return ("");
3075 }
3076 } else {
3077 $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
3078 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
3080 exec($tmp, $ar);
3081 flush();
3082 reset($ar);
3083 $hash= current($ar);
3085 if ($hash == "") {
3086 msg_dialog::display(_("Configuration error"), sprintf(_("Cannot generate samba hash: running '%s' failed, check the 'sambaHashHook'!"),$config->get_cfg_value('sambaHashHook')), ERROR_DIALOG);
3087 return ("");
3088 }
3089 }
3091 list($lm,$nt)= explode(":", trim($hash));
3093 $attrs['sambaLMPassword']= $lm;
3094 $attrs['sambaNTPassword']= $nt;
3095 $attrs['sambaPwdLastSet']= date('U');
3096 $attrs['sambaBadPasswordCount']= "0";
3097 $attrs['sambaBadPasswordTime']= "0";
3098 return($attrs);
3099 }
3102 /*! \brief Get the Change Sequence Number of a certain DN
3103 *
3104 * To verify if a given object has been changed outside of Gosa
3105 * in the meanwhile, this function can be used to get the entryCSN
3106 * from the LDAP directory. It uses the attribute as configured
3107 * in modificationDetectionAttribute
3108 *
3109 * \param string 'dn'
3110 * \return either the result or "" in any other case
3111 */
3112 function getEntryCSN($dn)
3113 {
3114 global $config;
3115 if(empty($dn) || !is_object($config)){
3116 return("");
3117 }
3119 /* Get attribute that we should use as serial number */
3120 $attr= $config->get_cfg_value("modificationDetectionAttribute");
3121 if($attr != ""){
3122 $ldap = $config->get_ldap_link();
3123 $ldap->cat($dn,array($attr));
3124 $csn = $ldap->fetch();
3125 if(isset($csn[$attr][0])){
3126 return($csn[$attr][0]);
3127 }
3128 }
3129 return("");
3130 }
3133 /*! \brief Add (a) given objectClass(es) to an attrs entry
3134 *
3135 * The function adds the specified objectClass(es) to the given
3136 * attrs entry.
3137 *
3138 * \param mixed 'classes' Either a single objectClass or several objectClasses
3139 * as an array
3140 * \param array 'attrs' The attrs array to be modified.
3141 *
3142 * */
3143 function add_objectClass($classes, &$attrs)
3144 {
3145 if (is_array($classes)){
3146 $list= $classes;
3147 } else {
3148 $list= array($classes);
3149 }
3151 foreach ($list as $class){
3152 $attrs['objectClass'][]= $class;
3153 }
3154 }
3157 /*! \brief Removes a given objectClass from the attrs entry
3158 *
3159 * Similar to add_objectClass, except that it removes the given
3160 * objectClasses. See it for the params.
3161 * */
3162 function remove_objectClass($classes, &$attrs)
3163 {
3164 if (isset($attrs['objectClass'])){
3165 /* Array? */
3166 if (is_array($classes)){
3167 $list= $classes;
3168 } else {
3169 $list= array($classes);
3170 }
3172 $tmp= array();
3173 foreach ($attrs['objectClass'] as $oc) {
3174 foreach ($list as $class){
3175 if (strtolower($oc) != strtolower($class)){
3176 $tmp[]= $oc;
3177 }
3178 }
3179 }
3180 $attrs['objectClass']= $tmp;
3181 }
3182 }
3185 /*! \brief Initialize a file download with given content, name and data type.
3186 * \param string data The content to send.
3187 * \param string name The name of the file.
3188 * \param string type The content identifier, default value is "application/octet-stream";
3189 */
3190 function send_binary_content($data,$name,$type = "application/octet-stream")
3191 {
3192 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
3193 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
3194 header("Cache-Control: no-cache");
3195 header("Pragma: no-cache");
3196 header("Cache-Control: post-check=0, pre-check=0");
3197 header("Content-type: ".$type."");
3199 $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
3201 /* Strip name if it is a complete path */
3202 if (preg_match ("/\//", $name)) {
3203 $name= basename($name);
3204 }
3206 /* force download dialog */
3207 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
3208 header('Content-Disposition: filename="'.$name.'"');
3209 } else {
3210 header('Content-Disposition: attachment; filename="'.$name.'"');
3211 }
3213 echo $data;
3214 exit();
3215 }
3218 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
3219 {
3220 if(is_string($str)){
3221 return(htmlentities($str,$type,$charset));
3222 }elseif(is_array($str)){
3223 foreach($str as $name => $value){
3224 $str[$name] = reverse_html_entities($value,$type,$charset);
3225 }
3226 }
3227 return($str);
3228 }
3231 /*! \brief Encode special string characters so we can use the string in \
3232 HTML output, without breaking quotes.
3233 \param string The String we want to encode.
3234 \return string The encoded String
3235 */
3236 function xmlentities($str)
3237 {
3238 if(is_string($str)){
3240 static $asc2uni= array();
3241 if (!count($asc2uni)){
3242 for($i=128;$i<256;$i++){
3243 # $asc2uni[chr($i)] = "&#x".dechex($i).";";
3244 }
3245 }
3247 $str = str_replace("&", "&", $str);
3248 $str = str_replace("<", "<", $str);
3249 $str = str_replace(">", ">", $str);
3250 $str = str_replace("'", "'", $str);
3251 $str = str_replace("\"", """, $str);
3252 $str = str_replace("\r", "", $str);
3253 $str = strtr($str,$asc2uni);
3254 return $str;
3255 }elseif(is_array($str)){
3256 foreach($str as $name => $value){
3257 $str[$name] = xmlentities($value);
3258 }
3259 }
3260 return($str);
3261 }
3264 /*! \brief Updates all accessTo attributes from a given value to a new one.
3265 For example if a host is renamed.
3266 \param String $from The source accessTo name.
3267 \param String $to The destination accessTo name.
3268 */
3269 function update_accessTo($from,$to)
3270 {
3271 global $config;
3272 $ldap = $config->get_ldap_link();
3273 $ldap->cd($config->current['BASE']);
3274 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
3275 while($attrs = $ldap->fetch()){
3276 $new_attrs = array("accessTo" => array());
3277 $dn = $attrs['dn'];
3278 for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
3279 $new_attrs['objectClass'][] = $attrs['objectClass'][$i];
3280 }
3281 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
3282 if($attrs['accessTo'][$i] == $from){
3283 if(!empty($to)){
3284 $new_attrs['accessTo'][] = $to;
3285 }
3286 }else{
3287 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
3288 }
3289 }
3290 $ldap->cd($dn);
3291 $ldap->modify($new_attrs);
3292 if (!$ldap->success()){
3293 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
3294 }
3295 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
3296 }
3297 }
3300 /*! \brief Returns a random char */
3301 function get_random_char () {
3302 $randno = rand (0, 63);
3303 if ($randno < 12) {
3304 return (chr ($randno + 46)); // Digits, '/' and '.'
3305 } else if ($randno < 38) {
3306 return (chr ($randno + 53)); // Uppercase
3307 } else {
3308 return (chr ($randno + 59)); // Lowercase
3309 }
3310 }
3313 function cred_encrypt($input, $password) {
3315 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3316 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3318 return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
3320 }
3323 function cred_decrypt($input,$password) {
3324 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3325 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3327 return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
3328 }
3331 function get_object_info()
3332 {
3333 return(session::get('objectinfo'));
3334 }
3337 function set_object_info($str = "")
3338 {
3339 session::set('objectinfo',$str);
3340 }
3343 function isIpInNet($ip, $net, $mask) {
3344 // Move to long ints
3345 $ip= ip2long($ip);
3346 $net= ip2long($net);
3347 $mask= ip2long($mask);
3349 // Mask given IP with mask. If it returns "net", we're in...
3350 $res= $ip & $mask;
3352 return ($res == $net);
3353 }
3356 function get_next_id($attrib, $dn)
3357 {
3358 global $config;
3360 switch ($config->get_cfg_value("idAllocationMethod", "traditional")){
3361 case "pool":
3362 return get_next_id_pool($attrib);
3363 case "traditional":
3364 return get_next_id_traditional($attrib, $dn);
3365 }
3367 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("unknown idAllocation method!"), ERROR_DIALOG);
3368 return null;
3369 }
3372 function get_next_id_pool($attrib) {
3373 global $config;
3375 /* Fill informational values */
3376 $min= $config->get_cfg_value("${attrib}PoolMin", 10000);
3377 $max= $config->get_cfg_value("${attrib}PoolMax", 40000);
3379 /* Sanity check */
3380 if ($min >= $max) {
3381 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." ".sprintf(_("%sPoolMin >= %sPoolMax!"), $attrib), ERROR_DIALOG);
3382 return null;
3383 }
3385 /* ID to skip */
3386 $ldap= $config->get_ldap_link();
3387 $id= null;
3389 /* Try to allocate the ID several times before failing */
3390 $tries= 3;
3391 while ($tries--) {
3393 /* Look for ID map entry */
3394 $ldap->cd ($config->current['BASE']);
3395 $ldap->search ("(&(objectClass=sambaUnixIdPool)($attrib=*))", array("$attrib"));
3397 /* If it does not exist, create one with these defaults */
3398 if ($ldap->count() == 0) {
3399 /* Fill informational values */
3400 $minUserId= $config->get_cfg_value("uidPoolMin", 10000);
3401 $minGroupId= $config->get_cfg_value("gidPoolMin", 10000);
3403 /* Add as default */
3404 $attrs= array("objectClass" => array("organizationalUnit", "sambaUnixIdPool"));
3405 $attrs["ou"]= "idmap";
3406 $attrs["uidNumber"]= $minUserId;
3407 $attrs["gidNumber"]= $minGroupId;
3408 $ldap->cd("ou=idmap,".$config->current['BASE']);
3409 $ldap->add($attrs);
3410 if ($ldap->error != "Success") {
3411 msg_dialog::display(_("Error"), _("Cannot create sambaUnixIdPool entry!"), ERROR_DIALOG);
3412 return null;
3413 }
3414 $tries++;
3415 continue;
3416 }
3417 /* Bail out if it's not unique */
3418 if ($ldap->count() != 1) {
3419 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("sambaUnixIdPool is not unique!"), ERROR_DIALOG);
3420 return null;
3421 }
3423 /* Store old attrib and generate new */
3424 $attrs= $ldap->fetch();
3425 $dn= $ldap->getDN();
3426 $oldAttr= $attrs[$attrib][0];
3427 $newAttr= $oldAttr + 1;
3429 /* Sanity check */
3430 if ($newAttr >= $max) {
3431 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("no ID available!"), ERROR_DIALOG);
3432 return null;
3433 }
3434 if ($newAttr < $min) {
3435 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("no ID available!"), ERROR_DIALOG);
3436 return null;
3437 }
3439 #FIXME: PHP is not able to do a modification of "del: .../add: ...", so this
3440 # is completely unsafe in the moment.
3441 #/* Remove old attr, add new attr */
3442 #$attrs= array($attrib => $oldAttr);
3443 #$ldap->rm($attrs, $dn);
3444 #if ($ldap->error != "Success") {
3445 # continue;
3446 #}
3447 $ldap->cd($dn);
3448 $ldap->modify(array($attrib => $newAttr));
3449 if ($ldap->error != "Success") {
3450 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." ".$ldap->get_error(), ERROR_DIALOG);
3451 return null;
3452 } else {
3453 return $oldAttr;
3454 }
3455 }
3457 /* Bail out if we had problems getting the next id */
3458 if (!$tries) {
3459 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("maximum tries exceeded!"), ERROR_DIALOG);
3460 }
3462 return $id;
3463 }
3466 function get_next_id_traditional($attrib, $dn)
3467 {
3468 global $config;
3470 $ids= array();
3471 $ldap= $config->get_ldap_link();
3473 $ldap->cd ($config->current['BASE']);
3474 if (preg_match('/gidNumber/i', $attrib)){
3475 $oc= "posixGroup";
3476 } else {
3477 $oc= "posixAccount";
3478 }
3479 $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
3481 /* Get list of ids */
3482 while ($attrs= $ldap->fetch()){
3483 $ids[]= (int)$attrs["$attrib"][0];
3484 }
3486 /* Add the nobody id */
3487 $ids[]= 65534;
3489 /* get the ranges */
3490 $tmp = array('0'=> 1000);
3491 if (preg_match('/posixAccount/', $oc) && $config->get_cfg_value("uidNumberBase") != ""){
3492 $tmp= explode('-',$config->get_cfg_value("uidNumberBase"));
3493 } elseif($config->get_cfg_value("gidNumberBase") != ""){
3494 $tmp= explode('-',$config->get_cfg_value("gidNumberBase"));
3495 }
3497 /* Set hwm to max if not set - for backward compatibility */
3498 $lwm= $tmp[0];
3499 if (isset($tmp[1])){
3500 $hwm= $tmp[1];
3501 } else {
3502 $hwm= pow(2,32);
3503 }
3504 /* Find out next free id near to UID_BASE */
3505 if ($config->get_cfg_value("baseIdHook") == ""){
3506 $base= $lwm;
3507 } else {
3508 /* Call base hook */
3509 $base= get_base_from_hook($dn, $attrib);
3510 }
3511 for ($id= $base; $id++; $id < pow(2,32)){
3512 if (!in_array($id, $ids)){
3513 return ($id);
3514 }
3515 }
3517 /* Should not happen */
3518 if ($id == $hwm){
3519 msg_dialog::display(_("Error"), _("Cannot allocate a free ID!"), ERROR_DIALOG);
3520 exit;
3521 }
3522 }
3525 /* Mark the occurance of a string with a span */
3526 function mark($needle, $haystack, $ignorecase= true)
3527 {
3528 $result= "";
3530 while (preg_match('/^(.*)('.preg_quote($needle).')(.*)$/i', $haystack, $matches)) {
3531 $result.= $matches[1]."<span class='mark'>".$matches[2]."</span>";
3532 $haystack= $matches[3];
3533 }
3535 return $result.$haystack;
3536 }
3539 /* Return an image description using the path */
3540 function image($path, $action= "", $title= "", $align= "middle")
3541 {
3542 global $config;
3543 global $BASE_DIR;
3544 $label= null;
3546 // Bail out, if there's no style file
3547 if(!session::global_is_set("img-styles")){
3549 // Get theme
3550 if (isset ($config)){
3551 $theme= $config->get_cfg_value("theme", "default");
3552 } else {
3553 # For debuging - avoid that there's no theme set
3554 die("config not set!");
3555 $theme= "default";
3556 }
3558 if (!file_exists("$BASE_DIR/ihtml/themes/$theme/img.styles")){
3559 die ("No img.style for this theme found!");
3560 }
3562 session::global_set('img-styles', unserialize(file_get_contents("$BASE_DIR/ihtml/themes/$theme/img.styles")));
3563 }
3564 $styles= session::global_get('img-styles');
3566 /* Extract labels from path */
3567 if (preg_match("/\.png\[(.*)\]$/", $path, $matches)) {
3568 $label= $matches[1];
3569 }
3571 $lbl= "";
3572 if ($label) {
3573 if (isset($styles["images/label-".$label.".png"])) {
3574 $lbl= "<div style='".$styles["images/label-".$label.".png"]."'></div>";
3575 } else {
3576 die("Invalid label specified: $label\n");
3577 }
3579 $path= preg_replace("/\[.*\]$/", "", $path);
3580 }
3582 // Non middle layout?
3583 if ($align == "middle") {
3584 $align= "";
3585 } else {
3586 $align= ";vertical-align:$align";
3587 }
3589 // Clickable image or not?
3590 if ($title != "") {
3591 $title= "title='$title'";
3592 }
3593 if ($action == "") {
3594 return "<div class='img' $title style='".$styles[$path]."$align'>$lbl</div>";
3595 } else {
3596 return "<input type='submit' class='img' id='$action' value='' name='$action' $title style='".$styles[$path]."$align'>";
3597 }
3598 }
3600 /*! \brief Encodes a complex string to be useable in HTML posts.
3601 */
3602 function postEncode($str)
3603 {
3604 return(preg_replace("/=/","_", base64_encode($str)));
3605 }
3607 /*! \brief Decodes a string encoded by postEncode
3608 */
3609 function postDecode($str)
3610 {
3611 return(base64_decode(preg_replace("/_/","=", $str)));
3612 }
3614 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3615 ?>