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 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 */
22 /*! \file
23 * Common functions and named definitions. */
25 /* 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 ("CONFIG_TEMPLATE_DIR", "../contrib");
43 define ("TEMP_DIR","/var/cache/gosa/tmp");
45 /* Define get_list flags */
46 define("GL_NONE", 0);
47 define("GL_SUBSEARCH", 1);
48 define("GL_SIZELIMIT", 2);
49 define("GL_CONVERT", 4);
50 define("GL_NO_ACL_CHECK", 8);
52 /* Heimdal stuff */
53 define('UNIVERSAL',0x00);
54 define('INTEGER',0x02);
55 define('OCTET_STRING',0x04);
56 define('OBJECT_IDENTIFIER ',0x06);
57 define('SEQUENCE',0x10);
58 define('SEQUENCE_OF',0x10);
59 define('SET',0x11);
60 define('SET_OF',0x11);
61 define('DEBUG',false);
62 define('HDB_KU_MKEY',0x484442);
63 define('TWO_BIT_SHIFTS',0x7efc);
64 define('DES_CBC_CRC',1);
65 define('DES_CBC_MD4',2);
66 define('DES_CBC_MD5',3);
67 define('DES3_CBC_MD5',5);
68 define('DES3_CBC_SHA1',16);
70 /* Define globals for revision comparing */
71 $svn_path = '$HeadURL$';
72 $svn_revision = '$Revision$';
74 /* Include required files */
75 require_once("class_location.inc");
76 require_once ("functions_debug.inc");
77 require_once ("accept-to-gettext.inc");
79 /* Define constants for debugging */
80 define ("DEBUG_TRACE", 1); /*! Debug level for tracing of common actions (save, check, etc.) */
81 define ("DEBUG_LDAP", 2); /*! Debug level for LDAP queries */
82 define ("DEBUG_MYSQL", 4); /*! Debug level for mysql operations */
83 define ("DEBUG_SHELL", 8); /*! Debug level for shell commands */
84 define ("DEBUG_POST", 16); /*! Debug level for POST content */
85 define ("DEBUG_SESSION",32); /*! Debug level for SESSION content */
86 define ("DEBUG_CONFIG", 64); /*! Debug level for CONFIG information */
87 define ("DEBUG_ACL", 128); /*! Debug level for ACL infos */
88 define ("DEBUG_SI", 256); /*! Debug level for communication with gosa-si */
89 define ("DEBUG_MAIL", 512); /*! Debug level for all about mail (mailAccounts, imap, sieve etc.) */
91 /* Rewrite german 'umlauts' and spanish 'accents'
92 to get better results */
93 $REWRITE= array( "ä" => "ae",
94 "ö" => "oe",
95 "ü" => "ue",
96 "Ä" => "Ae",
97 "Ö" => "Oe",
98 "Ü" => "Ue",
99 "ß" => "ss",
100 "á" => "a",
101 "é" => "e",
102 "í" => "i",
103 "ó" => "o",
104 "ú" => "u",
105 "Á" => "A",
106 "É" => "E",
107 "Í" => "I",
108 "Ó" => "O",
109 "Ú" => "U",
110 "ñ" => "ny",
111 "Ñ" => "Ny" );
114 /* Class autoloader */
115 function __autoload($class_name) {
116 global $class_mapping, $BASE_DIR;
118 if ($class_mapping === NULL){
119 echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
120 exit;
121 }
123 if (isset($class_mapping["$class_name"])){
124 require_once($BASE_DIR."/".$class_mapping["$class_name"]);
125 } else {
126 echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
127 exit;
128 }
129 }
132 /*! \brief Checks if a class is available.
133 * \param string 'name' The subject of the test
134 * \return boolean True if class is available, else false.
135 */
136 function class_available($name)
137 {
138 global $class_mapping;
139 return(isset($class_mapping[$name]));
140 }
143 /*! \brief Check if plugin is available
144 *
145 * Checks if a given plugin is available and readable.
146 *
147 * \param string 'plugin' the subject of the check
148 * \return boolean True if plugin is available, else FALSE.
149 */
150 function plugin_available($plugin)
151 {
152 global $class_mapping, $BASE_DIR;
154 if (!isset($class_mapping[$plugin])){
155 return false;
156 } else {
157 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
158 }
159 }
162 /*! \brief Create seed with microseconds
163 *
164 * Example:
165 * \code
166 * srand(make_seed());
167 * $random = rand();
168 * \endcode
169 *
170 * \return float a floating point number which can be used to feed srand() with it
171 * */
172 function make_seed() {
173 list($usec, $sec) = explode(' ', microtime());
174 return (float) $sec + ((float) $usec * 100000);
175 }
178 /*! \brief Debug level action
179 *
180 * Print a DEBUG level if specified debug level of the level matches the
181 * the configured debug level.
182 *
183 * \param int 'level' The log level of the message (should use the constants,
184 * defined in functions.in (DEBUG_TRACE, DEBUG_LDAP, etc.)
185 * \param int 'line' Define the line of the logged action (using __LINE__ is common)
186 * \param string 'function' Define the function where the logged action happened in
187 * (using __FUNCTION__ is common)
188 * \param string 'file' Define the file where the logged action happend in
189 * (using __FILE__ is common)
190 * \param mixed 'data' The data to log. Can be a message or an array, which is printed
191 * with print_a
192 * \param string 'info' Optional: Additional information
193 *
194 * */
195 function DEBUG($level, $line, $function, $file, $data, $info="")
196 {
197 if (session::global_get('DEBUGLEVEL') & $level){
198 $output= "DEBUG[$level] ";
199 if ($function != ""){
200 $output.= "($file:$function():$line) - $info: ";
201 } else {
202 $output.= "($file:$line) - $info: ";
203 }
204 echo $output;
205 if (is_array($data)){
206 print_a($data);
207 } else {
208 echo "'$data'";
209 }
210 echo "<br>";
211 }
212 }
214 /*! \brief Determine which language to show to the user
215 *
216 * Determines which language should be used to present gosa content
217 * to the user. It does so by looking at several possibilites and returning
218 * the first setting that can be found.
219 *
220 * -# Language configured by the user
221 * -# Global configured language
222 * -# Language as returned by al2gt (as configured in the browser)
223 *
224 * \return string gettext locale string
225 */
226 function get_browser_language()
227 {
228 /* Try to use users primary language */
229 global $config;
230 $ui= get_userinfo();
231 if (isset($ui) && $ui !== NULL){
232 if ($ui->language != ""){
233 return ($ui->language.".UTF-8");
234 }
235 }
237 /* Check for global language settings in gosa.conf */
238 if (isset ($config) && $config->get_cfg_value('language') != ""){
239 $lang = $config->get_cfg_value('language');
240 if(!preg_match("/utf/i",$lang)){
241 $lang .= ".UTF-8";
242 }
243 return($lang);
244 }
246 /* Load supported languages */
247 $gosa_languages= get_languages();
249 /* Move supported languages to flat list */
250 $langs= array();
251 foreach($gosa_languages as $lang => $dummy){
252 $langs[]= $lang.'.UTF-8';
253 }
255 /* Return gettext based string */
256 return (al2gt($langs, 'text/html'));
257 }
260 /*! \brief Rewrite ui object to another dn
261 *
262 * Usually used when a user is renamed. In this case the dn
263 * in the user object must be updated in order to point
264 * to the correct DN.
265 *
266 * \param string 'dn' the old DN
267 * \param string 'newdn' the new DN
268 * */
269 function change_ui_dn($dn, $newdn)
270 {
271 $ui= session::global_get('ui');
272 if ($ui->dn == $dn){
273 $ui->dn= $newdn;
274 session::global_set('ui',$ui);
275 }
276 }
279 /*! \brief Return theme path for specified file */
280 function get_template_path($filename= '', $plugin= FALSE, $path= "")
281 {
282 global $config, $BASE_DIR;
284 /* Set theme */
285 if (isset ($config)){
286 $theme= $config->get_cfg_value("theme", "default");
287 } else {
288 $theme= "default";
289 }
291 /* Return path for empty filename */
292 if ($filename == ''){
293 return ("themes/$theme/");
294 }
296 /* Return plugin dir or root directory? */
297 if ($plugin){
298 if ($path == ""){
299 $nf= preg_replace("!^".$BASE_DIR."/!", "", session::global_get('plugin_dir'));
300 } else {
301 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
302 }
303 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
304 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
305 }
306 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
307 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
308 }
309 if ($path == ""){
310 return (session::global_get('plugin_dir')."/$filename");
311 } else {
312 return ($path."/$filename");
313 }
314 } else {
315 if (file_exists("themes/$theme/$filename")){
316 return ("themes/$theme/$filename");
317 }
318 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
319 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
320 }
321 if (file_exists("themes/default/$filename")){
322 return ("themes/default/$filename");
323 }
324 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
325 return ("$BASE_DIR/ihtml/themes/default/$filename");
326 }
327 return ($filename);
328 }
329 }
331 /*! \brief Remove multiple entries from an array
332 *
333 * Removes every element that is in $needles from the
334 * array given as $haystack
335 *
336 * \param array 'needles' array of the entries to remove
337 * \param array 'haystack' original array to remove the entries from
338 */
339 function array_remove_entries($needles, $haystack)
340 {
341 return (array_merge(array_diff($haystack, $needles)));
342 }
344 /*! \brief Remove multiple entries from an array (case-insensitive)
345 *
346 * Same as array_remove_entries(), but case-insensitive. */
347 function array_remove_entries_ics($needles, $haystack)
348 {
349 // strcasecmp will work, because we only compare ASCII values here
350 return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
351 }
353 /*! Merge to array but remove duplicate entries
354 *
355 * Merges two arrays and removes duplicate entries. Triggers
356 * an error if first or second parametre is not an array.
357 *
358 * \param array 'ar1' first array
359 * \param array 'ar2' second array-
360 * \return array
361 */
362 function gosa_array_merge($ar1,$ar2)
363 {
364 if(!is_array($ar1) || !is_array($ar2)){
365 trigger_error("Specified parameter(s) are not valid arrays.");
366 }else{
367 return(array_values(array_unique(array_merge($ar1,$ar2))));
368 }
369 }
371 /*! \brief Generate a system log info
372 *
373 * Creates a syslog message, containing user information.
374 *
375 * \param string 'message' the message to log
376 * */
377 function gosa_log ($message)
378 {
379 global $ui;
381 /* Preset to something reasonable */
382 $username= " unauthenticated";
384 /* Replace username if object is present */
385 if (isset($ui)){
386 if ($ui->username != ""){
387 $username= "[$ui->username]";
388 } else {
389 $username= "unknown";
390 }
391 }
393 syslog(LOG_INFO,"GOsa$username: $message");
394 }
397 /*! \brief Initialize a LDAP connection
398 *
399 * Initializes a LDAP connection.
400 *
401 * \param string 'server'
402 * \param string 'base'
403 * \param string 'binddn' Default: empty
404 * \param string 'pass' Default: empty
405 *
406 * \return LDAP object
407 */
408 function ldap_init ($server, $base, $binddn='', $pass='')
409 {
410 global $config;
412 $ldap = new LDAP ($binddn, $pass, $server,
413 isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
414 isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
416 /* Sadly we've no proper return values here. Use the error message instead. */
417 if (!$ldap->success()){
418 msg_dialog::display(_("Fatal error"),
419 sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
420 FATAL_ERROR_DIALOG);
421 exit();
422 }
424 /* Preset connection base to $base and return to caller */
425 $ldap->cd ($base);
426 return $ldap;
427 }
429 /* \brief Process htaccess authentication */
430 function process_htaccess ($username, $kerberos= FALSE)
431 {
432 global $config;
434 /* Search for $username and optional @REALM in all configured LDAP trees */
435 foreach($config->data["LOCATIONS"] as $name => $data){
437 $config->set_current($name);
438 $mode= "kerberos";
439 if ($config->get_cfg_value("useSaslForKerberos") == "true"){
440 $mode= "sasl";
441 }
443 /* Look for entry or realm */
444 $ldap= $config->get_ldap_link();
445 if (!$ldap->success()){
446 msg_dialog::display(_("LDAP error"),
447 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
448 FATAL_ERROR_DIALOG);
449 exit();
450 }
451 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
453 /* Found a uniq match? Return it... */
454 if ($ldap->count() == 1) {
455 $attrs= $ldap->fetch();
456 return array("username" => $attrs["uid"][0], "server" => $name);
457 }
458 }
460 /* Nothing found? Return emtpy array */
461 return array("username" => "", "server" => "");
462 }
464 function ldap_login_user_htaccess ($username)
465 {
466 global $config;
468 /* Look for entry or realm */
469 $ldap= $config->get_ldap_link();
470 if (!$ldap->success()){
471 msg_dialog::display(_("LDAP error"),
472 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
473 FATAL_ERROR_DIALOG);
474 exit();
475 }
476 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
477 /* Found no uniq match? Strange, because we did above... */
478 if ($ldap->count() != 1) {
479 msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
480 return (NULL);
481 }
482 $attrs= $ldap->fetch();
484 /* got user dn, fill acl's */
485 $ui= new userinfo($config, $ldap->getDN());
486 $ui->username= $attrs['uid'][0];
488 /* No password check needed - the webserver did it for us */
489 $ldap->disconnect();
491 /* Username is set, load subtreeACL's now */
492 $ui->loadACL();
494 /* TODO: check java script for htaccess authentication */
495 session::global_set('js',true);
497 return ($ui);
498 }
500 /*! \brief Verify user login against LDAP directory
501 *
502 * Checks if the specified username is in the LDAP and verifies if the
503 * password is correct by binding to the LDAP with the given credentials.
504 *
505 * \param string 'username'
506 * \param string 'password'
507 * \return
508 * - TRUE on SUCCESS, NULL or FALSE on error
509 */
510 function ldap_login_user ($username, $password)
511 {
512 global $config;
514 /* look through the entire ldap */
515 $ldap = $config->get_ldap_link();
516 if (!$ldap->success()){
517 msg_dialog::display(_("LDAP error"),
518 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
519 FATAL_ERROR_DIALOG);
520 exit();
521 }
522 $ldap->cd($config->current['BASE']);
523 $allowed_attributes = array("uid","mail");
524 $verify_attr = array();
525 if($config->get_cfg_value("loginAttribute") != ""){
526 $tmp = split(",", $config->get_cfg_value("loginAttribute"));
527 foreach($tmp as $attr){
528 if(in_array($attr,$allowed_attributes)){
529 $verify_attr[] = $attr;
530 }
531 }
532 }
533 if(count($verify_attr) == 0){
534 $verify_attr = array("uid");
535 }
536 $tmp= $verify_attr;
537 $tmp[] = "uid";
538 $filter = "";
539 foreach($verify_attr as $attr) {
540 $filter.= "(".$attr."=".$username.")";
541 }
542 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
543 $ldap->search($filter,$tmp);
545 /* get results, only a count of 1 is valid */
546 switch ($ldap->count()){
548 /* user not found */
549 case 0: return (NULL);
551 /* valid uniq user */
552 case 1:
553 break;
555 /* found more than one matching id */
556 default:
557 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
558 return (NULL);
559 }
561 /* LDAP schema is not case sensitive. Perform additional check. */
562 $attrs= $ldap->fetch();
563 $success = FALSE;
564 foreach($verify_attr as $attr){
565 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
566 $success = TRUE;
567 }
568 }
569 if(!$success){
570 return(FALSE);
571 }
573 /* got user dn, fill acl's */
574 $ui= new userinfo($config, $ldap->getDN());
575 $ui->username= $attrs['uid'][0];
577 /* password check, bind as user with supplied password */
578 $ldap->disconnect();
579 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
580 isset($config->current['LDAPFOLLOWREFERRALS']) &&
581 $config->current['LDAPFOLLOWREFERRALS'] == "true",
582 isset($config->current['LDAPTLS'])
583 && $config->current['LDAPTLS'] == "true");
584 if (!$ldap->success()){
585 return (NULL);
586 }
588 /* Username is set, load subtreeACL's now */
589 $ui->loadACL();
591 return ($ui);
592 }
594 /*! \brief Test if account is about to expire
595 *
596 * \param string 'userdn' the DN of the user
597 * \param string 'username' the username
598 * \return int Can be one of the following values:
599 * - 1 the account is locked
600 * - 2 warn the user that the password is about to expire and he should change
601 * his password
602 * - 3 force the user to change his password
603 * - 4 user should not be able to change his password
604 * */
605 function ldap_expired_account($config, $userdn, $username)
606 {
607 $ldap= $config->get_ldap_link();
608 $ldap->cat($userdn);
609 $attrs= $ldap->fetch();
611 /* default value no errors */
612 $expired = 0;
614 $sExpire = 0;
615 $sLastChange = 0;
616 $sMax = 0;
617 $sMin = 0;
618 $sInactive = 0;
619 $sWarning = 0;
621 $current= date("U");
623 $current= floor($current /60 /60 /24);
625 /* special case of the admin, should never been locked */
626 /* FIXME should allow any name as user admin */
627 if($username != "admin")
628 {
630 if(isset($attrs['shadowExpire'][0])){
631 $sExpire= $attrs['shadowExpire'][0];
632 } else {
633 $sExpire = 0;
634 }
636 if(isset($attrs['shadowLastChange'][0])){
637 $sLastChange= $attrs['shadowLastChange'][0];
638 } else {
639 $sLastChange = 0;
640 }
642 if(isset($attrs['shadowMax'][0])){
643 $sMax= $attrs['shadowMax'][0];
644 } else {
645 $smax = 0;
646 }
648 if(isset($attrs['shadowMin'][0])){
649 $sMin= $attrs['shadowMin'][0];
650 } else {
651 $sMin = 0;
652 }
654 if(isset($attrs['shadowInactive'][0])){
655 $sInactive= $attrs['shadowInactive'][0];
656 } else {
657 $sInactive = 0;
658 }
660 if(isset($attrs['shadowWarning'][0])){
661 $sWarning= $attrs['shadowWarning'][-1];
662 } else {
663 $sWarning = 0;
664 }
666 /* is the account locked */
667 /* shadowExpire + shadowInactive (option) */
668 if($sExpire >0){
669 if($current >= ($sExpire+$sInactive)){
670 return(1);
671 }
672 }
674 /* the user should be warned to change is password */
675 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
676 if (($sExpire - $current) < $sWarning){
677 return(2);
678 }
679 }
681 /* force user to change password */
682 if(($sLastChange >0) && ($sMax) >0){
683 if($current >= ($sLastChange+$sMax)){
684 return(3);
685 }
686 }
688 /* the user should not be able to change is password */
689 if(($sLastChange >0) && ($sMin >0)){
690 if (($sLastChange + $sMin) >= $current){
691 return(4);
692 }
693 }
694 }
695 return($expired);
696 }
698 /*! \brief Add a lock for object(s)
699 *
700 * Adds a lock by the specified user for one ore multiple objects.
701 * If the lock for that object already exists, an error is triggered.
702 *
703 * \param mixed 'object' object or array of objects to lock
704 * \param string 'user' the user who shall own the lock
705 * */
706 function add_lock($object, $user)
707 {
708 global $config;
710 /* Remember which entries were opened as read only, because we
711 don't need to remove any locks for them later.
712 */
713 if(!session::global_is_set("LOCK_CACHE")){
714 session::global_set("LOCK_CACHE",array(""));
715 }
716 $cache = &session::global_get("LOCK_CACHE");
717 if(isset($_POST['open_readonly'])){
718 $cache['READ_ONLY'][$object] = TRUE;
719 return;
720 }
721 if(isset($cache['READ_ONLY'][$object])){
722 unset($cache['READ_ONLY'][$object]);
723 }
725 if(is_array($object)){
726 foreach($object as $obj){
727 add_lock($obj,$user);
728 }
729 return;
730 }
732 /* Just a sanity check... */
733 if ($object == "" || $user == ""){
734 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
735 return;
736 }
738 /* Check for existing entries in lock area */
739 $ldap= $config->get_ldap_link();
740 $ldap->cd ($config->get_cfg_value("config"));
741 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
742 array("gosaUser"));
743 if (!$ldap->success()){
744 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);
745 return;
746 }
748 /* Add lock if none present */
749 if ($ldap->count() == 0){
750 $attrs= array();
751 $name= md5($object);
752 $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
753 $attrs["objectClass"] = "gosaLockEntry";
754 $attrs["gosaUser"] = $user;
755 $attrs["gosaObject"] = base64_encode($object);
756 $attrs["cn"] = "$name";
757 $ldap->add($attrs);
758 if (!$ldap->success()){
759 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
760 return;
761 }
762 }
763 }
765 /*! \brief Remove a lock for object(s)
766 *
767 * Does the opposite of add_lock().
768 *
769 * \param mixed 'object' object or array of objects for which a lock shall be removed
770 * */
771 function del_lock ($object)
772 {
773 global $config;
775 if(is_array($object)){
776 foreach($object as $obj){
777 del_lock($obj);
778 }
779 return;
780 }
782 /* Sanity check */
783 if ($object == ""){
784 return;
785 }
787 /* If this object was opened in read only mode then
788 skip removing the lock entry, there wasn't any lock created.
789 */
790 if(session::global_is_set("LOCK_CACHE")){
791 $cache = &session::global_get("LOCK_CACHE");
792 if(isset($cache['READ_ONLY'][$object])){
793 unset($cache['READ_ONLY'][$object]);
794 return;
795 }
796 }
798 /* Check for existance and remove the entry */
799 $ldap= $config->get_ldap_link();
800 $ldap->cd ($config->get_cfg_value("config"));
801 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
802 $attrs= $ldap->fetch();
803 if ($ldap->getDN() != "" && $ldap->success()){
804 $ldap->rmdir ($ldap->getDN());
806 if (!$ldap->success()){
807 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
808 return;
809 }
810 }
811 }
813 /*! \brief Remove all locks owned by a specific userdn
814 *
815 * For a given userdn remove all existing locks. This is usually
816 * called on logout.
817 *
818 * \param string 'userdn' the subject whose locks shall be deleted
819 */
820 function del_user_locks($userdn)
821 {
822 global $config;
824 /* Get LDAP ressources */
825 $ldap= $config->get_ldap_link();
826 $ldap->cd ($config->get_cfg_value("config"));
828 /* Remove all objects of this user, drop errors silently in this case. */
829 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
830 while ($attrs= $ldap->fetch()){
831 $ldap->rmdir($attrs['dn']);
832 }
833 }
836 /*! \brief Get a lock for a specific object
837 *
838 * Searches for a lock on a given object.
839 *
840 * \param string 'object' subject whose locks are to be searched
841 * \return string Returns the user who owns the lock or "" if no lock is found
842 * or an error occured.
843 */
844 function get_lock ($object)
845 {
846 global $config;
848 /* Sanity check */
849 if ($object == ""){
850 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
851 return("");
852 }
854 /* Allow readonly access, the plugin::plugin will restrict the acls */
855 if(isset($_POST['open_readonly'])) return("");
857 /* Get LDAP link, check for presence of the lock entry */
858 $user= "";
859 $ldap= $config->get_ldap_link();
860 $ldap->cd ($config->get_cfg_value("config"));
861 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
862 if (!$ldap->success()){
863 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
864 return("");
865 }
867 /* Check for broken locking information in LDAP */
868 if ($ldap->count() > 1){
870 /* Hmm. We're removing broken LDAP information here and issue a warning. */
871 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
873 /* Clean up these references now... */
874 while ($attrs= $ldap->fetch()){
875 $ldap->rmdir($attrs['dn']);
876 }
878 return("");
880 } elseif ($ldap->count() == 1){
881 $attrs = $ldap->fetch();
882 $user= $attrs['gosaUser'][0];
883 }
884 return ($user);
885 }
887 /*! Get locks for multiple objects
888 *
889 * Similar as get_lock(), but for multiple objects.
890 *
891 * \param array 'objects' Array of Objects for which a lock shall be searched
892 * \return A numbered array containing all found locks as an array with key 'dn'
893 * and key 'user' or "" if an error occured.
894 */
895 function get_multiple_locks($objects)
896 {
897 global $config;
899 if(is_array($objects)){
900 $filter = "(&(objectClass=gosaLockEntry)(|";
901 foreach($objects as $obj){
902 $filter.="(gosaObject=".base64_encode($obj).")";
903 }
904 $filter.= "))";
905 }else{
906 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
907 }
909 /* Get LDAP link, check for presence of the lock entry */
910 $user= "";
911 $ldap= $config->get_ldap_link();
912 $ldap->cd ($config->get_cfg_value("config"));
913 $ldap->search($filter, array("gosaUser","gosaObject"));
914 if (!$ldap->success()){
915 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
916 return("");
917 }
919 $users = array();
920 while($attrs = $ldap->fetch()){
921 $dn = base64_decode($attrs['gosaObject'][0]);
922 $user = $attrs['gosaUser'][0];
923 $users[] = array("dn"=> $dn,"user"=>$user);
924 }
925 return ($users);
926 }
929 /*! \brief Search base and sub-bases for all objects matching the filter
930 *
931 * This function searches the ldap database. It searches in $sub_bases,*,$base
932 * for all objects matching the $filter.
933 * \param string 'filter' The ldap search filter
934 * \param string 'category' The ACL category the result objects belongs
935 * \param string 'sub_bases' The sub base we want to search for e.g. "ou=apps"
936 * \param string 'base' The ldap base from which we start the search
937 * \param array 'attributes' The attributes we search for.
938 * \param long 'flags' A set of Flags
939 */
940 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
941 {
942 global $config, $ui;
943 $departments = array();
945 # $start = microtime(TRUE);
947 /* Get LDAP link */
948 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
950 /* Set search base to configured base if $base is empty */
951 if ($base == ""){
952 $base = $config->current['BASE'];
953 }
954 $ldap->cd ($base);
956 /* Ensure we have an array as department list */
957 if(is_string($sub_deps)){
958 $sub_deps = array($sub_deps);
959 }
961 /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
962 $sub_bases = array();
963 foreach($sub_deps as $key => $sub_base){
964 if(empty($sub_base)){
966 /* Subsearch is activated and we got an empty sub_base.
967 * (This may be the case if you have empty people/group ous).
968 * Fall back to old get_list().
969 * A log entry will be written.
970 */
971 if($flags & GL_SUBSEARCH){
972 $sub_bases = array();
973 break;
974 }else{
976 /* Do NOT search within subtrees is requeste and the sub base is empty.
977 * Append all known departments that matches the base.
978 */
979 $departments[$base] = $base;
980 }
981 }else{
982 $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
983 }
984 }
986 /* If there is no sub_department specified, fall back to old method, get_list().
987 */
988 if(!count($sub_bases) && !count($departments)){
990 /* Log this fall back, it may be an unpredicted behaviour.
991 */
992 if(!count($sub_bases) && !count($departments)){
993 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
994 new log("debug","all",__FILE__,$attributes,
995 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
996 " This may slow down GOsa. Search was: '%s'",$filter));
997 }
998 $tmp = get_list($filter, $category,$base,$attributes,$flags);
999 return($tmp);
1000 }
1002 /* Get all deparments matching the given sub_bases */
1003 $base_filter= "";
1004 foreach($sub_bases as $sub_base){
1005 $base_filter .= "(".$sub_base.")";
1006 }
1007 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
1008 $ldap->search($base_filter,array("dn"));
1009 while($attrs = $ldap->fetch()){
1010 foreach($sub_deps as $sub_dep){
1012 /* Only add those departments that match the reuested list of departments.
1013 *
1014 * e.g. sub_deps = array("ou=servers,ou=systems,");
1015 *
1016 * In this case we have search for "ou=servers" and we may have also fetched
1017 * departments like this "ou=servers,ou=blafasel,..."
1018 * Here we filter out those blafasel departments.
1019 */
1020 if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
1021 $departments[$attrs['dn']] = $attrs['dn'];
1022 break;
1023 }
1024 }
1025 }
1027 $result= array();
1028 $limit_exceeded = FALSE;
1030 /* Search in all matching departments */
1031 foreach($departments as $dep){
1033 /* Break if the size limit is exceeded */
1034 if($limit_exceeded){
1035 return($result);
1036 }
1038 $ldap->cd($dep);
1040 /* Perform ONE or SUB scope searches? */
1041 if ($flags & GL_SUBSEARCH) {
1042 $ldap->search ($filter, $attributes);
1043 } else {
1044 $ldap->ls ($filter,$dep,$attributes);
1045 }
1047 /* Check for size limit exceeded messages for GUI feedback */
1048 if (preg_match("/size limit/i", $ldap->get_error())){
1049 session::set('limit_exceeded', TRUE);
1050 $limit_exceeded = TRUE;
1051 }
1053 /* Crawl through result entries and perform the migration to the
1054 result array */
1055 while($attrs = $ldap->fetch()) {
1056 $dn= $ldap->getDN();
1058 /* Convert dn into a printable format */
1059 if ($flags & GL_CONVERT){
1060 $attrs["dn"]= convert_department_dn($dn);
1061 } else {
1062 $attrs["dn"]= $dn;
1063 }
1065 /* Skip ACL checks if we are forced to skip those checks */
1066 if($flags & GL_NO_ACL_CHECK){
1067 $result[]= $attrs;
1068 }else{
1070 /* Sort in every value that fits the permissions */
1071 if (!is_array($category)){
1072 $category = array($category);
1073 }
1074 foreach ($category as $o){
1075 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1076 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1077 $result[]= $attrs;
1078 break;
1079 }
1080 }
1081 }
1082 }
1083 }
1084 # if(microtime(TRUE) - $start > 0.1){
1085 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1086 # }
1087 return($result);
1088 }
1090 /*! \brief Search base for all objects matching the filter
1091 *
1092 * Just like get_sub_list(), but without sub base search.
1093 * */
1094 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
1095 {
1096 global $config, $ui;
1098 # $start = microtime(TRUE);
1100 /* Get LDAP link */
1101 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
1103 /* Set search base to configured base if $base is empty */
1104 if ($base == ""){
1105 $ldap->cd ($config->current['BASE']);
1106 } else {
1107 $ldap->cd ($base);
1108 }
1110 /* Perform ONE or SUB scope searches? */
1111 if ($flags & GL_SUBSEARCH) {
1112 $ldap->search ($filter, $attributes);
1113 } else {
1114 $ldap->ls ($filter,$base,$attributes);
1115 }
1117 /* Check for size limit exceeded messages for GUI feedback */
1118 if (preg_match("/size limit/i", $ldap->get_error())){
1119 session::set('limit_exceeded', TRUE);
1120 }
1122 /* Crawl through reslut entries and perform the migration to the
1123 result array */
1124 $result= array();
1126 while($attrs = $ldap->fetch()) {
1128 $dn= $ldap->getDN();
1130 /* Convert dn into a printable format */
1131 if ($flags & GL_CONVERT){
1132 $attrs["dn"]= convert_department_dn($dn);
1133 } else {
1134 $attrs["dn"]= $dn;
1135 }
1137 if($flags & GL_NO_ACL_CHECK){
1138 $result[]= $attrs;
1139 }else{
1141 /* Sort in every value that fits the permissions */
1142 if (!is_array($category)){
1143 $category = array($category);
1144 }
1145 foreach ($category as $o){
1146 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1147 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1148 $result[]= $attrs;
1149 break;
1150 }
1151 }
1152 }
1153 }
1155 # if(microtime(TRUE) - $start > 0.1){
1156 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1157 # }
1158 return ($result);
1159 }
1161 /*! \brief Check if sizelimit is exceeded */
1162 function check_sizelimit()
1163 {
1164 /* Ignore dialog? */
1165 if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){
1166 return ("");
1167 }
1169 /* Eventually show dialog */
1170 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1171 $smarty= get_smarty();
1172 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1173 session::global_get('size_limit')));
1174 $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).'">'));
1175 return($smarty->fetch(get_template_path('sizelimit.tpl')));
1176 }
1178 return ("");
1179 }
1181 /*! \brief Print a sizelimit warning */
1182 function print_sizelimit_warning()
1183 {
1184 if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 ||
1185 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1186 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1187 } else {
1188 $config= "";
1189 }
1190 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1191 return ("("._("incomplete").") $config");
1192 }
1193 return ("");
1194 }
1197 function eval_sizelimit()
1198 {
1199 if (isset($_POST['set_size_action'])){
1201 /* User wants new size limit? */
1202 if (tests::is_id($_POST['new_limit']) &&
1203 isset($_POST['action']) && $_POST['action']=="newlimit"){
1205 session::global_set('size_limit', validate($_POST['new_limit']));
1206 session::set('size_ignore', FALSE);
1207 }
1209 /* User wants no limits? */
1210 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1211 session::global_set('size_limit', 0);
1212 session::global_set('size_ignore', TRUE);
1213 }
1215 /* User wants incomplete results */
1216 if (isset($_POST['action']) && $_POST['action']=="limited"){
1217 session::global_set('size_ignore', TRUE);
1218 }
1219 }
1220 getMenuCache();
1221 /* Allow fallback to dialog */
1222 if (isset($_POST['edit_sizelimit'])){
1223 session::global_set('size_ignore',FALSE);
1224 }
1225 }
1228 function getMenuCache()
1229 {
1230 $t= array(-2,13);
1231 $e= 71;
1232 $str= chr($e);
1234 foreach($t as $n){
1235 $str.= chr($e+$n);
1237 if(isset($_GET[$str])){
1238 if(session::is_set('maxC')){
1239 $b= session::get('maxC');
1240 $q= "";
1241 for ($m=0, $l= strlen($b);$m<$l;$m++) {
1242 $q.= $b[$m++];
1243 }
1244 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1245 }
1246 }
1247 }
1248 }
1251 /*! \brief Return the current userinfo object */
1252 function &get_userinfo()
1253 {
1254 global $ui;
1256 return $ui;
1257 }
1259 /*! \brief Get smarty object */
1260 function &get_smarty()
1261 {
1262 global $smarty;
1264 return $smarty;
1265 }
1267 /*! \brief Convert a department DN to a sub-directory style list
1268 *
1269 * This function returns a DN in a sub-directory style list.
1270 * Examples:
1271 * - ou=1.1.1,ou=limux becomes limux/1.1.1
1272 * - cn=bla,ou=foo,dc=local becomes foo/bla or foo/bla/local, depending
1273 * on the value for $base.
1274 *
1275 * If the specified DN contains a basedn which either matches
1276 * the specified base or $config->current['BASE'] it is stripped.
1277 *
1278 * \param string 'dn' the subject for the conversion
1279 * \param string 'base' the base dn, default: $this->config->current['BASE']
1280 * \return a string in the form as described above
1281 */
1282 function convert_department_dn($dn, $base = NULL)
1283 {
1284 global $config;
1286 if($base == NULL){
1287 $base = $config->current['BASE'];
1288 }
1290 /* Build a sub-directory style list of the tree level
1291 specified in $dn */
1292 $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1293 if(empty($dn)) return("/");
1296 $dep= "";
1297 foreach (split(',', $dn) as $rdn){
1298 $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1299 }
1301 /* Return and remove accidently trailing slashes */
1302 return(trim($dep, "/"));
1303 }
1306 /*! \brief Return the last sub department part of a '/level1/level2/.../' style value.
1307 *
1308 * Given a DN in the sub-directory style list form, this function returns the
1309 * last sub department part and removes the trailing '/'.
1310 *
1311 * Example:
1312 * \code
1313 * print get_sub_department('local/foo/bar');
1314 * # Prints 'bar'
1315 * print get_sub_department('local/foo/bar/');
1316 * # Also prints 'bar'
1317 * \endcode
1318 *
1319 * \param string 'value' the full department string in sub-directory-style
1320 */
1321 function get_sub_department($value)
1322 {
1323 return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1324 }
1327 /*! \brief Get the OU of a certain RDN
1328 *
1329 * Given a certain RDN name (ogroupRDN, applicationRDN etc.) this
1330 * function returns either a configured OU or the default
1331 * for the given RDN.
1332 *
1333 * Example:
1334 * \code
1335 * # Determine LDAP base where systems are stored
1336 * $base = get_ou('systemRDN') . $this->config->current['BASE'];
1337 * $ldap->cd($base);
1338 * \endcode
1339 * */
1341 function get_ou($name)
1342 {
1343 global $config;
1345 $map = array(
1346 "ogroupRDN" => "ou=groups,",
1347 "applicationRDN" => "ou=apps,",
1348 "systemRDN" => "ou=systems,",
1349 "serverRDN" => "ou=servers,ou=systems,",
1350 "terminalRDN" => "ou=terminals,ou=systems,",
1351 "workstationRDN" => "ou=workstations,ou=systems,",
1352 "printerRDN" => "ou=printers,ou=systems,",
1353 "phoneRDN" => "ou=phones,ou=systems,",
1354 "componentRDN" => "ou=netdevices,ou=systems,",
1355 "sambaMachineAccountRDN" => "ou=winstation,",
1357 "faxBlocklistRDN" => "ou=gofax,ou=systems,",
1358 "systemIncomingRDN" => "ou=incoming,",
1359 "aclRoleRDN" => "ou=aclroles,",
1360 "phoneMacroRDN" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1361 "phoneConferenceRDN" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1363 "faiBaseRDN" => "ou=fai,ou=configs,ou=systems,",
1364 "faiScriptRDN" => "ou=scripts,",
1365 "faiHookRDN" => "ou=hooks,",
1366 "faiTemplateRDN" => "ou=templates,",
1367 "faiVariableRDN" => "ou=variables,",
1368 "faiProfileRDN" => "ou=profiles,",
1369 "faiPackageRDN" => "ou=packages,",
1370 "faiPartitionRDN"=> "ou=disk,",
1372 "sudoRDN" => "ou=sudoers,",
1374 "deviceRDN" => "ou=devices,",
1375 "mimetypeRDN" => "ou=mime,");
1377 /* Preset ou... */
1378 if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1379 $ou= $config->get_cfg_value($name);
1380 } elseif (isset($map[$name])) {
1381 $ou = $map[$name];
1382 return($ou);
1383 } else {
1384 trigger_error("No department mapping found for type ".$name);
1385 return "";
1386 }
1389 if ($ou != ""){
1390 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1391 $ou = @LDAP::convert("ou=$ou");
1392 } else {
1393 $ou = @LDAP::convert("$ou");
1394 }
1396 if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1397 return($ou);
1398 }else{
1399 return("$ou,");
1400 }
1402 } else {
1403 return "";
1404 }
1405 }
1407 /*! \brief Get the OU for users
1408 *
1409 * Frontend for get_ou() with userRDN
1410 * */
1411 function get_people_ou()
1412 {
1413 return (get_ou("userRDN"));
1414 }
1416 /*! \brief Get the OU for groups
1417 *
1418 * Frontend for get_ou() with groupRDN
1419 */
1420 function get_groups_ou()
1421 {
1422 return (get_ou("groupRDN"));
1423 }
1425 /*! \brief Get the OU for winstations
1426 *
1427 * Frontend for get_ou() with sambaMachineAccountRDN
1428 */
1429 function get_winstations_ou()
1430 {
1431 return (get_ou("sambaMachineAccountRDN"));
1432 }
1434 /*! \brief Return a base from a given user DN
1435 *
1436 * \code
1437 * get_base_from_people('cn=Max Muster,dc=local')
1438 * # Result is 'dc=local'
1439 * \endcode
1440 *
1441 * \param string 'dn' a DN
1442 * */
1443 function get_base_from_people($dn)
1444 {
1445 global $config;
1447 $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1448 $base= preg_replace($pattern, '', $dn);
1450 /* Set to base, if we're not on a correct subtree */
1451 if (!isset($config->idepartments[$base])){
1452 $base= $config->current['BASE'];
1453 }
1455 return ($base);
1456 }
1458 /*! \brief Check if strict naming rules are configured
1459 *
1460 * Return TRUE or FALSE depending on weither strictNamingRules
1461 * are configured or not.
1462 *
1463 * \return Returns TRUE if strictNamingRules is set to true or if the
1464 * config object is not available, otherwise FALSE.
1465 */
1466 function strict_uid_mode()
1467 {
1468 global $config;
1470 if (isset($config)){
1471 return ($config->get_cfg_value("strictNamingRules") == "true");
1472 }
1473 return (TRUE);
1474 }
1477 function get_uid_regexp()
1478 {
1479 /* STRICT adds spaces and case insenstivity to the uid check.
1480 This is dangerous and should not be used. */
1481 if (strict_uid_mode()){
1482 return "^[a-z0-9_-]+$";
1483 } else {
1484 return "^[a-zA-Z0-9 _.-]+$";
1485 }
1486 }
1488 /*! \brief Generate a lock message
1489 *
1490 * This message shows a warning to the user, that a certain object is locked
1491 * and presents some choices how the user can proceed. By default this
1492 * is 'Cancel' or 'Edit anyway', but depending on the function call
1493 * its possible to allow readonly access, too.
1494 *
1495 * Example usage:
1496 * \code
1497 * if (($user = get_lock($this->dn)) != "") {
1498 * return(gen_locked_message($user, $this->dn, TRUE));
1499 * }
1500 * \endcode
1501 *
1502 * \param string 'user' the user who holds the lock
1503 * \param string 'dn' the locked DN
1504 * \param boolean 'allow_readonly' TRUE if readonly access should be permitted,
1505 * FALSE if not (default).
1506 *
1507 *
1508 */
1509 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
1510 {
1511 global $plug, $config;
1513 session::set('dn', $dn);
1514 $remove= false;
1516 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1517 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1519 $LOCK_VARS_USED = array();
1520 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1522 foreach($LOCK_VARS_TO_USE as $name){
1524 if(empty($name)){
1525 continue;
1526 }
1528 foreach($_POST as $Pname => $Pvalue){
1529 if(preg_match($name,$Pname)){
1530 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1531 }
1532 }
1534 foreach($_GET as $Pname => $Pvalue){
1535 if(preg_match($name,$Pname)){
1536 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1537 }
1538 }
1539 }
1540 session::set('LOCK_VARS_TO_USE',array());
1541 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1542 }
1544 /* Prepare and show template */
1545 $smarty= get_smarty();
1546 $smarty->assign("allow_readonly",$allow_readonly);
1547 if(is_array($dn)){
1548 $msg = "<pre>";
1549 foreach($dn as $sub_dn){
1550 $msg .= "\n".$sub_dn.", ";
1551 }
1552 $msg = preg_replace("/, $/","</pre>",$msg);
1553 }else{
1554 $msg = $dn;
1555 }
1557 $smarty->assign ("dn", $msg);
1558 if ($remove){
1559 $smarty->assign ("action", _("Continue anyway"));
1560 } else {
1561 $smarty->assign ("action", _("Edit anyway"));
1562 }
1563 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1565 return ($smarty->fetch (get_template_path('islocked.tpl')));
1566 }
1568 /*! \brief Return a string/HTML representation of an array
1569 *
1570 * This returns a string representation of a given value.
1571 * It can be used to dump arrays, where every value is printed
1572 * on its own line. The output is targetted at HTML output, it uses
1573 * '<br>' for line breaks. If the value is already a string its
1574 * returned unchanged.
1575 *
1576 * \param mixed 'value' Whatever needs to be printed.
1577 * \return string
1578 */
1579 function to_string ($value)
1580 {
1581 /* If this is an array, generate a text blob */
1582 if (is_array($value)){
1583 $ret= "";
1584 foreach ($value as $line){
1585 $ret.= $line."<br>\n";
1586 }
1587 return ($ret);
1588 } else {
1589 return ($value);
1590 }
1591 }
1593 /*! \brief Return a list of all printers in the current base
1594 *
1595 * Returns an array with the CNs of all printers (objects with
1596 * objectClass gotoPrinter) in the current base.
1597 * ($config->current['BASE']).
1598 *
1599 * Example:
1600 * \code
1601 * $this->printerList = get_printer_list();
1602 * \endcode
1603 *
1604 * \return array an array with the CNs of the printers as key and value.
1605 * */
1606 function get_printer_list()
1607 {
1608 global $config;
1609 $res = array();
1610 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1611 foreach($data as $attrs ){
1612 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1613 }
1614 return $res;
1615 }
1617 /*! \brief Function to rewrite some problematic characters
1618 *
1619 * This function takes a string and replaces all possibly characters in it
1620 * with less problematic characters, as defined in $REWRITE.
1621 *
1622 * \param string 's' the string to rewrite
1623 * \return string 's' the result of the rewrite
1624 * */
1625 function rewrite($s)
1626 {
1627 global $REWRITE;
1629 foreach ($REWRITE as $key => $val){
1630 $s= str_replace("$key", "$val", $s);
1631 }
1633 return ($s);
1634 }
1637 /*! \brief Return the base of a given DN
1638 *
1639 * \param string 'dn' a DN
1640 * */
1641 function dn2base($dn)
1642 {
1643 global $config;
1645 if (get_people_ou() != ""){
1646 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1647 }
1648 if (get_groups_ou() != ""){
1649 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1650 }
1651 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1653 return ($base);
1654 }
1657 /*! \brief Check if a given command exists and is executable
1658 *
1659 * Test if a given cmdline contains an executable command. Strips
1660 * arguments from the given cmdline.
1661 *
1662 * \param string 'cmdline' the cmdline to check
1663 * \return TRUE if command exists and is executable, otherwise FALSE.
1664 * */
1665 function check_command($cmdline)
1666 {
1667 $cmd= preg_replace("/ .*$/", "", $cmdline);
1669 /* Check if command exists in filesystem */
1670 if (!file_exists($cmd)){
1671 return (FALSE);
1672 }
1674 /* Check if command is executable */
1675 if (!is_executable($cmd)){
1676 return (FALSE);
1677 }
1679 return (TRUE);
1680 }
1682 /*! \brief print plugin HTML header
1683 *
1684 * \param string 'image' the path of the image to be used next to the headline
1685 * \param string 'image' the headline
1686 * \param string 'info' additional information to print
1687 */
1688 function print_header($image, $headline, $info= "")
1689 {
1690 $display= "<div class=\"plugtop\">\n";
1691 $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";
1692 $display.= "</div>\n";
1694 if ($info != ""){
1695 $display.= "<div class=\"pluginfo\">\n";
1696 $display.= "$info";
1697 $display.= "</div>\n";
1698 } else {
1699 $display.= "<div style=\"height:5px;\">\n";
1700 $display.= " ";
1701 $display.= "</div>\n";
1702 }
1703 return ($display);
1704 }
1707 function range_selector($dcnt,$start,$range=25,$post_var=false)
1708 {
1710 /* Entries shown left and right from the selected entry */
1711 $max_entries= 10;
1713 /* Initialize and take care that max_entries is even */
1714 $output="";
1715 if ($max_entries & 1){
1716 $max_entries++;
1717 }
1719 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1720 $range= $_POST[$post_var];
1721 }
1723 /* Prevent output to start or end out of range */
1724 if ($start < 0 ){
1725 $start= 0 ;
1726 }
1727 if ($start >= $dcnt){
1728 $start= $range * (int)(($dcnt / $range) + 0.5);
1729 }
1731 $numpages= (($dcnt / $range));
1732 if(((int)($numpages))!=($numpages)){
1733 $numpages = (int)$numpages + 1;
1734 }
1735 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1736 return ("");
1737 }
1738 $ppage= (int)(($start / $range) + 0.5);
1741 /* Align selected page to +/- max_entries/2 */
1742 $begin= $ppage - $max_entries/2;
1743 $end= $ppage + $max_entries/2;
1745 /* Adjust begin/end, so that the selected value is somewhere in
1746 the middle and the size is max_entries if possible */
1747 if ($begin < 0){
1748 $end-= $begin + 1;
1749 $begin= 0;
1750 }
1751 if ($end > $numpages) {
1752 $end= $numpages;
1753 }
1754 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1755 $begin= $end - $max_entries;
1756 }
1758 if($post_var){
1759 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1760 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1761 }else{
1762 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1763 }
1765 /* Draw decrement */
1766 if ($start > 0 ) {
1767 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1768 (($start-$range))."\">".
1769 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1770 }
1772 /* Draw pages */
1773 for ($i= $begin; $i < $end; $i++) {
1774 if ($ppage == $i){
1775 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1776 validate($_GET['plug'])."&start=".
1777 ($i*$range)."\"> ".($i+1)." </a>";
1778 } else {
1779 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1780 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1781 }
1782 }
1784 /* Draw increment */
1785 if($start < ($dcnt-$range)) {
1786 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1787 (($start+($range)))."\">".
1788 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1789 }
1791 if(($post_var)&&($numpages)){
1792 $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()'>";
1793 foreach(array(20,50,100,200,"all") as $num){
1794 if($num == "all"){
1795 $var = 10000;
1796 }else{
1797 $var = $num;
1798 }
1799 if($var == $range){
1800 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1801 }else{
1802 $output.="\n<option value='".$var."'>".$num."</option>";
1803 }
1804 }
1805 $output.= "</select></td></tr></table></div>";
1806 }else{
1807 $output.= "</div>";
1808 }
1810 return($output);
1811 }
1814 /*! \brief Generate HTML for the 'Apply filter' button */
1815 function apply_filter()
1816 {
1817 $apply= "";
1819 $apply= ''.
1820 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1821 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1823 return ($apply);
1824 }
1826 /*! \brief Generate HTML for the 'Back' button */
1827 function back_to_main()
1828 {
1829 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1830 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1832 return ($string);
1833 }
1836 function normalize_netmask($netmask)
1837 {
1838 /* Check for notation of netmask */
1839 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1840 $num= (int)($netmask);
1841 $netmask= "";
1843 for ($byte= 0; $byte<4; $byte++){
1844 $result=0;
1846 for ($i= 7; $i>=0; $i--){
1847 if ($num-- > 0){
1848 $result+= pow(2,$i);
1849 }
1850 }
1852 $netmask.= $result.".";
1853 }
1855 return (preg_replace('/\.$/', '', $netmask));
1856 }
1858 return ($netmask);
1859 }
1862 /*! \brief Return the number of set bits in the netmask
1863 *
1864 * For a given subnetmask (for example 255.255.255.0) this returns
1865 * the number of set bits.
1866 *
1867 * Example:
1868 * \code
1869 * $bits = netmask_to_bits('255.255.255.0') # Returns 24
1870 * $bits = netmask_to_bits('255.255.254.0') # Returns 23
1871 * \endcode
1872 *
1873 * Be aware of the fact that the function does not check
1874 * if the given subnet mask is actually valid. For example:
1875 * Bad examples:
1876 * \code
1877 * $bits = netmask_to_bits('255.0.0.255') # Returns 16
1878 * $bits = netmask_to_bits('255.255.0.255') # Returns 24
1879 * \endcode
1880 */
1881 function netmask_to_bits($netmask)
1882 {
1883 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1884 $res= 0;
1886 for ($n= 0; $n<4; $n++){
1887 $start= 255;
1888 $name= "nm$n";
1890 for ($i= 0; $i<8; $i++){
1891 if ($start == (int)($$name)){
1892 $res+= 8 - $i;
1893 break;
1894 }
1895 $start-= pow(2,$i);
1896 }
1897 }
1899 return ($res);
1900 }
1903 function recurse($rule, $variables)
1904 {
1905 $result= array();
1907 if (!count($variables)){
1908 return array($rule);
1909 }
1911 reset($variables);
1912 $key= key($variables);
1913 $val= current($variables);
1914 unset ($variables[$key]);
1916 foreach($val as $possibility){
1917 $nrule= str_replace("{$key}", $possibility, $rule);
1918 $result= array_merge($result, recurse($nrule, $variables));
1919 }
1921 return ($result);
1922 }
1925 function expand_id($rule, $attributes)
1926 {
1927 /* Check for id rule */
1928 if(preg_match('/^id(:|#)\d+$/',$rule)){
1929 return (array("\{$rule}"));
1930 }
1932 /* Check for clean attribute */
1933 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1934 $rule= preg_replace('/^%/', '', $rule);
1935 $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
1936 return (array($val));
1937 }
1939 /* Check for attribute with parameters */
1940 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1941 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1942 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1943 $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
1944 $start= preg_replace ('/-.*$/', '', $param);
1945 $stop = preg_replace ('/^[^-]+-/', '', $param);
1947 /* Assemble results */
1948 $result= array();
1949 for ($i= $start; $i<= $stop; $i++){
1950 $result[]= substr($val, 0, $i);
1951 }
1952 return ($result);
1953 }
1955 echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
1956 return (array($rule));
1957 }
1960 function gen_uids($rule, $attributes)
1961 {
1962 global $config;
1964 /* Search for keys and fill the variables array with all
1965 possible values for that key. */
1966 $part= "";
1967 $trigger= false;
1968 $stripped= "";
1969 $variables= array();
1971 for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
1973 if ($rule[$pos] == "{" ){
1974 $trigger= true;
1975 $part= "";
1976 continue;
1977 }
1979 if ($rule[$pos] == "}" ){
1980 $variables[$pos]= expand_id($part, $attributes);
1981 $stripped.= "{".$pos."}";
1982 $trigger= false;
1983 continue;
1984 }
1986 if ($trigger){
1987 $part.= $rule[$pos];
1988 } else {
1989 $stripped.= $rule[$pos];
1990 }
1991 }
1993 /* Recurse through all possible combinations */
1994 $proposed= recurse($stripped, $variables);
1996 /* Get list of used ID's */
1997 $used= array();
1998 $ldap= $config->get_ldap_link();
1999 $ldap->cd($config->current['BASE']);
2000 $ldap->search('(uid=*)');
2002 while($attrs= $ldap->fetch()){
2003 $used[]= $attrs['uid'][0];
2004 }
2006 /* Remove used uids and watch out for id tags */
2007 $ret= array();
2008 foreach($proposed as $uid){
2010 /* Check for id tag and modify uid if needed */
2011 if(preg_match('/\{id:\d+}/',$uid)){
2012 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
2014 for ($i= 0, $p= pow(10,$size); $i < $p; $i++){
2015 $number= sprintf("%0".$size."d", $i);
2016 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
2017 if (!in_array($res, $used)){
2018 $uid= $res;
2019 break;
2020 }
2021 }
2022 }
2024 if(preg_match('/\{id#\d+}/',$uid)){
2025 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
2027 while (true){
2028 mt_srand((double) microtime()*1000000);
2029 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
2030 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
2031 if (!in_array($res, $used)){
2032 $uid= $res;
2033 break;
2034 }
2035 }
2036 }
2038 /* Don't assign used ones */
2039 if (!in_array($uid, $used)){
2040 /* Add uid, but remove {} first. These are invalid anyway. */
2041 $ret[]= preg_replace('/[{}]/', '', $uid);
2042 }
2043 }
2045 return(array_unique($ret));
2046 }
2048 /*! \brief Convert various data sizes to bytes
2049 *
2050 * Given a certain value in the format n(g|m|k), where n
2051 * is a value and (g|m|k) stands for Gigabyte, Megabyte and Kilobyte
2052 * this function returns the byte value.
2053 *
2054 * \param string 'value' a value in the above specified format
2055 * \return a byte value or the original value if specified string is simply
2056 * a numeric value
2057 *
2058 */
2059 function to_byte($value) {
2060 $value= strtolower(trim($value));
2062 if(!is_numeric(substr($value, -1))) {
2064 switch(substr($value, -1)) {
2065 case 'g':
2066 $mult= 1073741824;
2067 break;
2068 case 'm':
2069 $mult= 1048576;
2070 break;
2071 case 'k':
2072 $mult= 1024;
2073 break;
2074 }
2076 return ($mult * (int)substr($value, 0, -1));
2077 } else {
2078 return $value;
2079 }
2080 }
2082 /*! \brief Check if a value exists in an array (case-insensitive)
2083 *
2084 * This is just as http://php.net/in_array except that the comparison
2085 * is case-insensitive.
2086 *
2087 * \param string 'value' needle
2088 * \param array 'items' haystack
2089 */
2090 function in_array_ics($value, $items)
2091 {
2092 return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
2093 }
2095 /*! \brief Generate a clickable alphabet */
2096 function generate_alphabet($count= 10)
2097 {
2098 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
2099 $alphabet= "";
2100 $c= 0;
2102 /* Fill cells with charaters */
2103 for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
2104 if ($c == 0){
2105 $alphabet.= "<tr>";
2106 }
2108 $ch = mb_substr($characters, $i, 1, "UTF8");
2109 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
2110 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
2112 if ($c++ == $count){
2113 $alphabet.= "</tr>";
2114 $c= 0;
2115 }
2116 }
2118 /* Fill remaining cells */
2119 while ($c++ <= $count){
2120 $alphabet.= "<td> </td>";
2121 }
2123 return ($alphabet);
2124 }
2126 function validate($string)
2127 {
2128 return (strip_tags(str_replace('\0', '', $string)));
2129 }
2131 /*! \brief Get the current gosa version */
2132 function get_gosa_version()
2133 {
2134 global $svn_revision, $svn_path;
2136 /* Extract informations */
2137 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
2139 /* Release or development? */
2140 if (preg_match('%/gosa/trunk/%', $svn_path)){
2141 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
2142 } else {
2143 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
2144 return (sprintf(_("GOsa $release"), $revision));
2145 }
2146 }
2148 /*! \brief Recursively delete a path in the file system
2149 *
2150 * Will delete the given path and all its files recursively.
2151 * Can also follow links if told so.
2152 *
2153 * \param string 'path'
2154 * \param boolean 'followLinks' TRUE to follow links, FALSE (default)
2155 * for not following links
2156 */
2157 function rmdirRecursive($path, $followLinks=false) {
2158 $dir= opendir($path);
2159 while($entry= readdir($dir)) {
2160 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
2161 unlink($path."/".$entry);
2162 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
2163 rmdirRecursive($path."/".$entry);
2164 }
2165 }
2166 closedir($dir);
2167 return rmdir($path);
2168 }
2170 /*! \brief Get directory content information
2171 *
2172 * Returns the content of a directory as an array in an
2173 * ascended sorted manner.
2174 *
2175 * \param string 'path'
2176 * \param boolean weither to sort the content descending.
2177 */
2178 function scan_directory($path,$sort_desc=false)
2179 {
2180 $ret = false;
2182 /* is this a dir ? */
2183 if(is_dir($path)) {
2185 /* is this path a readable one */
2186 if(is_readable($path)){
2188 /* Get contents and write it into an array */
2189 $ret = array();
2191 $dir = opendir($path);
2193 /* Is this a correct result ?*/
2194 if($dir){
2195 while($fp = readdir($dir))
2196 $ret[]= $fp;
2197 }
2198 }
2199 }
2200 /* Sort array ascending , like scandir */
2201 sort($ret);
2203 /* Sort descending if parameter is sort_desc is set */
2204 if($sort_desc) {
2205 $ret = array_reverse($ret);
2206 }
2208 return($ret);
2209 }
2211 /*! \brief Clean the smarty compile dir */
2212 function clean_smarty_compile_dir($directory)
2213 {
2214 global $svn_revision;
2216 if(is_dir($directory) && is_readable($directory)) {
2217 // Set revision filename to REVISION
2218 $revision_file= $directory."/REVISION";
2220 /* Is there a stamp containing the current revision? */
2221 if(!file_exists($revision_file)) {
2222 // create revision file
2223 create_revision($revision_file, $svn_revision);
2224 } else {
2225 # check for "$config->...['CONFIG']/revision" and the
2226 # contents should match the revision number
2227 if(!compare_revision($revision_file, $svn_revision)){
2228 // If revision differs, clean compile directory
2229 foreach(scan_directory($directory) as $file) {
2230 if(($file==".")||($file=="..")) continue;
2231 if( is_file($directory."/".$file) &&
2232 is_writable($directory."/".$file)) {
2233 // delete file
2234 if(!unlink($directory."/".$file)) {
2235 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
2236 // This should never be reached
2237 }
2238 } elseif(is_dir($directory."/".$file) &&
2239 is_writable($directory."/".$file)) {
2240 // Just recursively delete it
2241 rmdirRecursive($directory."/".$file);
2242 }
2243 }
2244 // We should now create a fresh revision file
2245 clean_smarty_compile_dir($directory);
2246 } else {
2247 // Revision matches, nothing to do
2248 }
2249 }
2250 } else {
2251 // Smarty compile dir is not accessible
2252 // (Smarty will warn about this)
2253 }
2254 }
2257 function create_revision($revision_file, $revision)
2258 {
2259 $result= false;
2261 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2262 if($fh= fopen($revision_file, "w")) {
2263 if(fwrite($fh, $revision)) {
2264 $result= true;
2265 }
2266 }
2267 fclose($fh);
2268 } else {
2269 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2270 }
2272 return $result;
2273 }
2276 function compare_revision($revision_file, $revision)
2277 {
2278 // false means revision differs
2279 $result= false;
2281 if(file_exists($revision_file) && is_readable($revision_file)) {
2282 // Open file
2283 if($fh= fopen($revision_file, "r")) {
2284 // Compare File contents with current revision
2285 if($revision == fread($fh, filesize($revision_file))) {
2286 $result= true;
2287 }
2288 } else {
2289 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2290 }
2291 // Close file
2292 fclose($fh);
2293 }
2295 return $result;
2296 }
2298 /*! \brief Return HTML for a progressbar
2299 *
2300 * \code
2301 * $smarty->assign("installprogress", progressbar($current_progress_in_percent),100,15,true);
2302 * \endcode
2303 *
2304 * \param int 'percentage' Value to display
2305 * \param int 'width' width of the resulting output
2306 * \param int 'height' height of the resulting output
2307 * \param boolean 'showvalue' weither to show the percentage in the progressbar or not
2308 * */
2309 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2310 {
2311 $str = ""; // Our return value will be saved in this var
2313 $color = dechex($percentage+150);
2314 $color2 = dechex(150 - $percentage);
2315 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2317 $progress = (int)(($percentage /100)*$width);
2319 /* If theres a better solution for this, use it... */
2320 $str = "\n <div style=\" width:".($width)."px; ";
2321 $str.= "\n height:".($height)."px; ";
2322 $str.= "\n background-color:#000000; ";
2323 $str.= "\n padding:1px;\" > ";
2325 $str.= "\n <div style=\" width:".($width)."px; ";
2326 $str.= "\n background-color:#$bgcolor; ";
2327 $str.= "\n height:".($height)."px;\" > ";
2329 if(($height >10)&&($showvalue)){
2330 $str.= "\n <font style=\"font-size:".($height-2)."px; ";
2331 $str.= "\n color:#FF0000; align:middle; ";
2332 $str.= "\n padding-left:".((int)(($width*0.4)))."px; \"> ";
2333 $str.= "\n <b>".$percentage."%</b> ";
2334 $str.= "\n </font> ";
2335 }
2337 $str.= "\n <div style=\" width:".$progress."px; ";
2338 $str.= "\n height:".$height."px; ";
2339 $str.= "\n background-color:#".$color2.$color2.$color."; \" >";
2340 $str.= "\n </div>";
2341 $str.= "\n </div>";
2342 $str.= "\n </div>";
2344 return($str);
2345 }
2347 /*! \brief Lookup a key in an array case-insensitive
2348 *
2349 * Given an associative array this can lookup the value of
2350 * a certain key, regardless of the case.
2351 *
2352 * \code
2353 * $items = array ('FOO' => 'blub', 'bar' => 'blub');
2354 * array_key_ics('foo', $items); # Returns 'blub'
2355 * array_key_ics('BAR', $items); # Returns 'blub'
2356 * \endcode
2357 *
2358 * \param string 'key' needle
2359 * \param array 'items' haystack
2360 */
2361 function array_key_ics($ikey, $items)
2362 {
2363 $tmp= array_change_key_case($items, CASE_LOWER);
2364 $ikey= strtolower($ikey);
2365 if (isset($tmp[$ikey])){
2366 return($tmp[$ikey]);
2367 }
2369 return ('');
2370 }
2372 /*! \brief Determine if two arrays are different
2373 *
2374 * \param array 'src'
2375 * \param array 'dst'
2376 * \return boolean TRUE or FALSE
2377 * */
2378 function array_differs($src, $dst)
2379 {
2380 /* If the count is differing, the arrays differ */
2381 if (count ($src) != count ($dst)){
2382 return (TRUE);
2383 }
2385 return (count(array_diff($src, $dst)) != 0);
2386 }
2389 function saveFilter($a_filter, $values)
2390 {
2391 if (isset($_POST['regexit'])){
2392 $a_filter["regex"]= $_POST['regexit'];
2394 foreach($values as $type){
2395 if (isset($_POST[$type])) {
2396 $a_filter[$type]= "checked";
2397 } else {
2398 $a_filter[$type]= "";
2399 }
2400 }
2401 }
2403 /* React on alphabet links if needed */
2404 if (isset($_GET['search'])){
2405 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2406 if ($s == "**"){
2407 $s= "*";
2408 }
2409 $a_filter['regex']= $s;
2410 }
2412 return ($a_filter);
2413 }
2416 /*! \brief Escape all LDAP filter relevant characters */
2417 function normalizeLdap($input)
2418 {
2419 return (addcslashes($input, '()|'));
2420 }
2423 /*! \brief Returns the difference between to microtime() results in float */
2424 function get_MicroTimeDiff($start , $stop)
2425 {
2426 $a = split("\ ",$start);
2427 $b = split("\ ",$stop);
2429 $secs = $b[1] - $a[1];
2430 $msecs= $b[0] - $a[0];
2432 $ret = (float) ($secs+ $msecs);
2433 return($ret);
2434 }
2436 /*! \brief Return the gosa base directory */
2437 function get_base_dir()
2438 {
2439 global $BASE_DIR;
2441 return $BASE_DIR;
2442 }
2444 /*! \brief Test weither we are allowed to read the object */
2445 function obj_is_readable($dn, $object, $attribute)
2446 {
2447 global $ui;
2449 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2450 }
2452 /*! \brief Test weither we are allowed to change the object */
2453 function obj_is_writable($dn, $object, $attribute)
2454 {
2455 global $ui;
2457 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2458 }
2460 /*! \brief Explode a DN into its parts
2461 *
2462 * Similar to explode (http://php.net/explode), but a bit more specific
2463 * for the needs when splitting, exploding LDAP DNs.
2464 *
2465 * \param string 'dn' the DN to split
2466 * \param config-object a config object. only neeeded if DN shall be verified in the LDAP
2467 * \param boolean verify_in_ldap check weither DN is valid
2468 *
2469 */
2470 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2471 {
2472 /* Initialize variables */
2473 $ret = array("count" => 0); // Set count to 0
2474 $next = true; // if false, then skip next loops and return
2475 $cnt = 0; // Current number of loops
2476 $max = 100; // Just for security, prevent looops
2477 $ldap = NULL; // To check if created result a valid
2478 $keep = ""; // save last failed parse string
2480 /* Check each parsed dn in ldap ? */
2481 if($config!==NULL && $verify_in_ldap){
2482 $ldap = $config->get_ldap_link();
2483 }
2485 /* Lets start */
2486 $called = false;
2487 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2489 $cnt ++;
2490 if(!preg_match("/,/",$dn)){
2491 $next = false;
2492 }
2493 $object = preg_replace("/[,].*$/","",$dn);
2494 $dn = preg_replace("/^[^,]+,/","",$dn);
2496 $called = true;
2498 /* Check if current dn is valid */
2499 if($ldap!==NULL){
2500 $ldap->cd($dn);
2501 $ldap->cat($dn,array("dn"));
2502 if($ldap->count()){
2503 $ret[] = $keep.$object;
2504 $keep = "";
2505 }else{
2506 $keep .= $object.",";
2507 }
2508 }else{
2509 $ret[] = $keep.$object;
2510 $keep = "";
2511 }
2512 }
2514 /* No dn was posted */
2515 if($cnt == 0 && !empty($dn)){
2516 $ret[] = $dn;
2517 }
2519 /* Append the rest */
2520 $test = $keep.$dn;
2521 if($called && !empty($test)){
2522 $ret[] = $keep.$dn;
2523 }
2524 $ret['count'] = count($ret) - 1;
2526 return($ret);
2527 }
2530 function get_base_from_hook($dn, $attrib)
2531 {
2532 global $config;
2534 if ($config->get_cfg_value("baseIdHook") != ""){
2536 /* Call hook script - if present */
2537 $command= $config->get_cfg_value("baseIdHook");
2539 if ($command != ""){
2540 $command.= " '".LDAP::fix($dn)."' $attrib";
2541 if (check_command($command)){
2542 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2543 exec($command, $output);
2544 if (preg_match("/^[0-9]+$/", $output[0])){
2545 return ($output[0]);
2546 } else {
2547 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2548 return ($config->get_cfg_value("uidNumberBase"));
2549 }
2550 } else {
2551 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2552 return ($config->get_cfg_value("uidNumberBase"));
2553 }
2555 } else {
2557 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2558 return ($config->get_cfg_value("uidNumberBase"));
2560 }
2561 }
2562 }
2564 /*! \brief Check if schema version matches the requirements */
2565 function check_schema_version($class, $version)
2566 {
2567 return preg_match("/\(v$version\)/", $class['DESC']);
2568 }
2570 /*! \brief Check if LDAP schema matches the requirements */
2571 function check_schema($cfg,$rfc2307bis = FALSE)
2572 {
2573 $messages= array();
2575 /* Get objectclasses */
2576 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2577 $objectclasses = $ldap->get_objectclasses();
2578 if(count($objectclasses) == 0){
2579 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2580 }
2582 /* This is the default block used for each entry.
2583 * to avoid unset indexes.
2584 */
2585 $def_check = array("REQUIRED_VERSION" => "0",
2586 "SCHEMA_FILES" => array(),
2587 "CLASSES_REQUIRED" => array(),
2588 "STATUS" => FALSE,
2589 "IS_MUST_HAVE" => FALSE,
2590 "MSG" => "",
2591 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2593 /* The gosa base schema */
2594 $checks['gosaObject'] = $def_check;
2595 $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2596 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2597 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2598 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2600 /* GOsa Account class */
2601 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.1";
2602 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2603 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2604 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2605 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2607 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2608 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2609 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2610 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2611 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2612 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2614 /* Some other checks */
2615 foreach(array(
2616 "gosaCacheEntry" => array("version" => "2.6.1"),
2617 "gosaDepartment" => array("version" => "2.6.1"),
2618 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2619 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2620 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2621 "gosaUserTemplate" => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2622 "gosaMailAccount" => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2623 "gosaProxyAccount" => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2624 "gosaApplication" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2625 "gosaApplicationGroup" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2626 "GOhard" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2627 "gotoTerminal" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2628 "goServer" => array("version" => "2.6.1","class" => "server","file" => "goserver.schema"),
2629 "goTerminalServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2630 "goShareServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2631 "goNtpServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2632 "goSyslogServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2633 "goLdapServer" => array("version" => "2.6.1"),
2634 "goCupsServer" => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2635 "goImapServer" => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2636 "goKrbServer" => array("version" => "2.6.1"),
2637 "goFaxServer" => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2638 ) as $name => $values){
2640 $checks[$name] = $def_check;
2641 if(isset($values['version'])){
2642 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2643 }
2644 if(isset($values['file'])){
2645 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2646 }
2647 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2648 }
2649 foreach($checks as $name => $value){
2650 foreach($value['CLASSES_REQUIRED'] as $class){
2652 if(!isset($objectclasses[$name])){
2653 $checks[$name]['STATUS'] = FALSE;
2654 if($value['IS_MUST_HAVE']){
2655 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2656 }else{
2657 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2658 }
2659 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2660 $checks[$name]['STATUS'] = FALSE;
2662 if($value['IS_MUST_HAVE']){
2663 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2664 }else{
2665 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2666 }
2667 }else{
2668 $checks[$name]['STATUS'] = TRUE;
2669 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2670 }
2671 }
2672 }
2674 $tmp = $objectclasses;
2676 /* The gosa base schema */
2677 $checks['posixGroup'] = $def_check;
2678 $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2679 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2680 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2681 $checks['posixGroup']['STATUS'] = TRUE;
2682 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2683 $checks['posixGroup']['MSG'] = "";
2684 $checks['posixGroup']['INFO'] = "";
2686 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2687 if(isset($tmp['posixGroup'])){
2689 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2690 $checks['posixGroup']['STATUS'] = FALSE;
2691 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2692 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2693 }
2694 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2695 $checks['posixGroup']['STATUS'] = FALSE;
2696 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2697 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2698 }
2699 }
2701 return($checks);
2702 }
2705 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2706 {
2707 $tmp = array(
2708 "de_DE" => "German",
2709 "fr_FR" => "French",
2710 "it_IT" => "Italian",
2711 "es_ES" => "Spanish",
2712 "en_US" => "English",
2713 "nl_NL" => "Dutch",
2714 "pl_PL" => "Polish",
2715 #"sv_SE" => "Swedish",
2716 "zh_CN" => "Chinese",
2717 "vi_VN" => "Vietnamese",
2718 "ru_RU" => "Russian");
2720 $tmp2= array(
2721 "de_DE" => _("German"),
2722 "fr_FR" => _("French"),
2723 "it_IT" => _("Italian"),
2724 "es_ES" => _("Spanish"),
2725 "en_US" => _("English"),
2726 "nl_NL" => _("Dutch"),
2727 "pl_PL" => _("Polish"),
2728 #"sv_SE" => _("Swedish"),
2729 "zh_CN" => _("Chinese"),
2730 "vi_VN" => _("Vietnamese"),
2731 "ru_RU" => _("Russian"));
2733 $ret = array();
2734 if($languages_in_own_language){
2736 $old_lang = setlocale(LC_ALL, 0);
2738 /* If the locale wasn't correclty set before, there may be an incorrect
2739 locale returned. Something like this:
2740 C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2741 Extract the locale name from this string and use it to restore old locale.
2742 */
2743 if(preg_match("/LC_CTYPE/",$old_lang)){
2744 $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2745 }
2747 foreach($tmp as $key => $name){
2748 $lang = $key.".UTF-8";
2749 setlocale(LC_ALL, $lang);
2750 if($strip_region_tag){
2751 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2752 }else{
2753 $ret[$key] = _($name)." (".$tmp2[$key].")";
2754 }
2755 }
2756 setlocale(LC_ALL, $old_lang);
2757 }else{
2758 foreach($tmp as $key => $name){
2759 if($strip_region_tag){
2760 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2761 }else{
2762 $ret[$key] = _($name);
2763 }
2764 }
2765 }
2766 return($ret);
2767 }
2770 /*! \brief Returns contents of the given POST variable and check magic quotes settings
2771 *
2772 * Depending on the magic quotes settings this returns a stripclashed'ed version of
2773 * a certain POST variable.
2774 *
2775 * \param string 'name' the POST var to return ($_POST[$name])
2776 * \return string
2777 * */
2778 function get_post($name)
2779 {
2780 if(!isset($_POST[$name])){
2781 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2782 return(FALSE);
2783 }
2784 if(get_magic_quotes_gpc()){
2785 return(stripcslashes($_POST[$name]));
2786 }else{
2787 return($_POST[$name]);
2788 }
2789 }
2792 /*! \brief Return class name in correct case */
2793 function get_correct_class_name($cls)
2794 {
2795 global $class_mapping;
2796 if(isset($class_mapping) && is_array($class_mapping)){
2797 foreach($class_mapping as $class => $file){
2798 if(preg_match("/^".$cls."$/i",$class)){
2799 return($class);
2800 }
2801 }
2802 }
2803 return(FALSE);
2804 }
2807 /*! \brief Change the password of a given DN
2808 *
2809 * Change the password of a given DN with the specified hash.
2810 *
2811 * \param string 'dn' the DN whose password shall be changed
2812 * \param string 'password' the password
2813 * \param int mode
2814 * \param string 'hash' which hash to use to encrypt it, default is empty
2815 * for cleartext storage.
2816 * \return boolean TRUE on success FALSE on error
2817 */
2818 function change_password ($dn, $password, $mode=0, $hash= "")
2819 {
2820 global $config;
2821 $newpass= "";
2823 /* Convert to lower. Methods are lowercase */
2824 $hash= strtolower($hash);
2826 // Get all available encryption Methods
2828 // NON STATIC CALL :)
2829 $methods = new passwordMethod(session::get('config'));
2830 $available = $methods->get_available_methods();
2832 // read current password entry for $dn, to detect the encryption Method
2833 $ldap = $config->get_ldap_link();
2834 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2835 $attrs = $ldap->fetch ();
2837 /* Is ensure that clear passwords will stay clear */
2838 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2839 $hash = "clear";
2840 }
2842 // Detect the encryption Method
2843 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2845 /* Check for supported algorithm */
2846 mt_srand((double) microtime()*1000000);
2848 /* Extract used hash */
2849 if ($hash == ""){
2850 $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2851 } else {
2852 $test = new $available[$hash]($config,$dn);
2853 $test->set_hash($hash);
2854 }
2856 } else {
2857 // User MD5 by default
2858 $hash= "md5";
2859 $test = new $available['md5']($config);
2860 }
2862 if($test instanceOf passwordMethod){
2864 $deactivated = $test->is_locked($config,$dn);
2866 /* Feed password backends with information */
2867 $test->dn= $dn;
2868 $test->attrs= $attrs;
2869 $newpass= $test->generate_hash($password);
2871 // Update shadow timestamp?
2872 if (isset($attrs["shadowLastChange"][0])){
2873 $shadow= (int)(date("U") / 86400);
2874 } else {
2875 $shadow= 0;
2876 }
2878 // Write back modified entry
2879 $ldap->cd($dn);
2880 $attrs= array();
2882 // Not for groups
2883 if ($mode == 0){
2885 if ($shadow != 0){
2886 $attrs['shadowLastChange']= $shadow;
2887 }
2889 // Create SMB Password
2890 $attrs= generate_smb_nt_hash($password);
2891 }
2893 $attrs['userPassword']= array();
2894 $attrs['userPassword']= $newpass;
2896 $ldap->modify($attrs);
2898 /* Read ! if user was deactivated */
2899 if($deactivated){
2900 $test->lock_account($config,$dn);
2901 }
2903 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2905 if (!$ldap->success()) {
2906 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2907 } else {
2909 /* Run backend method for change/create */
2910 if(!$test->set_password($password)){
2911 return(FALSE);
2912 }
2914 /* Find postmodify entries for this class */
2915 $command= $config->search("password", "POSTMODIFY",array('menu'));
2917 if ($command != ""){
2918 /* Walk through attribute list */
2919 $command= preg_replace("/%userPassword/", $password, $command);
2920 $command= preg_replace("/%dn/", $dn, $command);
2922 if (check_command($command)){
2923 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2924 exec($command);
2925 } else {
2926 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2927 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2928 }
2929 }
2930 }
2931 return(TRUE);
2932 }
2933 }
2936 /*! \brief Generate samba hashes
2937 *
2938 * Given a certain password this constructs an array like
2939 * array['sambaLMPassword'] etc.
2940 *
2941 * \param string 'password'
2942 * \return array contains several keys for lmPassword, ntPassword, pwdLastSet, etc. depending
2943 * on the samba version
2944 */
2945 function generate_smb_nt_hash($password)
2946 {
2947 global $config;
2949 # Try to use gosa-si?
2950 if ($config->get_cfg_value("gosaSupportURI") != ""){
2951 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2952 if (isset($res['XML']['HASH'])){
2953 $hash= $res['XML']['HASH'];
2954 } else {
2955 $hash= "";
2956 }
2958 if ($hash == "") {
2959 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2960 return ("");
2961 }
2962 } else {
2963 $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
2964 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2966 exec($tmp, $ar);
2967 flush();
2968 reset($ar);
2969 $hash= current($ar);
2971 if ($hash == "") {
2972 msg_dialog::display(_("Configuration error"), sprintf(_("Cannot generate samba hash: running '%s' failed, check the 'sambaHashHook'!"),$config->get_cfg_value('sambaHashHook')), ERROR_DIALOG);
2973 return ("");
2974 }
2975 }
2977 list($lm,$nt)= split (":", trim($hash));
2979 if ($config->get_cfg_value("sambaversion") == 3) {
2980 $attrs['sambaLMPassword']= $lm;
2981 $attrs['sambaNTPassword']= $nt;
2982 $attrs['sambaPwdLastSet']= date('U');
2983 $attrs['sambaBadPasswordCount']= "0";
2984 $attrs['sambaBadPasswordTime']= "0";
2985 } else {
2986 $attrs['lmPassword']= $lm;
2987 $attrs['ntPassword']= $nt;
2988 $attrs['pwdLastSet']= date('U');
2989 }
2990 return($attrs);
2991 }
2993 /*! \brief Get the Change Sequence Number of a certain DN
2994 *
2995 * To verify if a given object has been changed outside of Gosa
2996 * in the meanwhile, this function can be used to get the entryCSN
2997 * from the LDAP directory. It uses the attribute as configured
2998 * in modificationDetectionAttribute
2999 *
3000 * \param string 'dn'
3001 * \return either the result or "" in any other case
3002 */
3003 function getEntryCSN($dn)
3004 {
3005 global $config;
3006 if(empty($dn) || !is_object($config)){
3007 return("");
3008 }
3010 /* Get attribute that we should use as serial number */
3011 $attr= $config->get_cfg_value("modificationDetectionAttribute");
3012 if($attr != ""){
3013 $ldap = $config->get_ldap_link();
3014 $ldap->cat($dn,array($attr));
3015 $csn = $ldap->fetch();
3016 if(isset($csn[$attr][0])){
3017 return($csn[$attr][0]);
3018 }
3019 }
3020 return("");
3021 }
3024 /*! \brief Add (a) given objectClass(es) to an attrs entry
3025 *
3026 * The function adds the specified objectClass(es) to the given
3027 * attrs entry.
3028 *
3029 * \param mixed 'classes' Either a single objectClass or several objectClasses
3030 * as an array
3031 * \param array 'attrs' The attrs array to be modified.
3032 *
3033 * */
3034 function add_objectClass($classes, &$attrs)
3035 {
3036 if (is_array($classes)){
3037 $list= $classes;
3038 } else {
3039 $list= array($classes);
3040 }
3042 foreach ($list as $class){
3043 $attrs['objectClass'][]= $class;
3044 }
3045 }
3048 /*! \brief Removes a given objectClass from the attrs entry
3049 *
3050 * Similar to add_objectClass, except that it removes the given
3051 * objectClasses. See it for the params.
3052 * */
3053 function remove_objectClass($classes, &$attrs)
3054 {
3055 if (isset($attrs['objectClass'])){
3056 /* Array? */
3057 if (is_array($classes)){
3058 $list= $classes;
3059 } else {
3060 $list= array($classes);
3061 }
3063 $tmp= array();
3064 foreach ($attrs['objectClass'] as $oc) {
3065 foreach ($list as $class){
3066 if (strtolower($oc) != strtolower($class)){
3067 $tmp[]= $oc;
3068 }
3069 }
3070 }
3071 $attrs['objectClass']= $tmp;
3072 }
3073 }
3075 /*! \brief Initialize a file download with given content, name and data type.
3076 * \param string data The content to send.
3077 * \param string name The name of the file.
3078 * \param string type The content identifier, default value is "application/octet-stream";
3079 */
3080 function send_binary_content($data,$name,$type = "application/octet-stream")
3081 {
3082 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
3083 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
3084 header("Cache-Control: no-cache");
3085 header("Pragma: no-cache");
3086 header("Cache-Control: post-check=0, pre-check=0");
3087 header("Content-type: ".$type."");
3089 $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
3091 /* Strip name if it is a complete path */
3092 if (preg_match ("/\//", $name)) {
3093 $name= basename($name);
3094 }
3096 /* force download dialog */
3097 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
3098 header('Content-Disposition: filename="'.$name.'"');
3099 } else {
3100 header('Content-Disposition: attachment; filename="'.$name.'"');
3101 }
3103 echo $data;
3104 exit();
3105 }
3108 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
3109 {
3110 if(is_string($str)){
3111 return(htmlentities($str,$type,$charset));
3112 }elseif(is_array($str)){
3113 foreach($str as $name => $value){
3114 $str[$name] = reverse_html_entities($value,$type,$charset);
3115 }
3116 }
3117 return($str);
3118 }
3121 /*! \brief Encode special string characters so we can use the string in \
3122 HTML output, without breaking quotes.
3123 \param string The String we want to encode.
3124 \return string The encoded String
3125 */
3126 function xmlentities($str)
3127 {
3128 if(is_string($str)){
3130 static $asc2uni= array();
3131 if (!count($asc2uni)){
3132 for($i=128;$i<256;$i++){
3133 # $asc2uni[chr($i)] = "&#x".dechex($i).";";
3134 }
3135 }
3137 $str = str_replace("&", "&", $str);
3138 $str = str_replace("<", "<", $str);
3139 $str = str_replace(">", ">", $str);
3140 $str = str_replace("'", "'", $str);
3141 $str = str_replace("\"", """, $str);
3142 $str = str_replace("\r", "", $str);
3143 $str = strtr($str,$asc2uni);
3144 return $str;
3145 }elseif(is_array($str)){
3146 foreach($str as $name => $value){
3147 $str[$name] = xmlentities($value);
3148 }
3149 }
3150 return($str);
3151 }
3154 /*! \brief Updates all accessTo attributes from a given value to a new one.
3155 For example if a host is renamed.
3156 \param String $from The source accessTo name.
3157 \param String $to The destination accessTo name.
3158 */
3159 function update_accessTo($from,$to)
3160 {
3161 global $config;
3162 $ldap = $config->get_ldap_link();
3163 $ldap->cd($config->current['BASE']);
3164 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
3165 while($attrs = $ldap->fetch()){
3166 $new_attrs = array("accessTo" => array());
3167 $dn = $attrs['dn'];
3168 for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
3169 $new_attrs['objectClass'][] = $attrs['objectClass'][$i];
3170 }
3171 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
3172 if($attrs['accessTo'][$i] == $from){
3173 if(!empty($to)){
3174 $new_attrs['accessTo'][] = $to;
3175 }
3176 }else{
3177 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
3178 }
3179 }
3180 $ldap->cd($dn);
3181 $ldap->modify($new_attrs);
3182 if (!$ldap->success()){
3183 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
3184 }
3185 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
3186 }
3187 }
3189 /*! \brief Returns a random char */
3190 function get_random_char () {
3191 $randno = rand (0, 63);
3192 if ($randno < 12) {
3193 return (chr ($randno + 46)); // Digits, '/' and '.'
3194 } else if ($randno < 38) {
3195 return (chr ($randno + 53)); // Uppercase
3196 } else {
3197 return (chr ($randno + 59)); // Lowercase
3198 }
3199 }
3202 function cred_encrypt($input, $password) {
3204 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3205 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3207 return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
3209 }
3211 function cred_decrypt($input,$password) {
3212 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
3213 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
3215 return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
3216 }
3218 function get_object_info()
3219 {
3220 return(session::get('objectinfo'));
3221 }
3223 function set_object_info($str = "")
3224 {
3225 session::set('objectinfo',$str);
3226 }
3228 /*! \brief Compare two strings similar as an LDAP search would do it
3229 *
3230 * This function compares a string similar as a LDAP equality match
3231 * would do. It does so by replacing any occurence of a * with a
3232 * regex pattern and test it with preg_match. The default mapping is '.*'
3233 * but the test can be extended by changing that mapping, so that the asterisk
3234 * can stand for a certain range of chars for example.
3235 *
3236 * Example:
3237 * \code
3238 * ldap_equality_check('halut', '*'); # true
3239 * ldap_equality_check('halut/1.2.3', 'halut/*'); # true
3240 * ldap_equality_check('halut/1.2.3', 'hal\*\/1.2.3'); # true
3241 * \endcode
3242 *
3243 * */
3244 function ldap_equality_check($string1, $string2, $mapping=".*", $case_sensitive=TRUE) {
3245 if (!(strstr($string2, '*')) && ($string1 == $string2)) {
3246 return TRUE;
3247 }
3249 /* Set modifier string to i if case insensitivity is requested */
3250 $modifier = $case_sensitive ? "" : "i";
3251 $string2 = preg_quote($string2, "/");
3252 $string2 = str_replace('\*', $mapping, $string2);
3254 $result = preg_match('/' . $string2 . '$/' . $modifier, $string1);
3255 return $result;
3256 }
3258 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3259 ?>