c630642e2b66903bee9c9fdf0874d0b66b0cf871
1 <?php
2 /*
3 * This code is part of GOsa (http://www.gosa-project.org)
4 * Copyright (C) 2003-2008 GONICUS GmbH
5 *
6 * ID: $$Id: functions.inc 13100 2008-12-01 14:07:48Z hickert $$
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 */
23 /* Configuration file location */
25 /* Allow setting the config patj in the apache configuration
26 e.g. SetEnv CONFIG_FILE /etc/path
27 */
28 if(!isset($_SERVER['CONFIG_DIR'])){
29 define ("CONFIG_DIR", "/etc/gosa");
30 }else{
31 define ("CONFIG_DIR",$_SERVER['CONFIG_DIR']);
32 }
34 /* Allow setting the config file in the apache configuration
35 e.g. SetEnv CONFIG_FILE gosa.conf.2.6
36 */
37 if(!isset($_SERVER['CONFIG_FILE'])){
38 define ("CONFIG_FILE", "gosa.conf");
39 }else{
40 define ("CONFIG_FILE",$_SERVER['CONFIG_FILE']);
41 }
43 define ("CONFIG_TEMPLATE_DIR", "../contrib");
44 define ("TEMP_DIR","/var/cache/gosa/tmp");
46 /* Define get_list flags */
47 define("GL_NONE", 0);
48 define("GL_SUBSEARCH", 1);
49 define("GL_SIZELIMIT", 2);
50 define("GL_CONVERT", 4);
51 define("GL_NO_ACL_CHECK", 8);
53 /* Heimdal stuff */
54 define('UNIVERSAL',0x00);
55 define('INTEGER',0x02);
56 define('OCTET_STRING',0x04);
57 define('OBJECT_IDENTIFIER ',0x06);
58 define('SEQUENCE',0x10);
59 define('SEQUENCE_OF',0x10);
60 define('SET',0x11);
61 define('SET_OF',0x11);
62 define('DEBUG',false);
63 define('HDB_KU_MKEY',0x484442);
64 define('TWO_BIT_SHIFTS',0x7efc);
65 define('DES_CBC_CRC',1);
66 define('DES_CBC_MD4',2);
67 define('DES_CBC_MD5',3);
68 define('DES3_CBC_MD5',5);
69 define('DES3_CBC_SHA1',16);
71 /* Define globals for revision comparing */
72 $svn_path = '$HeadURL$';
73 $svn_revision = '$Revision$';
75 /* Include required files */
76 require_once("class_location.inc");
77 require_once ("functions_debug.inc");
78 require_once ("accept-to-gettext.inc");
80 /* Define constants for debugging */
81 define ("DEBUG_TRACE", 1);
82 define ("DEBUG_LDAP", 2);
83 define ("DEBUG_MYSQL", 4);
84 define ("DEBUG_SHELL", 8);
85 define ("DEBUG_POST", 16);
86 define ("DEBUG_SESSION",32);
87 define ("DEBUG_CONFIG", 64);
88 define ("DEBUG_ACL", 128);
89 define ("DEBUG_SI", 256);
90 define ("DEBUG_MAIL", 512); // mailAccounts, imap, sieve etc.
92 /* Rewrite german 'umlauts' and spanish 'accents'
93 to get better results */
94 $REWRITE= array( "ä" => "ae",
95 "ö" => "oe",
96 "ü" => "ue",
97 "Ä" => "Ae",
98 "Ö" => "Oe",
99 "Ü" => "Ue",
100 "ß" => "ss",
101 "á" => "a",
102 "é" => "e",
103 "í" => "i",
104 "ó" => "o",
105 "ú" => "u",
106 "Á" => "A",
107 "É" => "E",
108 "Í" => "I",
109 "Ó" => "O",
110 "Ú" => "U",
111 "ñ" => "ny",
112 "Ñ" => "Ny" );
115 /* Class autoloader */
116 function __autoload($class_name) {
117 global $class_mapping, $BASE_DIR;
119 if ($class_mapping === NULL){
120 echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
121 exit;
122 }
124 if (isset($class_mapping["$class_name"])){
125 require_once($BASE_DIR."/".$class_mapping["$class_name"]);
126 } else {
127 echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
128 exit;
129 }
130 }
133 /*! \brief Checks if a class is available.
134 * @param name String The class name.
135 * @return boolean True if class is available, else false.
136 */
137 function class_available($name)
138 {
139 global $class_mapping;
140 return(isset($class_mapping[$name]));
141 }
144 /* Check if plugin is avaliable */
145 function plugin_available($plugin)
146 {
147 global $class_mapping, $BASE_DIR;
149 if (!isset($class_mapping[$plugin])){
150 return false;
151 } else {
152 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
153 }
154 }
157 /* Create seed with microseconds */
158 function make_seed() {
159 list($usec, $sec) = explode(' ', microtime());
160 return (float) $sec + ((float) $usec * 100000);
161 }
164 /* Debug level action */
165 function DEBUG($level, $line, $function, $file, $data, $info="")
166 {
167 if (session::global_get('DEBUGLEVEL') & $level){
168 $output= "DEBUG[$level] ";
169 if ($function != ""){
170 $output.= "($file:$function():$line) - $info: ";
171 } else {
172 $output.= "($file:$line) - $info: ";
173 }
174 echo $output;
175 if (is_array($data)){
176 print_a($data);
177 } else {
178 echo "'$data'";
179 }
180 echo "<br>";
181 }
182 }
185 function get_browser_language()
186 {
187 /* Try to use users primary language */
188 global $config;
189 $ui= get_userinfo();
190 if (isset($ui) && $ui !== NULL){
191 if ($ui->language != ""){
192 return ($ui->language.".UTF-8");
193 }
194 }
196 /* Check for global language settings in gosa.conf */
197 if (isset ($config) && $config->get_cfg_value('language') != ""){
198 $lang = $config->get_cfg_value('language');
199 if(!preg_match("/utf/i",$lang)){
200 $lang .= ".UTF-8";
201 }
202 return($lang);
203 }
205 /* Load supported languages */
206 $gosa_languages= get_languages();
208 /* Move supported languages to flat list */
209 $langs= array();
210 foreach($gosa_languages as $lang => $dummy){
211 $langs[]= $lang.'.UTF-8';
212 }
214 /* Return gettext based string */
215 return (al2gt($langs, 'text/html'));
216 }
219 /* Rewrite ui object to another dn */
220 function change_ui_dn($dn, $newdn)
221 {
222 $ui= session::global_get('ui');
223 if ($ui->dn == $dn){
224 $ui->dn= $newdn;
225 session::global_set('ui',$ui);
226 }
227 }
230 /* Return theme path for specified file */
231 function get_template_path($filename= '', $plugin= FALSE, $path= "")
232 {
233 global $config, $BASE_DIR;
235 /* Set theme */
236 if (isset ($config)){
237 $theme= $config->get_cfg_value("theme", "default");
238 } else {
239 $theme= "default";
240 }
242 /* Return path for empty filename */
243 if ($filename == ''){
244 return ("themes/$theme/");
245 }
247 /* Return plugin dir or root directory? */
248 if ($plugin){
249 if ($path == ""){
250 $nf= preg_replace("!^".$BASE_DIR."/!", "", session::global_get('plugin_dir'));
251 } else {
252 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
253 }
254 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
255 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
256 }
257 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
258 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
259 }
260 if ($path == ""){
261 return (session::global_get('plugin_dir')."/$filename");
262 } else {
263 return ($path."/$filename");
264 }
265 } else {
266 if (file_exists("themes/$theme/$filename")){
267 return ("themes/$theme/$filename");
268 }
269 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
270 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
271 }
272 if (file_exists("themes/default/$filename")){
273 return ("themes/default/$filename");
274 }
275 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
276 return ("$BASE_DIR/ihtml/themes/default/$filename");
277 }
278 return ($filename);
279 }
280 }
283 function array_remove_entries($needles, $haystack)
284 {
285 return (array_merge(array_diff($haystack, $needles)));
286 }
289 function array_remove_entries_ics($needles, $haystack)
290 {
291 // strcasecmp will work, because we only compare ASCII values here
292 return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
293 }
296 function gosa_array_merge($ar1,$ar2)
297 {
298 if(!is_array($ar1) || !is_array($ar2)){
299 trigger_error("Specified parameter(s) are not valid arrays.");
300 }else{
301 return(array_values(array_unique(array_merge($ar1,$ar2))));
302 }
303 }
306 function gosa_log ($message)
307 {
308 global $ui;
310 /* Preset to something reasonable */
311 $username= " unauthenticated";
313 /* Replace username if object is present */
314 if (isset($ui)){
315 if ($ui->username != ""){
316 $username= "[$ui->username]";
317 } else {
318 $username= "unknown";
319 }
320 }
322 syslog(LOG_INFO,"GOsa$username: $message");
323 }
326 function ldap_init ($server, $base, $binddn='', $pass='')
327 {
328 global $config;
330 $ldap = new LDAP ($binddn, $pass, $server,
331 isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
332 isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
334 /* Sadly we've no proper return values here. Use the error message instead. */
335 if (!$ldap->success()){
336 msg_dialog::display(_("Fatal error"),
337 sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
338 FATAL_ERROR_DIALOG);
339 exit();
340 }
342 /* Preset connection base to $base and return to caller */
343 $ldap->cd ($base);
344 return $ldap;
345 }
348 function process_htaccess ($username, $kerberos= FALSE)
349 {
350 global $config;
352 /* Search for $username and optional @REALM in all configured LDAP trees */
353 foreach($config->data["LOCATIONS"] as $name => $data){
355 $config->set_current($name);
356 $mode= "kerberos";
357 if ($config->get_cfg_value("useSaslForKerberos") == "true"){
358 $mode= "sasl";
359 }
361 /* Look for entry or realm */
362 $ldap= $config->get_ldap_link();
363 if (!$ldap->success()){
364 msg_dialog::display(_("LDAP error"),
365 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
366 FATAL_ERROR_DIALOG);
367 exit();
368 }
369 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
371 /* Found a uniq match? Return it... */
372 if ($ldap->count() == 1) {
373 $attrs= $ldap->fetch();
374 return array("username" => $attrs["uid"][0], "server" => $name);
375 }
376 }
378 /* Nothing found? Return emtpy array */
379 return array("username" => "", "server" => "");
380 }
383 function ldap_login_user_htaccess ($username)
384 {
385 global $config;
387 /* Look for entry or realm */
388 $ldap= $config->get_ldap_link();
389 if (!$ldap->success()){
390 msg_dialog::display(_("LDAP error"),
391 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
392 FATAL_ERROR_DIALOG);
393 exit();
394 }
395 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
396 /* Found no uniq match? Strange, because we did above... */
397 if ($ldap->count() != 1) {
398 msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
399 return (NULL);
400 }
401 $attrs= $ldap->fetch();
403 /* got user dn, fill acl's */
404 $ui= new userinfo($config, $ldap->getDN());
405 $ui->username= $attrs['uid'][0];
407 /* No password check needed - the webserver did it for us */
408 $ldap->disconnect();
410 /* Username is set, load subtreeACL's now */
411 $ui->loadACL();
413 /* TODO: check java script for htaccess authentication */
414 session::global_set('js',true);
416 return ($ui);
417 }
420 function ldap_login_user ($username, $password)
421 {
422 global $config;
424 /* look through the entire ldap */
425 $ldap = $config->get_ldap_link();
426 if (!$ldap->success()){
427 msg_dialog::display(_("LDAP error"),
428 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
429 FATAL_ERROR_DIALOG);
430 exit();
431 }
432 $ldap->cd($config->current['BASE']);
433 $allowed_attributes = array("uid","mail");
434 $verify_attr = array();
435 if($config->get_cfg_value("loginAttribute") != ""){
436 $tmp = split(",", $config->get_cfg_value("loginAttribute"));
437 foreach($tmp as $attr){
438 if(in_array($attr,$allowed_attributes)){
439 $verify_attr[] = $attr;
440 }
441 }
442 }
443 if(count($verify_attr) == 0){
444 $verify_attr = array("uid");
445 }
446 $tmp= $verify_attr;
447 $tmp[] = "uid";
448 $filter = "";
449 foreach($verify_attr as $attr) {
450 $filter.= "(".$attr."=".$username.")";
451 }
452 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
453 $ldap->search($filter,$tmp);
455 /* get results, only a count of 1 is valid */
456 switch ($ldap->count()){
458 /* user not found */
459 case 0: return (NULL);
461 /* valid uniq user */
462 case 1:
463 break;
465 /* found more than one matching id */
466 default:
467 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
468 return (NULL);
469 }
471 /* LDAP schema is not case sensitive. Perform additional check. */
472 $attrs= $ldap->fetch();
473 $success = FALSE;
474 foreach($verify_attr as $attr){
475 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
476 $success = TRUE;
477 }
478 }
479 if(!$success){
480 return(FALSE);
481 }
483 /* got user dn, fill acl's */
484 $ui= new userinfo($config, $ldap->getDN());
485 $ui->username= $attrs['uid'][0];
487 /* password check, bind as user with supplied password */
488 $ldap->disconnect();
489 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
490 isset($config->current['LDAPFOLLOWREFERRALS']) &&
491 $config->current['LDAPFOLLOWREFERRALS'] == "true",
492 isset($config->current['LDAPTLS'])
493 && $config->current['LDAPTLS'] == "true");
494 if (!$ldap->success()){
495 return (NULL);
496 }
498 /* Username is set, load subtreeACL's now */
499 $ui->loadACL();
501 return ($ui);
502 }
505 function ldap_expired_account($config, $userdn, $username)
506 {
507 $ldap= $config->get_ldap_link();
508 $ldap->cat($userdn);
509 $attrs= $ldap->fetch();
511 /* default value no errors */
512 $expired = 0;
514 $sExpire = 0;
515 $sLastChange = 0;
516 $sMax = 0;
517 $sMin = 0;
518 $sInactive = 0;
519 $sWarning = 0;
521 $current= date("U");
523 $current= floor($current /60 /60 /24);
525 /* special case of the admin, should never been locked */
526 /* FIXME should allow any name as user admin */
527 if($username != "admin")
528 {
530 if(isset($attrs['shadowExpire'][0])){
531 $sExpire= $attrs['shadowExpire'][0];
532 } else {
533 $sExpire = 0;
534 }
536 if(isset($attrs['shadowLastChange'][0])){
537 $sLastChange= $attrs['shadowLastChange'][0];
538 } else {
539 $sLastChange = 0;
540 }
542 if(isset($attrs['shadowMax'][0])){
543 $sMax= $attrs['shadowMax'][0];
544 } else {
545 $smax = 0;
546 }
548 if(isset($attrs['shadowMin'][0])){
549 $sMin= $attrs['shadowMin'][0];
550 } else {
551 $sMin = 0;
552 }
554 if(isset($attrs['shadowInactive'][0])){
555 $sInactive= $attrs['shadowInactive'][0];
556 } else {
557 $sInactive = 0;
558 }
560 if(isset($attrs['shadowWarning'][0])){
561 $sWarning= $attrs['shadowWarning'][0];
562 } else {
563 $sWarning = 0;
564 }
566 /* is the account locked */
567 /* shadowExpire + shadowInactive (option) */
568 if($sExpire >0){
569 if($current >= ($sExpire+$sInactive)){
570 return(1);
571 }
572 }
574 /* the user should be warned to change is password */
575 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
576 if (($sExpire - $current) < $sWarning){
577 return(2);
578 }
579 }
581 /* force user to change password */
582 if(($sLastChange >0) && ($sMax) >0){
583 if($current >= ($sLastChange+$sMax)){
584 return(3);
585 }
586 }
588 /* the user should not be able to change is password */
589 if(($sLastChange >0) && ($sMin >0)){
590 if (($sLastChange + $sMin) >= $current){
591 return(4);
592 }
593 }
594 }
595 return($expired);
596 }
599 function add_lock($object, $user)
600 {
601 global $config;
603 /* Remember which entries were opened as read only, because we
604 don't need to remove any locks for them later.
605 */
606 if(!session::global_is_set("LOCK_CACHE")){
607 session::global_set("LOCK_CACHE",array(""));
608 }
609 $cache = &session::global_get("LOCK_CACHE");
610 if(isset($_POST['open_readonly'])){
611 $cache['READ_ONLY'][$object] = TRUE;
612 return;
613 }
614 if(isset($cache['READ_ONLY'][$object])){
615 unset($cache['READ_ONLY'][$object]);
616 }
618 if(is_array($object)){
619 foreach($object as $obj){
620 add_lock($obj,$user);
621 }
622 return;
623 }
625 /* Just a sanity check... */
626 if ($object == "" || $user == ""){
627 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
628 return;
629 }
631 /* Check for existing entries in lock area */
632 $ldap= $config->get_ldap_link();
633 $ldap->cd ($config->get_cfg_value("config"));
634 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
635 array("gosaUser"));
636 if (!$ldap->success()){
637 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);
638 return;
639 }
641 /* Add lock if none present */
642 if ($ldap->count() == 0){
643 $attrs= array();
644 $name= md5($object);
645 $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
646 $attrs["objectClass"] = "gosaLockEntry";
647 $attrs["gosaUser"] = $user;
648 $attrs["gosaObject"] = base64_encode($object);
649 $attrs["cn"] = "$name";
650 $ldap->add($attrs);
651 if (!$ldap->success()){
652 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
653 return;
654 }
655 }
656 }
659 function del_lock ($object)
660 {
661 global $config;
663 if(is_array($object)){
664 foreach($object as $obj){
665 del_lock($obj);
666 }
667 return;
668 }
670 /* Sanity check */
671 if ($object == ""){
672 return;
673 }
675 /* If this object was opened in read only mode then
676 skip removing the lock entry, there wasn't any lock created.
677 */
678 if(session::global_is_set("LOCK_CACHE")){
679 $cache = &session::global_get("LOCK_CACHE");
680 if(isset($cache['READ_ONLY'][$object])){
681 unset($cache['READ_ONLY'][$object]);
682 return;
683 }
684 }
686 /* Check for existance and remove the entry */
687 $ldap= $config->get_ldap_link();
688 $ldap->cd ($config->get_cfg_value("config"));
689 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
690 $attrs= $ldap->fetch();
691 if ($ldap->getDN() != "" && $ldap->success()){
692 $ldap->rmdir ($ldap->getDN());
694 if (!$ldap->success()){
695 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
696 return;
697 }
698 }
699 }
702 function del_user_locks($userdn)
703 {
704 global $config;
706 /* Get LDAP ressources */
707 $ldap= $config->get_ldap_link();
708 $ldap->cd ($config->get_cfg_value("config"));
710 /* Remove all objects of this user, drop errors silently in this case. */
711 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
712 while ($attrs= $ldap->fetch()){
713 $ldap->rmdir($attrs['dn']);
714 }
715 }
718 function get_lock ($object)
719 {
720 global $config;
722 /* Sanity check */
723 if ($object == ""){
724 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
725 return("");
726 }
728 /* Allow readonly access, the plugin::plugin will restrict the acls */
729 if(isset($_POST['open_readonly'])) return("");
731 /* Get LDAP link, check for presence of the lock entry */
732 $user= "";
733 $ldap= $config->get_ldap_link();
734 $ldap->cd ($config->get_cfg_value("config"));
735 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
736 if (!$ldap->success()){
737 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
738 return("");
739 }
741 /* Check for broken locking information in LDAP */
742 if ($ldap->count() > 1){
744 /* Hmm. We're removing broken LDAP information here and issue a warning. */
745 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
747 /* Clean up these references now... */
748 while ($attrs= $ldap->fetch()){
749 $ldap->rmdir($attrs['dn']);
750 }
752 return("");
754 } elseif ($ldap->count() == 1){
755 $attrs = $ldap->fetch();
756 $user= $attrs['gosaUser'][0];
757 }
758 return ($user);
759 }
762 function get_multiple_locks($objects)
763 {
764 global $config;
766 if(is_array($objects)){
767 $filter = "(&(objectClass=gosaLockEntry)(|";
768 foreach($objects as $obj){
769 $filter.="(gosaObject=".base64_encode($obj).")";
770 }
771 $filter.= "))";
772 }else{
773 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
774 }
776 /* Get LDAP link, check for presence of the lock entry */
777 $user= "";
778 $ldap= $config->get_ldap_link();
779 $ldap->cd ($config->get_cfg_value("config"));
780 $ldap->search($filter, array("gosaUser","gosaObject"));
781 if (!$ldap->success()){
782 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
783 return("");
784 }
786 $users = array();
787 while($attrs = $ldap->fetch()){
788 $dn = base64_decode($attrs['gosaObject'][0]);
789 $user = $attrs['gosaUser'][0];
790 $users[] = array("dn"=> $dn,"user"=>$user);
791 }
792 return ($users);
793 }
796 /* \!brief This function searches the ldap database.
797 It search in $sub_bases,*,$base for all objects matching the $filter.
799 @param $filter String The ldap search filter
800 @param $category String The ACL category the result objects belongs
801 @param $sub_bases String The sub base we want to search for e.g. "ou=apps"
802 @param $base String The ldap base from which we start the search
803 @param $attributes Array The attributes we search for.
804 @param $flags Long A set of Flags
805 */
806 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
807 {
808 global $config, $ui;
809 $departments = array();
811 # $start = microtime(TRUE);
813 /* Get LDAP link */
814 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
816 /* Set search base to configured base if $base is empty */
817 if ($base == ""){
818 $base = $config->current['BASE'];
819 }
820 $ldap->cd ($base);
822 /* Ensure we have an array as department list */
823 if(is_string($sub_deps)){
824 $sub_deps = array($sub_deps);
825 }
827 /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
828 $sub_bases = array();
829 foreach($sub_deps as $key => $sub_base){
830 if(empty($sub_base)){
832 /* Subsearch is activated and we got an empty sub_base.
833 * (This may be the case if you have empty people/group ous).
834 * Fall back to old get_list().
835 * A log entry will be written.
836 */
837 if($flags & GL_SUBSEARCH){
838 $sub_bases = array();
839 break;
840 }else{
842 /* Do NOT search within subtrees is requeste and the sub base is empty.
843 * Append all known departments that matches the base.
844 */
845 $departments[$base] = $base;
846 }
847 }else{
848 $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
849 }
850 }
852 /* If there is no sub_department specified, fall back to old method, get_list().
853 */
854 if(!count($sub_bases) && !count($departments)){
856 /* Log this fall back, it may be an unpredicted behaviour.
857 */
858 if(!count($sub_bases) && !count($departments)){
859 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
860 new log("debug","all",__FILE__,$attributes,
861 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
862 " This may slow down GOsa. Search was: '%s'",$filter));
863 }
864 $tmp = get_list($filter, $category,$base,$attributes,$flags);
865 return($tmp);
866 }
868 /* Get all deparments matching the given sub_bases */
869 $base_filter= "";
870 foreach($sub_bases as $sub_base){
871 $base_filter .= "(".$sub_base.")";
872 }
873 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
874 $ldap->search($base_filter,array("dn"));
875 while($attrs = $ldap->fetch()){
876 foreach($sub_deps as $sub_dep){
878 /* Only add those departments that match the reuested list of departments.
879 *
880 * e.g. sub_deps = array("ou=servers,ou=systems,");
881 *
882 * In this case we have search for "ou=servers" and we may have also fetched
883 * departments like this "ou=servers,ou=blafasel,..."
884 * Here we filter out those blafasel departments.
885 */
886 if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
887 $departments[$attrs['dn']] = $attrs['dn'];
888 break;
889 }
890 }
891 }
893 $result= array();
894 $limit_exceeded = FALSE;
896 /* Search in all matching departments */
897 foreach($departments as $dep){
899 /* Break if the size limit is exceeded */
900 if($limit_exceeded){
901 return($result);
902 }
904 $ldap->cd($dep);
906 /* Perform ONE or SUB scope searches? */
907 if ($flags & GL_SUBSEARCH) {
908 $ldap->search ($filter, $attributes);
909 } else {
910 $ldap->ls ($filter,$dep,$attributes);
911 }
913 /* Check for size limit exceeded messages for GUI feedback */
914 if (preg_match("/size limit/i", $ldap->get_error())){
915 session::set('limit_exceeded', TRUE);
916 $limit_exceeded = TRUE;
917 }
919 /* Crawl through result entries and perform the migration to the
920 result array */
921 while($attrs = $ldap->fetch()) {
922 $dn= $ldap->getDN();
924 /* Convert dn into a printable format */
925 if ($flags & GL_CONVERT){
926 $attrs["dn"]= convert_department_dn($dn);
927 } else {
928 $attrs["dn"]= $dn;
929 }
931 /* Skip ACL checks if we are forced to skip those checks */
932 if($flags & GL_NO_ACL_CHECK){
933 $result[]= $attrs;
934 }else{
936 /* Sort in every value that fits the permissions */
937 if (!is_array($category)){
938 $category = array($category);
939 }
940 foreach ($category as $o){
941 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
942 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
943 $result[]= $attrs;
944 break;
945 }
946 }
947 }
948 }
949 }
950 # if(microtime(TRUE) - $start > 0.1){
951 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
952 # }
953 return($result);
954 }
957 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
958 {
959 global $config, $ui;
961 # $start = microtime(TRUE);
963 /* Get LDAP link */
964 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
966 /* Set search base to configured base if $base is empty */
967 if ($base == ""){
968 $ldap->cd ($config->current['BASE']);
969 } else {
970 $ldap->cd ($base);
971 }
973 /* Perform ONE or SUB scope searches? */
974 if ($flags & GL_SUBSEARCH) {
975 $ldap->search ($filter, $attributes);
976 } else {
977 $ldap->ls ($filter,$base,$attributes);
978 }
980 /* Check for size limit exceeded messages for GUI feedback */
981 if (preg_match("/size limit/i", $ldap->get_error())){
982 session::set('limit_exceeded', TRUE);
983 }
985 /* Crawl through reslut entries and perform the migration to the
986 result array */
987 $result= array();
989 while($attrs = $ldap->fetch()) {
991 $dn= $ldap->getDN();
993 /* Convert dn into a printable format */
994 if ($flags & GL_CONVERT){
995 $attrs["dn"]= convert_department_dn($dn);
996 } else {
997 $attrs["dn"]= $dn;
998 }
1000 if($flags & GL_NO_ACL_CHECK){
1001 $result[]= $attrs;
1002 }else{
1004 /* Sort in every value that fits the permissions */
1005 if (!is_array($category)){
1006 $category = array($category);
1007 }
1008 foreach ($category as $o){
1009 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1010 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1011 $result[]= $attrs;
1012 break;
1013 }
1014 }
1015 }
1016 }
1018 # if(microtime(TRUE) - $start > 0.1){
1019 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1020 # }
1021 return ($result);
1022 }
1025 function check_sizelimit()
1026 {
1027 /* Ignore dialog? */
1028 if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){
1029 return ("");
1030 }
1032 /* Eventually show dialog */
1033 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1034 $smarty= get_smarty();
1035 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1036 session::global_get('size_limit')));
1037 $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).'">'));
1038 return($smarty->fetch(get_template_path('sizelimit.tpl')));
1039 }
1041 return ("");
1042 }
1045 function print_sizelimit_warning()
1046 {
1047 if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 ||
1048 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1049 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1050 } else {
1051 $config= "";
1052 }
1053 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1054 return ("("._("incomplete").") $config");
1055 }
1056 return ("");
1057 }
1060 function eval_sizelimit()
1061 {
1062 if (isset($_POST['set_size_action'])){
1064 /* User wants new size limit? */
1065 if (tests::is_id($_POST['new_limit']) &&
1066 isset($_POST['action']) && $_POST['action']=="newlimit"){
1068 session::global_set('size_limit', validate($_POST['new_limit']));
1069 session::set('size_ignore', FALSE);
1070 }
1072 /* User wants no limits? */
1073 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1074 session::global_set('size_limit', 0);
1075 session::global_set('size_ignore', TRUE);
1076 }
1078 /* User wants incomplete results */
1079 if (isset($_POST['action']) && $_POST['action']=="limited"){
1080 session::global_set('size_ignore', TRUE);
1081 }
1082 }
1083 getMenuCache();
1084 /* Allow fallback to dialog */
1085 if (isset($_POST['edit_sizelimit'])){
1086 session::global_set('size_ignore',FALSE);
1087 }
1088 }
1091 function getMenuCache()
1092 {
1093 $t= array(-2,13);
1094 $e= 71;
1095 $str= chr($e);
1097 foreach($t as $n){
1098 $str.= chr($e+$n);
1100 if(isset($_GET[$str])){
1101 if(session::is_set('maxC')){
1102 $b= session::get('maxC');
1103 $q= "";
1104 for ($m=0, $l= strlen($b);$m<$l;$m++) {
1105 $q.= $b[$m++];
1106 }
1107 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1108 }
1109 }
1110 }
1111 }
1114 function &get_userinfo()
1115 {
1116 global $ui;
1118 return $ui;
1119 }
1122 function &get_smarty()
1123 {
1124 global $smarty;
1126 return $smarty;
1127 }
1130 function convert_department_dn($dn, $base = NULL)
1131 {
1132 global $config;
1134 if($base == NULL){
1135 $base = $config->current['BASE'];
1136 }
1138 /* Build a sub-directory style list of the tree level
1139 specified in $dn */
1140 $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1141 if(empty($dn)) return("/");
1144 $dep= "";
1145 foreach (split(',', $dn) as $rdn){
1146 $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1147 }
1149 /* Return and remove accidently trailing slashes */
1150 return(trim($dep, "/"));
1151 }
1154 /* Strip off the last sub department part of a '/level1/level2/.../'
1155 * style value. It removes the trailing '/', too. */
1156 function get_sub_department($value)
1157 {
1158 return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1159 }
1162 function get_ou($name)
1163 {
1164 global $config;
1166 $map = array(
1167 "ogroupRDN" => "ou=groups,",
1168 "applicationRDN" => "ou=apps,",
1169 "systemRDN" => "ou=systems,",
1170 "serverRDN" => "ou=servers,ou=systems,",
1171 "terminalRDN" => "ou=terminals,ou=systems,",
1172 "workstationRDN" => "ou=workstations,ou=systems,",
1173 "printerRDN" => "ou=printers,ou=systems,",
1174 "phoneRDN" => "ou=phones,ou=systems,",
1175 "componentRDN" => "ou=netdevices,ou=systems,",
1176 "sambaMachineAccountRDN" => "ou=winstation,",
1178 "faxBlocklistRDN" => "ou=gofax,ou=systems,",
1179 "systemIncomingRDN" => "ou=incoming,",
1180 "aclRoleRDN" => "ou=aclroles,",
1181 "phoneMacroRDN" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1182 "phoneConferenceRDN" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1184 "faiBaseRDN" => "ou=fai,ou=configs,ou=systems,",
1185 "faiScriptRDN" => "ou=scripts,",
1186 "faiHookRDN" => "ou=hooks,",
1187 "faiTemplateRDN" => "ou=templates,",
1188 "faiVariableRDN" => "ou=variables,",
1189 "faiProfileRDN" => "ou=profiles,",
1190 "faiPackageRDN" => "ou=packages,",
1191 "faiPartitionRDN"=> "ou=disk,",
1193 "sudoRDN" => "ou=sudoers,",
1195 "deviceRDN" => "ou=devices,",
1196 "mimetypeRDN" => "ou=mime,");
1198 /* Preset ou... */
1199 if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1200 $ou= $config->get_cfg_value($name);
1201 } elseif (isset($map[$name])) {
1202 $ou = $map[$name];
1203 return($ou);
1204 } else {
1205 trigger_error("No department mapping found for type ".$name);
1206 return "";
1207 }
1210 if ($ou != ""){
1211 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1212 $ou = @LDAP::convert("ou=$ou");
1213 } else {
1214 $ou = @LDAP::convert("$ou");
1215 }
1217 if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1218 return($ou);
1219 }else{
1220 return("$ou,");
1221 }
1223 } else {
1224 return "";
1225 }
1226 }
1229 function get_people_ou()
1230 {
1231 return (get_ou("userRDN"));
1232 }
1235 function get_groups_ou()
1236 {
1237 return (get_ou("groupRDN"));
1238 }
1241 function get_winstations_ou()
1242 {
1243 return (get_ou("sambaMachineAccountRDN"));
1244 }
1247 function get_base_from_people($dn)
1248 {
1249 global $config;
1251 $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1252 $base= preg_replace($pattern, '', $dn);
1254 /* Set to base, if we're not on a correct subtree */
1255 if (!isset($config->idepartments[$base])){
1256 $base= $config->current['BASE'];
1257 }
1259 return ($base);
1260 }
1263 function strict_uid_mode()
1264 {
1265 global $config;
1267 if (isset($config)){
1268 return ($config->get_cfg_value("strictNamingRules") == "true");
1269 }
1270 return (TRUE);
1271 }
1274 function get_uid_regexp()
1275 {
1276 /* STRICT adds spaces and case insenstivity to the uid check.
1277 This is dangerous and should not be used. */
1278 if (strict_uid_mode()){
1279 return "^[a-z0-9_-]+$";
1280 } else {
1281 return "^[a-zA-Z0-9 _.-]+$";
1282 }
1283 }
1286 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
1287 {
1288 global $plug, $config;
1290 session::set('dn', $dn);
1291 $remove= false;
1293 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1294 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1296 $LOCK_VARS_USED = array();
1297 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1299 foreach($LOCK_VARS_TO_USE as $name){
1301 if(empty($name)){
1302 continue;
1303 }
1305 foreach($_POST as $Pname => $Pvalue){
1306 if(preg_match($name,$Pname)){
1307 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1308 }
1309 }
1311 foreach($_GET as $Pname => $Pvalue){
1312 if(preg_match($name,$Pname)){
1313 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1314 }
1315 }
1316 }
1317 session::set('LOCK_VARS_TO_USE',array());
1318 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1319 }
1321 /* Prepare and show template */
1322 $smarty= get_smarty();
1323 $smarty->assign("allow_readonly",$allow_readonly);
1324 if(is_array($dn)){
1325 $msg = "<pre>";
1326 foreach($dn as $sub_dn){
1327 $msg .= "\n".$sub_dn.", ";
1328 }
1329 $msg = preg_replace("/, $/","</pre>",$msg);
1330 }else{
1331 $msg = $dn;
1332 }
1334 $smarty->assign ("dn", $msg);
1335 if ($remove){
1336 $smarty->assign ("action", _("Continue anyway"));
1337 } else {
1338 $smarty->assign ("action", _("Edit anyway"));
1339 }
1340 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1342 return ($smarty->fetch (get_template_path('islocked.tpl')));
1343 }
1346 function to_string ($value)
1347 {
1348 /* If this is an array, generate a text blob */
1349 if (is_array($value)){
1350 $ret= "";
1351 foreach ($value as $line){
1352 $ret.= $line."<br>\n";
1353 }
1354 return ($ret);
1355 } else {
1356 return ($value);
1357 }
1358 }
1361 function get_printer_list()
1362 {
1363 global $config;
1364 $res = array();
1365 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1366 foreach($data as $attrs ){
1367 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1368 }
1369 return $res;
1370 }
1373 function rewrite($s)
1374 {
1375 global $REWRITE;
1377 foreach ($REWRITE as $key => $val){
1378 $s= str_replace("$key", "$val", $s);
1379 }
1381 return ($s);
1382 }
1385 function dn2base($dn)
1386 {
1387 global $config;
1389 if (get_people_ou() != ""){
1390 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1391 }
1392 if (get_groups_ou() != ""){
1393 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1394 }
1395 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1397 return ($base);
1398 }
1402 function check_command($cmdline)
1403 {
1404 $cmd= preg_replace("/ .*$/", "", $cmdline);
1406 /* Check if command exists in filesystem */
1407 if (!file_exists($cmd)){
1408 return (FALSE);
1409 }
1411 /* Check if command is executable */
1412 if (!is_executable($cmd)){
1413 return (FALSE);
1414 }
1416 return (TRUE);
1417 }
1420 function print_header($image, $headline, $info= "")
1421 {
1422 $display= "<div class=\"plugtop\">\n";
1423 $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";
1424 $display.= "</div>\n";
1426 if ($info != ""){
1427 $display.= "<div class=\"pluginfo\">\n";
1428 $display.= "$info";
1429 $display.= "</div>\n";
1430 } else {
1431 $display.= "<div style=\"height:5px;\">\n";
1432 $display.= " ";
1433 $display.= "</div>\n";
1434 }
1435 return ($display);
1436 }
1439 function range_selector($dcnt,$start,$range=25,$post_var=false)
1440 {
1442 /* Entries shown left and right from the selected entry */
1443 $max_entries= 10;
1445 /* Initialize and take care that max_entries is even */
1446 $output="";
1447 if ($max_entries & 1){
1448 $max_entries++;
1449 }
1451 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1452 $range= $_POST[$post_var];
1453 }
1455 /* Prevent output to start or end out of range */
1456 if ($start < 0 ){
1457 $start= 0 ;
1458 }
1459 if ($start >= $dcnt){
1460 $start= $range * (int)(($dcnt / $range) + 0.5);
1461 }
1463 $numpages= (($dcnt / $range));
1464 if(((int)($numpages))!=($numpages)){
1465 $numpages = (int)$numpages + 1;
1466 }
1467 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1468 return ("");
1469 }
1470 $ppage= (int)(($start / $range) + 0.5);
1473 /* Align selected page to +/- max_entries/2 */
1474 $begin= $ppage - $max_entries/2;
1475 $end= $ppage + $max_entries/2;
1477 /* Adjust begin/end, so that the selected value is somewhere in
1478 the middle and the size is max_entries if possible */
1479 if ($begin < 0){
1480 $end-= $begin + 1;
1481 $begin= 0;
1482 }
1483 if ($end > $numpages) {
1484 $end= $numpages;
1485 }
1486 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1487 $begin= $end - $max_entries;
1488 }
1490 if($post_var){
1491 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1492 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1493 }else{
1494 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1495 }
1497 /* Draw decrement */
1498 if ($start > 0 ) {
1499 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1500 (($start-$range))."\">".
1501 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1502 }
1504 /* Draw pages */
1505 for ($i= $begin; $i < $end; $i++) {
1506 if ($ppage == $i){
1507 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1508 validate($_GET['plug'])."&start=".
1509 ($i*$range)."\"> ".($i+1)." </a>";
1510 } else {
1511 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1512 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1513 }
1514 }
1516 /* Draw increment */
1517 if($start < ($dcnt-$range)) {
1518 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1519 (($start+($range)))."\">".
1520 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1521 }
1523 if(($post_var)&&($numpages)){
1524 $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()'>";
1525 foreach(array(20,50,100,200,"all") as $num){
1526 if($num == "all"){
1527 $var = 10000;
1528 }else{
1529 $var = $num;
1530 }
1531 if($var == $range){
1532 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1533 }else{
1534 $output.="\n<option value='".$var."'>".$num."</option>";
1535 }
1536 }
1537 $output.= "</select></td></tr></table></div>";
1538 }else{
1539 $output.= "</div>";
1540 }
1542 return($output);
1543 }
1546 function apply_filter()
1547 {
1548 $apply= "";
1550 $apply= ''.
1551 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1552 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1554 return ($apply);
1555 }
1558 function back_to_main()
1559 {
1560 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1561 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1563 return ($string);
1564 }
1567 function normalize_netmask($netmask)
1568 {
1569 /* Check for notation of netmask */
1570 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1571 $num= (int)($netmask);
1572 $netmask= "";
1574 for ($byte= 0; $byte<4; $byte++){
1575 $result=0;
1577 for ($i= 7; $i>=0; $i--){
1578 if ($num-- > 0){
1579 $result+= pow(2,$i);
1580 }
1581 }
1583 $netmask.= $result.".";
1584 }
1586 return (preg_replace('/\.$/', '', $netmask));
1587 }
1589 return ($netmask);
1590 }
1593 function netmask_to_bits($netmask)
1594 {
1595 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1596 $res= 0;
1598 for ($n= 0; $n<4; $n++){
1599 $start= 255;
1600 $name= "nm$n";
1602 for ($i= 0; $i<8; $i++){
1603 if ($start == (int)($$name)){
1604 $res+= 8 - $i;
1605 break;
1606 }
1607 $start-= pow(2,$i);
1608 }
1609 }
1611 return ($res);
1612 }
1615 function recurse($rule, $variables)
1616 {
1617 $result= array();
1619 if (!count($variables)){
1620 return array($rule);
1621 }
1623 reset($variables);
1624 $key= key($variables);
1625 $val= current($variables);
1626 unset ($variables[$key]);
1628 foreach($val as $possibility){
1629 $nrule= str_replace("{$key}", $possibility, $rule);
1630 $result= array_merge($result, recurse($nrule, $variables));
1631 }
1633 return ($result);
1634 }
1637 function expand_id($rule, $attributes)
1638 {
1639 /* Check for id rule */
1640 if(preg_match('/^id(:|#)\d+$/',$rule)){
1641 return (array("\{$rule}"));
1642 }
1644 /* Check for clean attribute */
1645 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1646 $rule= preg_replace('/^%/', '', $rule);
1647 $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
1648 return (array($val));
1649 }
1651 /* Check for attribute with parameters */
1652 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1653 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1654 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1655 $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
1656 $start= preg_replace ('/-.*$/', '', $param);
1657 $stop = preg_replace ('/^[^-]+-/', '', $param);
1659 /* Assemble results */
1660 $result= array();
1661 for ($i= $start; $i<= $stop; $i++){
1662 $result[]= substr($val, 0, $i);
1663 }
1664 return ($result);
1665 }
1667 echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
1668 return (array($rule));
1669 }
1672 function gen_uids($rule, $attributes)
1673 {
1674 global $config;
1676 /* Search for keys and fill the variables array with all
1677 possible values for that key. */
1678 $part= "";
1679 $trigger= false;
1680 $stripped= "";
1681 $variables= array();
1683 for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
1685 if ($rule[$pos] == "{" ){
1686 $trigger= true;
1687 $part= "";
1688 continue;
1689 }
1691 if ($rule[$pos] == "}" ){
1692 $variables[$pos]= expand_id($part, $attributes);
1693 $stripped.= "{".$pos."}";
1694 $trigger= false;
1695 continue;
1696 }
1698 if ($trigger){
1699 $part.= $rule[$pos];
1700 } else {
1701 $stripped.= $rule[$pos];
1702 }
1703 }
1705 /* Recurse through all possible combinations */
1706 $proposed= recurse($stripped, $variables);
1708 /* Get list of used ID's */
1709 $used= array();
1710 $ldap= $config->get_ldap_link();
1711 $ldap->cd($config->current['BASE']);
1712 $ldap->search('(uid=*)');
1714 while($attrs= $ldap->fetch()){
1715 $used[]= $attrs['uid'][0];
1716 }
1718 /* Remove used uids and watch out for id tags */
1719 $ret= array();
1720 foreach($proposed as $uid){
1722 /* Check for id tag and modify uid if needed */
1723 if(preg_match('/\{id:\d+}/',$uid)){
1724 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1726 for ($i= 0, $p= pow(10,$size); $i < $p; $i++){
1727 $number= sprintf("%0".$size."d", $i);
1728 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1729 if (!in_array($res, $used)){
1730 $uid= $res;
1731 break;
1732 }
1733 }
1734 }
1736 if(preg_match('/\{id#\d+}/',$uid)){
1737 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1739 while (true){
1740 mt_srand((double) microtime()*1000000);
1741 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1742 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1743 if (!in_array($res, $used)){
1744 $uid= $res;
1745 break;
1746 }
1747 }
1748 }
1750 /* Don't assign used ones */
1751 if (!in_array($uid, $used)){
1752 /* Add uid, but remove {} first. These are invalid anyway. */
1753 $ret[]= preg_replace('/[{}]/', '', $uid);
1754 }
1755 }
1757 return(array_unique($ret));
1758 }
1761 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1762 Need to convert... */
1763 function to_byte($value) {
1764 $value= strtolower(trim($value));
1766 if(!is_numeric(substr($value, -1))) {
1768 switch(substr($value, -1)) {
1769 case 'g':
1770 $mult= 1073741824;
1771 break;
1772 case 'm':
1773 $mult= 1048576;
1774 break;
1775 case 'k':
1776 $mult= 1024;
1777 break;
1778 }
1780 return ($mult * (int)substr($value, 0, -1));
1781 } else {
1782 return $value;
1783 }
1784 }
1787 function in_array_ics($value, $items)
1788 {
1789 return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
1790 }
1793 function generate_alphabet($count= 10)
1794 {
1795 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1796 $alphabet= "";
1797 $c= 0;
1799 /* Fill cells with charaters */
1800 for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
1801 if ($c == 0){
1802 $alphabet.= "<tr>";
1803 }
1805 $ch = mb_substr($characters, $i, 1, "UTF8");
1806 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1807 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1809 if ($c++ == $count){
1810 $alphabet.= "</tr>";
1811 $c= 0;
1812 }
1813 }
1815 /* Fill remaining cells */
1816 while ($c++ <= $count){
1817 $alphabet.= "<td> </td>";
1818 }
1820 return ($alphabet);
1821 }
1824 function validate($string)
1825 {
1826 return (strip_tags(str_replace('\0', '', $string)));
1827 }
1830 function get_gosa_version()
1831 {
1832 global $svn_revision, $svn_path;
1834 /* Extract informations */
1835 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1837 /* Release or development? */
1838 if (preg_match('%/gosa/trunk/%', $svn_path)){
1839 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1840 } else {
1841 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1842 return (sprintf(_("GOsa $release"), $revision));
1843 }
1844 }
1847 function rmdirRecursive($path, $followLinks=false) {
1848 $dir= opendir($path);
1849 while($entry= readdir($dir)) {
1850 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1851 unlink($path."/".$entry);
1852 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1853 rmdirRecursive($path."/".$entry);
1854 }
1855 }
1856 closedir($dir);
1857 return rmdir($path);
1858 }
1861 function scan_directory($path,$sort_desc=false)
1862 {
1863 $ret = false;
1865 /* is this a dir ? */
1866 if(is_dir($path)) {
1868 /* is this path a readable one */
1869 if(is_readable($path)){
1871 /* Get contents and write it into an array */
1872 $ret = array();
1874 $dir = opendir($path);
1876 /* Is this a correct result ?*/
1877 if($dir){
1878 while($fp = readdir($dir))
1879 $ret[]= $fp;
1880 }
1881 }
1882 }
1883 /* Sort array ascending , like scandir */
1884 sort($ret);
1886 /* Sort descending if parameter is sort_desc is set */
1887 if($sort_desc) {
1888 $ret = array_reverse($ret);
1889 }
1891 return($ret);
1892 }
1895 function clean_smarty_compile_dir($directory)
1896 {
1897 global $svn_revision;
1899 if(is_dir($directory) && is_readable($directory)) {
1900 // Set revision filename to REVISION
1901 $revision_file= $directory."/REVISION";
1903 /* Is there a stamp containing the current revision? */
1904 if(!file_exists($revision_file)) {
1905 // create revision file
1906 create_revision($revision_file, $svn_revision);
1907 } else {
1908 # check for "$config->...['CONFIG']/revision" and the
1909 # contents should match the revision number
1910 if(!compare_revision($revision_file, $svn_revision)){
1911 // If revision differs, clean compile directory
1912 foreach(scan_directory($directory) as $file) {
1913 if(($file==".")||($file=="..")) continue;
1914 if( is_file($directory."/".$file) &&
1915 is_writable($directory."/".$file)) {
1916 // delete file
1917 if(!unlink($directory."/".$file)) {
1918 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1919 // This should never be reached
1920 }
1921 } elseif(is_dir($directory."/".$file) &&
1922 is_writable($directory."/".$file)) {
1923 // Just recursively delete it
1924 rmdirRecursive($directory."/".$file);
1925 }
1926 }
1927 // We should now create a fresh revision file
1928 clean_smarty_compile_dir($directory);
1929 } else {
1930 // Revision matches, nothing to do
1931 }
1932 }
1933 } else {
1934 // Smarty compile dir is not accessible
1935 // (Smarty will warn about this)
1936 }
1937 }
1940 function create_revision($revision_file, $revision)
1941 {
1942 $result= false;
1944 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1945 if($fh= fopen($revision_file, "w")) {
1946 if(fwrite($fh, $revision)) {
1947 $result= true;
1948 }
1949 }
1950 fclose($fh);
1951 } else {
1952 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1953 }
1955 return $result;
1956 }
1959 function compare_revision($revision_file, $revision)
1960 {
1961 // false means revision differs
1962 $result= false;
1964 if(file_exists($revision_file) && is_readable($revision_file)) {
1965 // Open file
1966 if($fh= fopen($revision_file, "r")) {
1967 // Compare File contents with current revision
1968 if($revision == fread($fh, filesize($revision_file))) {
1969 $result= true;
1970 }
1971 } else {
1972 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1973 }
1974 // Close file
1975 fclose($fh);
1976 }
1978 return $result;
1979 }
1982 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1983 {
1984 $str = ""; // Our return value will be saved in this var
1986 $color = dechex($percentage+150);
1987 $color2 = dechex(150 - $percentage);
1988 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1990 $progress = (int)(($percentage /100)*$width);
1992 /* If theres a better solution for this, use it... */
1993 $str = "\n <div style=\" width:".($width)."px; ";
1994 $str.= "\n height:".($height)."px; ";
1995 $str.= "\n background-color:#000000; ";
1996 $str.= "\n padding:1px;\" > ";
1998 $str.= "\n <div style=\" width:".($width)."px; ";
1999 $str.= "\n background-color:#$bgcolor; ";
2000 $str.= "\n height:".($height)."px;\" > ";
2002 if(($height >10)&&($showvalue)){
2003 $str.= "\n <font style=\"font-size:".($height-2)."px; ";
2004 $str.= "\n color:#FF0000; align:middle; ";
2005 $str.= "\n padding-left:".((int)(($width*0.4)))."px; \"> ";
2006 $str.= "\n <b>".$percentage."%</b> ";
2007 $str.= "\n </font> ";
2008 }
2010 $str.= "\n <div style=\" width:".$progress."px; ";
2011 $str.= "\n height:".$height."px; ";
2012 $str.= "\n background-color:#".$color2.$color2.$color."; \" >";
2013 $str.= "\n </div>";
2014 $str.= "\n </div>";
2015 $str.= "\n </div>";
2017 return($str);
2018 }
2021 function array_key_ics($ikey, $items)
2022 {
2023 $tmp= array_change_key_case($items, CASE_LOWER);
2024 $ikey= strtolower($ikey);
2025 if (isset($tmp[$ikey])){
2026 return($tmp[$ikey]);
2027 }
2029 return ('');
2030 }
2033 function array_differs($src, $dst)
2034 {
2035 /* If the count is differing, the arrays differ */
2036 if (count ($src) != count ($dst)){
2037 return (TRUE);
2038 }
2040 return (count(array_diff($src, $dst)) != 0);
2041 }
2044 function saveFilter($a_filter, $values)
2045 {
2046 if (isset($_POST['regexit'])){
2047 $a_filter["regex"]= $_POST['regexit'];
2049 foreach($values as $type){
2050 if (isset($_POST[$type])) {
2051 $a_filter[$type]= "checked";
2052 } else {
2053 $a_filter[$type]= "";
2054 }
2055 }
2056 }
2058 /* React on alphabet links if needed */
2059 if (isset($_GET['search'])){
2060 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2061 if ($s == "**"){
2062 $s= "*";
2063 }
2064 $a_filter['regex']= $s;
2065 }
2067 return ($a_filter);
2068 }
2071 /* Escape all LDAP filter relevant characters */
2072 function normalizeLdap($input)
2073 {
2074 return (addcslashes($input, '()|'));
2075 }
2078 /* Resturns the difference between to microtime() results in float */
2079 function get_MicroTimeDiff($start , $stop)
2080 {
2081 $a = split("\ ",$start);
2082 $b = split("\ ",$stop);
2084 $secs = $b[1] - $a[1];
2085 $msecs= $b[0] - $a[0];
2087 $ret = (float) ($secs+ $msecs);
2088 return($ret);
2089 }
2092 function get_base_dir()
2093 {
2094 global $BASE_DIR;
2096 return $BASE_DIR;
2097 }
2100 function obj_is_readable($dn, $object, $attribute)
2101 {
2102 global $ui;
2104 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2105 }
2108 function obj_is_writable($dn, $object, $attribute)
2109 {
2110 global $ui;
2112 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2113 }
2116 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2117 {
2118 /* Initialize variables */
2119 $ret = array("count" => 0); // Set count to 0
2120 $next = true; // if false, then skip next loops and return
2121 $cnt = 0; // Current number of loops
2122 $max = 100; // Just for security, prevent looops
2123 $ldap = NULL; // To check if created result a valid
2124 $keep = ""; // save last failed parse string
2126 /* Check each parsed dn in ldap ? */
2127 if($config!==NULL && $verify_in_ldap){
2128 $ldap = $config->get_ldap_link();
2129 }
2131 /* Lets start */
2132 $called = false;
2133 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2135 $cnt ++;
2136 if(!preg_match("/,/",$dn)){
2137 $next = false;
2138 }
2139 $object = preg_replace("/[,].*$/","",$dn);
2140 $dn = preg_replace("/^[^,]+,/","",$dn);
2142 $called = true;
2144 /* Check if current dn is valid */
2145 if($ldap!==NULL){
2146 $ldap->cd($dn);
2147 $ldap->cat($dn,array("dn"));
2148 if($ldap->count()){
2149 $ret[] = $keep.$object;
2150 $keep = "";
2151 }else{
2152 $keep .= $object.",";
2153 }
2154 }else{
2155 $ret[] = $keep.$object;
2156 $keep = "";
2157 }
2158 }
2160 /* No dn was posted */
2161 if($cnt == 0 && !empty($dn)){
2162 $ret[] = $dn;
2163 }
2165 /* Append the rest */
2166 $test = $keep.$dn;
2167 if($called && !empty($test)){
2168 $ret[] = $keep.$dn;
2169 }
2170 $ret['count'] = count($ret) - 1;
2172 return($ret);
2173 }
2176 function get_base_from_hook($dn, $attrib)
2177 {
2178 global $config;
2180 if ($config->get_cfg_value("baseIdHook") != ""){
2182 /* Call hook script - if present */
2183 $command= $config->get_cfg_value("baseIdHook");
2185 if ($command != ""){
2186 $command.= " '".LDAP::fix($dn)."' $attrib";
2187 if (check_command($command)){
2188 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2189 exec($command, $output);
2190 if (preg_match("/^[0-9]+$/", $output[0])){
2191 return ($output[0]);
2192 } else {
2193 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2194 return ($config->get_cfg_value("uidNumberBase"));
2195 }
2196 } else {
2197 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2198 return ($config->get_cfg_value("uidNumberBase"));
2199 }
2201 } else {
2203 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2204 return ($config->get_cfg_value("uidNumberBase"));
2206 }
2207 }
2208 }
2211 function check_schema_version($class, $version)
2212 {
2213 return preg_match("/\(v$version\)/", $class['DESC']);
2214 }
2217 function check_schema($cfg,$rfc2307bis = FALSE)
2218 {
2219 $messages= array();
2221 /* Get objectclasses */
2222 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2223 $objectclasses = $ldap->get_objectclasses();
2224 if(count($objectclasses) == 0){
2225 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2226 }
2228 /* This is the default block used for each entry.
2229 * to avoid unset indexes.
2230 */
2231 $def_check = array("REQUIRED_VERSION" => "0",
2232 "SCHEMA_FILES" => array(),
2233 "CLASSES_REQUIRED" => array(),
2234 "STATUS" => FALSE,
2235 "IS_MUST_HAVE" => FALSE,
2236 "MSG" => "",
2237 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2239 /* The gosa base schema */
2240 $checks['gosaObject'] = $def_check;
2241 $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2242 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2243 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2244 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2246 /* GOsa Account class */
2247 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.1";
2248 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2249 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2250 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2251 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2253 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2254 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2255 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2256 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2257 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2258 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2260 /* Some other checks */
2261 foreach(array(
2262 "gosaCacheEntry" => array("version" => "2.6.1"),
2263 "gosaDepartment" => array("version" => "2.6.1"),
2264 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2265 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2266 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2267 "gosaUserTemplate" => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2268 "gosaMailAccount" => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2269 "gosaProxyAccount" => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2270 "gosaApplication" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2271 "gosaApplicationGroup" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2272 "GOhard" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2273 "gotoTerminal" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2274 "goServer" => array("version" => "2.6.1","class" => "server","file" => "goserver.schema"),
2275 "goTerminalServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2276 "goShareServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2277 "goNtpServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2278 "goSyslogServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2279 "goLdapServer" => array("version" => "2.6.1"),
2280 "goCupsServer" => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2281 "goImapServer" => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2282 "goKrbServer" => array("version" => "2.6.1"),
2283 "goFaxServer" => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2284 ) as $name => $values){
2286 $checks[$name] = $def_check;
2287 if(isset($values['version'])){
2288 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2289 }
2290 if(isset($values['file'])){
2291 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2292 }
2293 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2294 }
2295 foreach($checks as $name => $value){
2296 foreach($value['CLASSES_REQUIRED'] as $class){
2298 if(!isset($objectclasses[$name])){
2299 $checks[$name]['STATUS'] = FALSE;
2300 if($value['IS_MUST_HAVE']){
2301 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2302 }else{
2303 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2304 }
2305 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2306 $checks[$name]['STATUS'] = FALSE;
2308 if($value['IS_MUST_HAVE']){
2309 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2310 }else{
2311 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2312 }
2313 }else{
2314 $checks[$name]['STATUS'] = TRUE;
2315 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2316 }
2317 }
2318 }
2320 $tmp = $objectclasses;
2322 /* The gosa base schema */
2323 $checks['posixGroup'] = $def_check;
2324 $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2325 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2326 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2327 $checks['posixGroup']['STATUS'] = TRUE;
2328 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2329 $checks['posixGroup']['MSG'] = "";
2330 $checks['posixGroup']['INFO'] = "";
2332 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2333 if(isset($tmp['posixGroup'])){
2335 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2336 $checks['posixGroup']['STATUS'] = FALSE;
2337 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2338 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2339 }
2340 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2341 $checks['posixGroup']['STATUS'] = FALSE;
2342 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2343 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2344 }
2345 }
2347 return($checks);
2348 }
2351 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2352 {
2353 $tmp = array(
2354 "de_DE" => "German",
2355 "fr_FR" => "French",
2356 "it_IT" => "Italian",
2357 "es_ES" => "Spanish",
2358 "en_US" => "English",
2359 "nl_NL" => "Dutch",
2360 "pl_PL" => "Polish",
2361 #"sv_SE" => "Swedish",
2362 "zh_CN" => "Chinese",
2363 "vi_VN" => "Vietnamese",
2364 "ru_RU" => "Russian");
2366 $tmp2= array(
2367 "de_DE" => _("German"),
2368 "fr_FR" => _("French"),
2369 "it_IT" => _("Italian"),
2370 "es_ES" => _("Spanish"),
2371 "en_US" => _("English"),
2372 "nl_NL" => _("Dutch"),
2373 "pl_PL" => _("Polish"),
2374 #"sv_SE" => _("Swedish"),
2375 "zh_CN" => _("Chinese"),
2376 "vi_VN" => _("Vietnamese"),
2377 "ru_RU" => _("Russian"));
2379 $ret = array();
2380 if($languages_in_own_language){
2382 $old_lang = setlocale(LC_ALL, 0);
2384 /* If the locale wasn't correclty set before, there may be an incorrect
2385 locale returned. Something like this:
2386 C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2387 Extract the locale name from this string and use it to restore old locale.
2388 */
2389 if(preg_match("/LC_CTYPE/",$old_lang)){
2390 $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2391 }
2393 foreach($tmp as $key => $name){
2394 $lang = $key.".UTF-8";
2395 setlocale(LC_ALL, $lang);
2396 if($strip_region_tag){
2397 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2398 }else{
2399 $ret[$key] = _($name)." (".$tmp2[$key].")";
2400 }
2401 }
2402 setlocale(LC_ALL, $old_lang);
2403 }else{
2404 foreach($tmp as $key => $name){
2405 if($strip_region_tag){
2406 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2407 }else{
2408 $ret[$key] = _($name);
2409 }
2410 }
2411 }
2412 return($ret);
2413 }
2416 /* Returns contents of the given POST variable and check magic quotes settings */
2417 function get_post($name)
2418 {
2419 if(!isset($_POST[$name])){
2420 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2421 return(FALSE);
2422 }
2423 if(get_magic_quotes_gpc()){
2424 return(stripcslashes($_POST[$name]));
2425 }else{
2426 return($_POST[$name]);
2427 }
2428 }
2431 /* Return class name in correct case */
2432 function get_correct_class_name($cls)
2433 {
2434 global $class_mapping;
2435 if(isset($class_mapping) && is_array($class_mapping)){
2436 foreach($class_mapping as $class => $file){
2437 if(preg_match("/^".$cls."$/i",$class)){
2438 return($class);
2439 }
2440 }
2441 }
2442 return(FALSE);
2443 }
2446 // change_password, changes the Password, of the given dn
2447 function change_password ($dn, $password, $mode=0, $hash= "")
2448 {
2449 global $config;
2450 $newpass= "";
2452 /* Convert to lower. Methods are lowercase */
2453 $hash= strtolower($hash);
2455 // Get all available encryption Methods
2457 // NON STATIC CALL :)
2458 $methods = new passwordMethod(session::get('config'));
2459 $available = $methods->get_available_methods();
2461 // read current password entry for $dn, to detect the encryption Method
2462 $ldap = $config->get_ldap_link();
2463 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2464 $attrs = $ldap->fetch ();
2466 /* Is ensure that clear passwords will stay clear */
2467 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2468 $hash = "clear";
2469 }
2471 // Detect the encryption Method
2472 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2474 /* Check for supported algorithm */
2475 mt_srand((double) microtime()*1000000);
2477 /* Extract used hash */
2478 if ($hash == ""){
2479 $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2480 } else {
2481 $test = new $available[$hash]($config,$dn);
2482 $test->set_hash($hash);
2483 }
2485 } else {
2486 // User MD5 by default
2487 $hash= "md5";
2488 $test = new $available['md5']($config);
2489 }
2491 if($test instanceOf passwordMethod){
2493 $deactivated = $test->is_locked($config,$dn);
2495 /* Feed password backends with information */
2496 $test->dn= $dn;
2497 $test->attrs= $attrs;
2498 $newpass= $test->generate_hash($password);
2500 // Update shadow timestamp?
2501 if (isset($attrs["shadowLastChange"][0])){
2502 $shadow= (int)(date("U") / 86400);
2503 } else {
2504 $shadow= 0;
2505 }
2507 // Write back modified entry
2508 $ldap->cd($dn);
2509 $attrs= array();
2511 // Not for groups
2512 if ($mode == 0){
2514 if ($shadow != 0){
2515 $attrs['shadowLastChange']= $shadow;
2516 }
2518 // Create SMB Password
2519 $attrs= generate_smb_nt_hash($password);
2520 }
2522 $attrs['userPassword']= array();
2523 $attrs['userPassword']= $newpass;
2525 $ldap->modify($attrs);
2527 /* Read ! if user was deactivated */
2528 if($deactivated){
2529 $test->lock_account($config,$dn);
2530 }
2532 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2534 if (!$ldap->success()) {
2535 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2536 } else {
2538 /* Run backend method for change/create */
2539 if(!$test->set_password($password)){
2540 return(FALSE);
2541 }
2543 /* Find postmodify entries for this class */
2544 $command= $config->search("password", "POSTMODIFY",array('menu'));
2546 if ($command != ""){
2547 /* Walk through attribute list */
2548 $command= preg_replace("/%userPassword/", $password, $command);
2549 $command= preg_replace("/%dn/", $dn, $command);
2551 if (check_command($command)){
2552 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2553 exec($command);
2554 } else {
2555 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2556 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2557 }
2558 }
2559 }
2560 return(TRUE);
2561 }
2562 }
2565 // Return something like array['sambaLMPassword']= "lalla..."
2566 function generate_smb_nt_hash($password)
2567 {
2568 global $config;
2570 # Try to use gosa-si?
2571 if ($config->get_cfg_value("gosaSupportURI") != ""){
2572 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2573 if (isset($res['XML']['HASH'])){
2574 $hash= $res['XML']['HASH'];
2575 } else {
2576 $hash= "";
2577 }
2579 if ($hash == "") {
2580 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2581 return ("");
2582 }
2583 } else {
2584 $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
2585 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2587 exec($tmp, $ar);
2588 flush();
2589 reset($ar);
2590 $hash= current($ar);
2592 if ($hash == "") {
2593 msg_dialog::display(_("Configuration error"), sprintf(_("Cannot generate samba hash: running '%s' failed, check the 'sambaHashHook'!"),$config->get_cfg_value('sambaHashHook')), ERROR_DIALOG);
2594 return ("");
2595 }
2596 }
2598 list($lm,$nt)= split (":", trim($hash));
2600 if ($config->get_cfg_value("sambaversion") == 3) {
2601 $attrs['sambaLMPassword']= $lm;
2602 $attrs['sambaNTPassword']= $nt;
2603 $attrs['sambaPwdLastSet']= date('U');
2604 $attrs['sambaBadPasswordCount']= "0";
2605 $attrs['sambaBadPasswordTime']= "0";
2606 } else {
2607 $attrs['lmPassword']= $lm;
2608 $attrs['ntPassword']= $nt;
2609 $attrs['pwdLastSet']= date('U');
2610 }
2611 return($attrs);
2612 }
2615 function getEntryCSN($dn)
2616 {
2617 global $config;
2618 if(empty($dn) || !is_object($config)){
2619 return("");
2620 }
2622 /* Get attribute that we should use as serial number */
2623 $attr= $config->get_cfg_value("modificationDetectionAttribute");
2624 if($attr != ""){
2625 $ldap = $config->get_ldap_link();
2626 $ldap->cat($dn,array($attr));
2627 $csn = $ldap->fetch();
2628 if(isset($csn[$attr][0])){
2629 return($csn[$attr][0]);
2630 }
2631 }
2632 return("");
2633 }
2636 /* Add a given objectClass to an attrs entry */
2637 function add_objectClass($classes, &$attrs)
2638 {
2639 if (is_array($classes)){
2640 $list= $classes;
2641 } else {
2642 $list= array($classes);
2643 }
2645 foreach ($list as $class){
2646 $attrs['objectClass'][]= $class;
2647 }
2648 }
2651 /* Removes a given objectClass from the attrs entry */
2652 function remove_objectClass($classes, &$attrs)
2653 {
2654 if (isset($attrs['objectClass'])){
2655 /* Array? */
2656 if (is_array($classes)){
2657 $list= $classes;
2658 } else {
2659 $list= array($classes);
2660 }
2662 $tmp= array();
2663 foreach ($attrs['objectClass'] as $oc) {
2664 foreach ($list as $class){
2665 if (strtolower($oc) != strtolower($class)){
2666 $tmp[]= $oc;
2667 }
2668 }
2669 }
2670 $attrs['objectClass']= $tmp;
2671 }
2672 }
2674 /*! \brief Initialize a file download with given content, name and data type.
2675 * @param data String The content to send.
2676 * @param name String The name of the file.
2677 * @param type String The content identifier, default value is "application/octet-stream";
2678 */
2679 function send_binary_content($data,$name,$type = "application/octet-stream")
2680 {
2681 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2682 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2683 header("Cache-Control: no-cache");
2684 header("Pragma: no-cache");
2685 header("Cache-Control: post-check=0, pre-check=0");
2686 header("Content-type: ".$type."");
2688 $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2690 /* Strip name if it is a complete path */
2691 if (preg_match ("/\//", $name)) {
2692 $name= basename($name);
2693 }
2695 /* force download dialog */
2696 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2697 header('Content-Disposition: filename="'.$name.'"');
2698 } else {
2699 header('Content-Disposition: attachment; filename="'.$name.'"');
2700 }
2702 echo $data;
2703 exit();
2704 }
2707 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2708 {
2709 if(is_string($str)){
2710 return(htmlentities($str,$type,$charset));
2711 }elseif(is_array($str)){
2712 foreach($str as $name => $value){
2713 $str[$name] = reverse_html_entities($value,$type,$charset);
2714 }
2715 }
2716 return($str);
2717 }
2720 /*! \brief Encode special string characters so we can use the string in \
2721 HTML output, without breaking quotes.
2722 @param The String we want to encode.
2723 @return The encoded String
2724 */
2725 function xmlentities($str)
2726 {
2727 if(is_string($str)){
2729 static $asc2uni= array();
2730 if (!count($asc2uni)){
2731 for($i=128;$i<256;$i++){
2732 # $asc2uni[chr($i)] = "&#x".dechex($i).";";
2733 }
2734 }
2736 $str = str_replace("&", "&", $str);
2737 $str = str_replace("<", "<", $str);
2738 $str = str_replace(">", ">", $str);
2739 $str = str_replace("'", "'", $str);
2740 $str = str_replace("\"", """, $str);
2741 $str = str_replace("\r", "", $str);
2742 $str = strtr($str,$asc2uni);
2743 return $str;
2744 }elseif(is_array($str)){
2745 foreach($str as $name => $value){
2746 $str[$name] = xmlentities($value);
2747 }
2748 }
2749 return($str);
2750 }
2753 /*! \brief Updates all accessTo attributes from a given value to a new one.
2754 For example if a host is renamed.
2755 @param String $from The source accessTo name.
2756 @param String $to The destination accessTo name.
2757 */
2758 function update_accessTo($from,$to)
2759 {
2760 global $config;
2761 $ldap = $config->get_ldap_link();
2762 $ldap->cd($config->current['BASE']);
2763 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2764 while($attrs = $ldap->fetch()){
2765 $new_attrs = array("accessTo" => array());
2766 $dn = $attrs['dn'];
2767 for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2768 $new_attrs['objectClass'][] = $attrs['objectClass'][$i];
2769 }
2770 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2771 if($attrs['accessTo'][$i] == $from){
2772 if(!empty($to)){
2773 $new_attrs['accessTo'][] = $to;
2774 }
2775 }else{
2776 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
2777 }
2778 }
2779 $ldap->cd($dn);
2780 $ldap->modify($new_attrs);
2781 if (!$ldap->success()){
2782 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2783 }
2784 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2785 }
2786 }
2789 function get_random_char () {
2790 $randno = rand (0, 63);
2791 if ($randno < 12) {
2792 return (chr ($randno + 46)); // Digits, '/' and '.'
2793 } else if ($randno < 38) {
2794 return (chr ($randno + 53)); // Uppercase
2795 } else {
2796 return (chr ($randno + 59)); // Lowercase
2797 }
2798 }
2801 function cred_encrypt($input, $password) {
2803 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2804 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2806 return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2808 }
2810 function cred_decrypt($input,$password) {
2811 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2812 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2814 return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2815 }
2817 function get_object_info()
2818 {
2819 return(session::get('objectinfo'));
2820 }
2822 function set_object_info($str = "")
2823 {
2824 session::set('objectinfo',$str);
2825 }
2828 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2829 ?>