b0d14045abc23aaeddc4012b82e3cf059a74c982
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.
91 define ("DEBUG_FAI", 1024); // FAI (incomplete)
93 /* Rewrite german 'umlauts' and spanish 'accents'
94 to get better results */
95 $REWRITE= array( "ä" => "ae",
96 "ö" => "oe",
97 "ü" => "ue",
98 "Ä" => "Ae",
99 "Ö" => "Oe",
100 "Ü" => "Ue",
101 "ß" => "ss",
102 "á" => "a",
103 "é" => "e",
104 "í" => "i",
105 "ó" => "o",
106 "ú" => "u",
107 "Á" => "A",
108 "É" => "E",
109 "Í" => "I",
110 "Ó" => "O",
111 "Ú" => "U",
112 "ñ" => "ny",
113 "Ñ" => "Ny" );
116 /* Class autoloader */
117 function __autoload($class_name) {
118 global $class_mapping, $BASE_DIR;
120 if ($class_mapping === NULL){
121 echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
122 exit;
123 }
125 if (isset($class_mapping["$class_name"])){
126 require_once($BASE_DIR."/".$class_mapping["$class_name"]);
127 } else {
128 echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
129 exit;
130 }
131 }
134 /*! \brief Checks if a class is available.
135 * @param name String The class name.
136 * @return boolean True if class is available, else false.
137 */
138 function class_available($name)
139 {
140 global $class_mapping;
141 return(isset($class_mapping[$name]));
142 }
145 /* Check if plugin is avaliable */
146 function plugin_available($plugin)
147 {
148 global $class_mapping, $BASE_DIR;
150 if (!isset($class_mapping[$plugin])){
151 return false;
152 } else {
153 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
154 }
155 }
158 /* Create seed with microseconds */
159 function make_seed() {
160 list($usec, $sec) = explode(' ', microtime());
161 return (float) $sec + ((float) $usec * 100000);
162 }
165 /* Debug level action */
166 function DEBUG($level, $line, $function, $file, $data, $info="")
167 {
168 if (session::global_get('DEBUGLEVEL') & $level){
169 $output= "DEBUG[$level] ";
170 if ($function != ""){
171 $output.= "($file:$function():$line) - $info: ";
172 } else {
173 $output.= "($file:$line) - $info: ";
174 }
175 echo $output;
176 if (is_array($data)){
177 print_a($data);
178 } else {
179 echo "'$data'";
180 }
181 echo "<br>";
182 }
183 }
186 function get_browser_language()
187 {
188 /* Try to use users primary language */
189 global $config;
190 $ui= get_userinfo();
191 if (isset($ui) && $ui !== NULL){
192 if ($ui->language != ""){
193 return ($ui->language.".UTF-8");
194 }
195 }
197 /* Check for global language settings in gosa.conf */
198 if (isset ($config) && $config->get_cfg_value('language') != ""){
199 $lang = $config->get_cfg_value('language');
200 if(!preg_match("/utf/i",$lang)){
201 $lang .= ".UTF-8";
202 }
203 return($lang);
204 }
206 /* Load supported languages */
207 $gosa_languages= get_languages();
209 /* Move supported languages to flat list */
210 $langs= array();
211 foreach($gosa_languages as $lang => $dummy){
212 $langs[]= $lang.'.UTF-8';
213 }
215 /* Return gettext based string */
216 return (al2gt($langs, 'text/html'));
217 }
220 /* Rewrite ui object to another dn */
221 function change_ui_dn($dn, $newdn)
222 {
223 $ui= session::global_get('ui');
224 if ($ui->dn == $dn){
225 $ui->dn= $newdn;
226 session::global_set('ui',$ui);
227 }
228 }
231 /* Return theme path for specified file */
232 function get_template_path($filename= '', $plugin= FALSE, $path= "")
233 {
234 global $config, $BASE_DIR;
236 /* Set theme */
237 if (isset ($config)){
238 $theme= $config->get_cfg_value("theme", "default");
239 } else {
240 $theme= "default";
241 }
243 /* Return path for empty filename */
244 if ($filename == ''){
245 return ("themes/$theme/");
246 }
248 /* Return plugin dir or root directory? */
249 if ($plugin){
250 if ($path == ""){
251 $nf= preg_replace("!^".$BASE_DIR."/!", "", session::global_get('plugin_dir'));
252 } else {
253 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
254 }
255 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
256 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
257 }
258 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
259 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
260 }
261 if ($path == ""){
262 return (session::global_get('plugin_dir')."/$filename");
263 } else {
264 return ($path."/$filename");
265 }
266 } else {
267 if (file_exists("themes/$theme/$filename")){
268 return ("themes/$theme/$filename");
269 }
270 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
271 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
272 }
273 if (file_exists("themes/default/$filename")){
274 return ("themes/default/$filename");
275 }
276 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
277 return ("$BASE_DIR/ihtml/themes/default/$filename");
278 }
279 return ($filename);
280 }
281 }
284 function array_remove_entries($needles, $haystack)
285 {
286 return (array_merge(array_diff($haystack, $needles)));
287 }
290 function array_remove_entries_ics($needles, $haystack)
291 {
292 // strcasecmp will work, because we only compare ASCII values here
293 return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
294 }
297 function gosa_array_merge($ar1,$ar2)
298 {
299 if(!is_array($ar1) || !is_array($ar2)){
300 trigger_error("Specified parameter(s) are not valid arrays.");
301 }else{
302 return(array_values(array_unique(array_merge($ar1,$ar2))));
303 }
304 }
307 function gosa_log ($message)
308 {
309 global $ui;
311 /* Preset to something reasonable */
312 $username= " unauthenticated";
314 /* Replace username if object is present */
315 if (isset($ui)){
316 if ($ui->username != ""){
317 $username= "[$ui->username]";
318 } else {
319 $username= "unknown";
320 }
321 }
323 syslog(LOG_INFO,"GOsa$username: $message");
324 }
327 function ldap_init ($server, $base, $binddn='', $pass='')
328 {
329 global $config;
331 $ldap = new LDAP ($binddn, $pass, $server,
332 isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
333 isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
335 /* Sadly we've no proper return values here. Use the error message instead. */
336 if (!$ldap->success()){
337 msg_dialog::display(_("Fatal error"),
338 sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
339 FATAL_ERROR_DIALOG);
340 exit();
341 }
343 /* Preset connection base to $base and return to caller */
344 $ldap->cd ($base);
345 return $ldap;
346 }
349 function process_htaccess ($username, $kerberos= FALSE)
350 {
351 global $config;
353 /* Search for $username and optional @REALM in all configured LDAP trees */
354 foreach($config->data["LOCATIONS"] as $name => $data){
356 $config->set_current($name);
357 $mode= "kerberos";
358 if ($config->get_cfg_value("useSaslForKerberos") == "true"){
359 $mode= "sasl";
360 }
362 /* Look for entry or realm */
363 $ldap= $config->get_ldap_link();
364 if (!$ldap->success()){
365 msg_dialog::display(_("LDAP error"),
366 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
367 FATAL_ERROR_DIALOG);
368 exit();
369 }
370 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
372 /* Found a uniq match? Return it... */
373 if ($ldap->count() == 1) {
374 $attrs= $ldap->fetch();
375 return array("username" => $attrs["uid"][0], "server" => $name);
376 }
377 }
379 /* Nothing found? Return emtpy array */
380 return array("username" => "", "server" => "");
381 }
384 function ldap_login_user_htaccess ($username)
385 {
386 global $config;
388 /* Look for entry or realm */
389 $ldap= $config->get_ldap_link();
390 if (!$ldap->success()){
391 msg_dialog::display(_("LDAP error"),
392 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
393 FATAL_ERROR_DIALOG);
394 exit();
395 }
396 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
397 /* Found no uniq match? Strange, because we did above... */
398 if ($ldap->count() != 1) {
399 msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
400 return (NULL);
401 }
402 $attrs= $ldap->fetch();
404 /* got user dn, fill acl's */
405 $ui= new userinfo($config, $ldap->getDN());
406 $ui->username= $attrs['uid'][0];
408 /* No password check needed - the webserver did it for us */
409 $ldap->disconnect();
411 /* Username is set, load subtreeACL's now */
412 $ui->loadACL();
414 /* TODO: check java script for htaccess authentication */
415 session::global_set('js',true);
417 return ($ui);
418 }
421 function ldap_login_user ($username, $password)
422 {
423 global $config;
425 /* look through the entire ldap */
426 $ldap = $config->get_ldap_link();
427 if (!$ldap->success()){
428 msg_dialog::display(_("LDAP error"),
429 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
430 FATAL_ERROR_DIALOG);
431 exit();
432 }
433 $ldap->cd($config->current['BASE']);
434 $allowed_attributes = array("uid","mail");
435 $verify_attr = array();
436 if($config->get_cfg_value("loginAttribute") != ""){
437 $tmp = split(",", $config->get_cfg_value("loginAttribute"));
438 foreach($tmp as $attr){
439 if(in_array($attr,$allowed_attributes)){
440 $verify_attr[] = $attr;
441 }
442 }
443 }
444 if(count($verify_attr) == 0){
445 $verify_attr = array("uid");
446 }
447 $tmp= $verify_attr;
448 $tmp[] = "uid";
449 $filter = "";
450 foreach($verify_attr as $attr) {
451 $filter.= "(".$attr."=".$username.")";
452 }
453 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
454 $ldap->search($filter,$tmp);
456 /* get results, only a count of 1 is valid */
457 switch ($ldap->count()){
459 /* user not found */
460 case 0: return (NULL);
462 /* valid uniq user */
463 case 1:
464 break;
466 /* found more than one matching id */
467 default:
468 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
469 return (NULL);
470 }
472 /* LDAP schema is not case sensitive. Perform additional check. */
473 $attrs= $ldap->fetch();
474 $success = FALSE;
475 foreach($verify_attr as $attr){
476 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
477 $success = TRUE;
478 }
479 }
480 if(!$success){
481 return(FALSE);
482 }
484 /* got user dn, fill acl's */
485 $ui= new userinfo($config, $ldap->getDN());
486 $ui->username= $attrs['uid'][0];
488 /* password check, bind as user with supplied password */
489 $ldap->disconnect();
490 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
491 isset($config->current['LDAPFOLLOWREFERRALS']) &&
492 $config->current['LDAPFOLLOWREFERRALS'] == "true",
493 isset($config->current['LDAPTLS'])
494 && $config->current['LDAPTLS'] == "true");
495 if (!$ldap->success()){
496 return (NULL);
497 }
499 /* Username is set, load subtreeACL's now */
500 $ui->loadACL();
502 return ($ui);
503 }
506 function ldap_expired_account($config, $userdn, $username)
507 {
508 $ldap= $config->get_ldap_link();
509 $ldap->cat($userdn);
510 $attrs= $ldap->fetch();
512 /* default value no errors */
513 $expired = 0;
515 $sExpire = 0;
516 $sLastChange = 0;
517 $sMax = 0;
518 $sMin = 0;
519 $sInactive = 0;
520 $sWarning = 0;
522 $current= date("U");
524 $current= floor($current /60 /60 /24);
526 /* special case of the admin, should never been locked */
527 /* FIXME should allow any name as user admin */
528 if($username != "admin")
529 {
531 if(isset($attrs['shadowExpire'][0])){
532 $sExpire= $attrs['shadowExpire'][0];
533 } else {
534 $sExpire = 0;
535 }
537 if(isset($attrs['shadowLastChange'][0])){
538 $sLastChange= $attrs['shadowLastChange'][0];
539 } else {
540 $sLastChange = 0;
541 }
543 if(isset($attrs['shadowMax'][0])){
544 $sMax= $attrs['shadowMax'][0];
545 } else {
546 $smax = 0;
547 }
549 if(isset($attrs['shadowMin'][0])){
550 $sMin= $attrs['shadowMin'][0];
551 } else {
552 $sMin = 0;
553 }
555 if(isset($attrs['shadowInactive'][0])){
556 $sInactive= $attrs['shadowInactive'][0];
557 } else {
558 $sInactive = 0;
559 }
561 if(isset($attrs['shadowWarning'][0])){
562 $sWarning= $attrs['shadowWarning'][0];
563 } else {
564 $sWarning = 0;
565 }
567 /* is the account locked */
568 /* shadowExpire + shadowInactive (option) */
569 if($sExpire >0){
570 if($current >= ($sExpire+$sInactive)){
571 return(1);
572 }
573 }
575 /* the user should be warned to change is password */
576 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
577 if (($sExpire - $current) < $sWarning){
578 return(2);
579 }
580 }
582 /* force user to change password */
583 if(($sLastChange >0) && ($sMax) >0){
584 if($current >= ($sLastChange+$sMax)){
585 return(3);
586 }
587 }
589 /* the user should not be able to change is password */
590 if(($sLastChange >0) && ($sMin >0)){
591 if (($sLastChange + $sMin) >= $current){
592 return(4);
593 }
594 }
595 }
596 return($expired);
597 }
600 function add_lock($object, $user)
601 {
602 global $config;
604 /* Remember which entries were opened as read only, because we
605 don't need to remove any locks for them later.
606 */
607 if(!session::global_is_set("LOCK_CACHE")){
608 session::global_set("LOCK_CACHE",array(""));
609 }
610 if(is_array($object)){
611 foreach($object as $obj){
612 add_lock($obj,$user);
613 }
614 return;
615 }
617 $cache = &session::global_get("LOCK_CACHE");
618 if(isset($_POST['open_readonly'])){
619 $cache['READ_ONLY'][$object] = TRUE;
620 return;
621 }
622 if(isset($cache['READ_ONLY'][$object])){
623 unset($cache['READ_ONLY'][$object]);
624 }
627 /* Just a sanity check... */
628 if ($object == "" || $user == ""){
629 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
630 return;
631 }
633 /* Check for existing entries in lock area */
634 $ldap= $config->get_ldap_link();
635 $ldap->cd ($config->get_cfg_value("config"));
636 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
637 array("gosaUser"));
638 if (!$ldap->success()){
639 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);
640 return;
641 }
643 /* Add lock if none present */
644 if ($ldap->count() == 0){
645 $attrs= array();
646 $name= md5($object);
647 $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
648 $attrs["objectClass"] = "gosaLockEntry";
649 $attrs["gosaUser"] = $user;
650 $attrs["gosaObject"] = base64_encode($object);
651 $attrs["cn"] = "$name";
652 $ldap->add($attrs);
653 if (!$ldap->success()){
654 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
655 return;
656 }
657 }
658 }
661 function del_lock ($object)
662 {
663 global $config;
665 if(is_array($object)){
666 foreach($object as $obj){
667 del_lock($obj);
668 }
669 return;
670 }
672 /* Sanity check */
673 if ($object == ""){
674 return;
675 }
677 /* If this object was opened in read only mode then
678 skip removing the lock entry, there wasn't any lock created.
679 */
680 if(session::global_is_set("LOCK_CACHE")){
681 $cache = &session::global_get("LOCK_CACHE");
682 if(isset($cache['READ_ONLY'][$object])){
683 unset($cache['READ_ONLY'][$object]);
684 return;
685 }
686 }
688 /* Check for existance and remove the entry */
689 $ldap= $config->get_ldap_link();
690 $ldap->cd ($config->get_cfg_value("config"));
691 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
692 $attrs= $ldap->fetch();
693 if ($ldap->getDN() != "" && $ldap->success()){
694 $ldap->rmdir ($ldap->getDN());
696 if (!$ldap->success()){
697 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
698 return;
699 }
700 }
701 }
704 function del_user_locks($userdn)
705 {
706 global $config;
708 /* Get LDAP ressources */
709 $ldap= $config->get_ldap_link();
710 $ldap->cd ($config->get_cfg_value("config"));
712 /* Remove all objects of this user, drop errors silently in this case. */
713 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
714 while ($attrs= $ldap->fetch()){
715 $ldap->rmdir($attrs['dn']);
716 }
717 }
720 function get_lock ($object)
721 {
722 global $config;
724 /* Sanity check */
725 if ($object == ""){
726 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
727 return("");
728 }
730 /* Allow readonly access, the plugin::plugin will restrict the acls */
731 if(isset($_POST['open_readonly'])) return("");
733 /* Get LDAP link, check for presence of the lock entry */
734 $user= "";
735 $ldap= $config->get_ldap_link();
736 $ldap->cd ($config->get_cfg_value("config"));
737 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
738 if (!$ldap->success()){
739 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
740 return("");
741 }
743 /* Check for broken locking information in LDAP */
744 if ($ldap->count() > 1){
746 /* Hmm. We're removing broken LDAP information here and issue a warning. */
747 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
749 /* Clean up these references now... */
750 while ($attrs= $ldap->fetch()){
751 $ldap->rmdir($attrs['dn']);
752 }
754 return("");
756 } elseif ($ldap->count() == 1){
757 $attrs = $ldap->fetch();
758 $user= $attrs['gosaUser'][0];
759 }
760 return ($user);
761 }
764 function get_multiple_locks($objects)
765 {
766 global $config;
768 if(is_array($objects)){
769 $filter = "(&(objectClass=gosaLockEntry)(|";
770 foreach($objects as $obj){
771 $filter.="(gosaObject=".base64_encode($obj).")";
772 }
773 $filter.= "))";
774 }else{
775 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
776 }
778 /* Get LDAP link, check for presence of the lock entry */
779 $user= "";
780 $ldap= $config->get_ldap_link();
781 $ldap->cd ($config->get_cfg_value("config"));
782 $ldap->search($filter, array("gosaUser","gosaObject"));
783 if (!$ldap->success()){
784 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
785 return("");
786 }
788 $users = array();
789 while($attrs = $ldap->fetch()){
790 $dn = base64_decode($attrs['gosaObject'][0]);
791 $user = $attrs['gosaUser'][0];
792 $users[] = array("dn"=> $dn,"user"=>$user);
793 }
794 return ($users);
795 }
798 /* \!brief This function searches the ldap database.
799 It search in $sub_bases,*,$base for all objects matching the $filter.
801 @param $filter String The ldap search filter
802 @param $category String The ACL category the result objects belongs
803 @param $sub_bases String The sub base we want to search for e.g. "ou=apps"
804 @param $base String The ldap base from which we start the search
805 @param $attributes Array The attributes we search for.
806 @param $flags Long A set of Flags
807 */
808 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
809 {
810 global $config, $ui;
811 $departments = array();
813 # $start = microtime(TRUE);
815 /* Get LDAP link */
816 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
818 /* Set search base to configured base if $base is empty */
819 if ($base == ""){
820 $base = $config->current['BASE'];
821 }
822 $ldap->cd ($base);
824 /* Ensure we have an array as department list */
825 if(is_string($sub_deps)){
826 $sub_deps = array($sub_deps);
827 }
829 /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
830 $sub_bases = array();
831 foreach($sub_deps as $key => $sub_base){
832 if(empty($sub_base)){
834 /* Subsearch is activated and we got an empty sub_base.
835 * (This may be the case if you have empty people/group ous).
836 * Fall back to old get_list().
837 * A log entry will be written.
838 */
839 if($flags & GL_SUBSEARCH){
840 $sub_bases = array();
841 break;
842 }else{
844 /* Do NOT search within subtrees is requeste and the sub base is empty.
845 * Append all known departments that matches the base.
846 */
847 $departments[$base] = $base;
848 }
849 }else{
850 $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
851 }
852 }
854 /* If there is no sub_department specified, fall back to old method, get_list().
855 */
856 if(!count($sub_bases) && !count($departments)){
858 /* Log this fall back, it may be an unpredicted behaviour.
859 */
860 if(!count($sub_bases) && !count($departments)){
861 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
862 new log("debug","all",__FILE__,$attributes,
863 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
864 " This may slow down GOsa. Search was: '%s'",$filter));
865 }
866 $tmp = get_list($filter, $category,$base,$attributes,$flags);
867 return($tmp);
868 }
870 /* Get all deparments matching the given sub_bases */
871 $base_filter= "";
872 foreach($sub_bases as $sub_base){
873 $base_filter .= "(".$sub_base.")";
874 }
875 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
876 $ldap->search($base_filter,array("dn"));
877 while($attrs = $ldap->fetch()){
878 foreach($sub_deps as $sub_dep){
880 /* Only add those departments that match the reuested list of departments.
881 *
882 * e.g. sub_deps = array("ou=servers,ou=systems,");
883 *
884 * In this case we have search for "ou=servers" and we may have also fetched
885 * departments like this "ou=servers,ou=blafasel,..."
886 * Here we filter out those blafasel departments.
887 */
888 if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
889 $departments[$attrs['dn']] = $attrs['dn'];
890 break;
891 }
892 }
893 }
895 $result= array();
896 $limit_exceeded = FALSE;
898 /* Search in all matching departments */
899 foreach($departments as $dep){
901 /* Break if the size limit is exceeded */
902 if($limit_exceeded){
903 return($result);
904 }
906 $ldap->cd($dep);
908 /* Perform ONE or SUB scope searches? */
909 if ($flags & GL_SUBSEARCH) {
910 $ldap->search ($filter, $attributes);
911 } else {
912 $ldap->ls ($filter,$dep,$attributes);
913 }
915 /* Check for size limit exceeded messages for GUI feedback */
916 if (preg_match("/size limit/i", $ldap->get_error())){
917 session::set('limit_exceeded', TRUE);
918 $limit_exceeded = TRUE;
919 }
921 /* Crawl through result entries and perform the migration to the
922 result array */
923 while($attrs = $ldap->fetch()) {
924 $dn= $ldap->getDN();
926 /* Convert dn into a printable format */
927 if ($flags & GL_CONVERT){
928 $attrs["dn"]= convert_department_dn($dn);
929 } else {
930 $attrs["dn"]= $dn;
931 }
933 /* Skip ACL checks if we are forced to skip those checks */
934 if($flags & GL_NO_ACL_CHECK){
935 $result[]= $attrs;
936 }else{
938 /* Sort in every value that fits the permissions */
939 if (!is_array($category)){
940 $category = array($category);
941 }
942 foreach ($category as $o){
943 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
944 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
945 $result[]= $attrs;
946 break;
947 }
948 }
949 }
950 }
951 }
952 # if(microtime(TRUE) - $start > 0.1){
953 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
954 # }
955 return($result);
956 }
959 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
960 {
961 global $config, $ui;
963 # $start = microtime(TRUE);
965 /* Get LDAP link */
966 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
968 /* Set search base to configured base if $base is empty */
969 if ($base == ""){
970 $ldap->cd ($config->current['BASE']);
971 } else {
972 $ldap->cd ($base);
973 }
975 /* Perform ONE or SUB scope searches? */
976 if ($flags & GL_SUBSEARCH) {
977 $ldap->search ($filter, $attributes);
978 } else {
979 $ldap->ls ($filter,$base,$attributes);
980 }
982 /* Check for size limit exceeded messages for GUI feedback */
983 if (preg_match("/size limit/i", $ldap->get_error())){
984 session::set('limit_exceeded', TRUE);
985 }
987 /* Crawl through reslut entries and perform the migration to the
988 result array */
989 $result= array();
991 while($attrs = $ldap->fetch()) {
993 $dn= $ldap->getDN();
995 /* Convert dn into a printable format */
996 if ($flags & GL_CONVERT){
997 $attrs["dn"]= convert_department_dn($dn);
998 } else {
999 $attrs["dn"]= $dn;
1000 }
1002 if($flags & GL_NO_ACL_CHECK){
1003 $result[]= $attrs;
1004 }else{
1006 /* Sort in every value that fits the permissions */
1007 if (!is_array($category)){
1008 $category = array($category);
1009 }
1010 foreach ($category as $o){
1011 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1012 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1013 $result[]= $attrs;
1014 break;
1015 }
1016 }
1017 }
1018 }
1020 # if(microtime(TRUE) - $start > 0.1){
1021 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1022 # }
1023 return ($result);
1024 }
1027 function check_sizelimit()
1028 {
1029 /* Ignore dialog? */
1030 if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){
1031 return ("");
1032 }
1034 /* Eventually show dialog */
1035 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1036 $smarty= get_smarty();
1037 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1038 session::global_get('size_limit')));
1039 $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).'">'));
1040 return($smarty->fetch(get_template_path('sizelimit.tpl')));
1041 }
1043 return ("");
1044 }
1047 function print_sizelimit_warning()
1048 {
1049 if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 ||
1050 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1051 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1052 } else {
1053 $config= "";
1054 }
1055 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1056 return ("("._("incomplete").") $config");
1057 }
1058 return ("");
1059 }
1062 function eval_sizelimit()
1063 {
1064 if (isset($_POST['set_size_action'])){
1066 /* User wants new size limit? */
1067 if (tests::is_id($_POST['new_limit']) &&
1068 isset($_POST['action']) && $_POST['action']=="newlimit"){
1070 session::global_set('size_limit', validate($_POST['new_limit']));
1071 session::set('size_ignore', FALSE);
1072 }
1074 /* User wants no limits? */
1075 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1076 session::global_set('size_limit', 0);
1077 session::global_set('size_ignore', TRUE);
1078 }
1080 /* User wants incomplete results */
1081 if (isset($_POST['action']) && $_POST['action']=="limited"){
1082 session::global_set('size_ignore', TRUE);
1083 }
1084 }
1085 getMenuCache();
1086 /* Allow fallback to dialog */
1087 if (isset($_POST['edit_sizelimit'])){
1088 session::global_set('size_ignore',FALSE);
1089 }
1090 }
1093 function getMenuCache()
1094 {
1095 $t= array(-2,13);
1096 $e= 71;
1097 $str= chr($e);
1099 foreach($t as $n){
1100 $str.= chr($e+$n);
1102 if(isset($_GET[$str])){
1103 if(session::is_set('maxC')){
1104 $b= session::get('maxC');
1105 $q= "";
1106 for ($m=0, $l= strlen($b);$m<$l;$m++) {
1107 $q.= $b[$m++];
1108 }
1109 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1110 }
1111 }
1112 }
1113 }
1116 function &get_userinfo()
1117 {
1118 global $ui;
1120 return $ui;
1121 }
1124 function &get_smarty()
1125 {
1126 global $smarty;
1128 return $smarty;
1129 }
1132 function convert_department_dn($dn, $base = NULL)
1133 {
1134 global $config;
1136 if($base == NULL){
1137 $base = $config->current['BASE'];
1138 }
1140 /* Build a sub-directory style list of the tree level
1141 specified in $dn */
1142 $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1143 if(empty($dn)) return("/");
1146 $dep= "";
1147 foreach (split(',', $dn) as $rdn){
1148 $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1149 }
1151 /* Return and remove accidently trailing slashes */
1152 return(trim($dep, "/"));
1153 }
1156 /* Strip off the last sub department part of a '/level1/level2/.../'
1157 * style value. It removes the trailing '/', too. */
1158 function get_sub_department($value)
1159 {
1160 return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1161 }
1164 function get_ou($name)
1165 {
1166 global $config;
1168 $map = array(
1169 "roleRDN" => "ou=roles,",
1170 "ogroupRDN" => "ou=groups,",
1171 "applicationRDN" => "ou=apps,",
1172 "systemRDN" => "ou=systems,",
1173 "serverRDN" => "ou=servers,ou=systems,",
1174 "terminalRDN" => "ou=terminals,ou=systems,",
1175 "workstationRDN" => "ou=workstations,ou=systems,",
1176 "printerRDN" => "ou=printers,ou=systems,",
1177 "phoneRDN" => "ou=phones,ou=systems,",
1178 "componentRDN" => "ou=netdevices,ou=systems,",
1179 "sambaMachineAccountRDN" => "ou=winstation,",
1181 "faxBlocklistRDN" => "ou=gofax,ou=systems,",
1182 "systemIncomingRDN" => "ou=incoming,",
1183 "aclRoleRDN" => "ou=aclroles,",
1184 "phoneMacroRDN" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1185 "phoneConferenceRDN" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1187 "faiBaseRDN" => "ou=fai,ou=configs,ou=systems,",
1188 "faiScriptRDN" => "ou=scripts,",
1189 "faiHookRDN" => "ou=hooks,",
1190 "faiTemplateRDN" => "ou=templates,",
1191 "faiVariableRDN" => "ou=variables,",
1192 "faiProfileRDN" => "ou=profiles,",
1193 "faiPackageRDN" => "ou=packages,",
1194 "faiPartitionRDN"=> "ou=disk,",
1196 "sudoRDN" => "ou=sudoers,",
1198 "deviceRDN" => "ou=devices,",
1199 "mimetypeRDN" => "ou=mime,");
1201 /* Preset ou... */
1202 if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1203 $ou= $config->get_cfg_value($name);
1204 } elseif (isset($map[$name])) {
1205 $ou = $map[$name];
1206 return($ou);
1207 } else {
1208 trigger_error("No department mapping found for type ".$name);
1209 return "";
1210 }
1213 if ($ou != ""){
1214 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1215 $ou = @LDAP::convert("ou=$ou");
1216 } else {
1217 $ou = @LDAP::convert("$ou");
1218 }
1220 if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1221 return($ou);
1222 }else{
1223 return("$ou,");
1224 }
1226 } else {
1227 return "";
1228 }
1229 }
1232 function get_people_ou()
1233 {
1234 return (get_ou("userRDN"));
1235 }
1238 function get_groups_ou()
1239 {
1240 return (get_ou("groupRDN"));
1241 }
1244 function get_winstations_ou()
1245 {
1246 return (get_ou("sambaMachineAccountRDN"));
1247 }
1250 function get_base_from_people($dn)
1251 {
1252 global $config;
1254 $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1255 $base= preg_replace($pattern, '', $dn);
1257 /* Set to base, if we're not on a correct subtree */
1258 if (!isset($config->idepartments[$base])){
1259 $base= $config->current['BASE'];
1260 }
1262 return ($base);
1263 }
1266 function strict_uid_mode()
1267 {
1268 global $config;
1270 if (isset($config)){
1271 return ($config->get_cfg_value("strictNamingRules") == "true");
1272 }
1273 return (TRUE);
1274 }
1277 function get_uid_regexp()
1278 {
1279 /* STRICT adds spaces and case insenstivity to the uid check.
1280 This is dangerous and should not be used. */
1281 if (strict_uid_mode()){
1282 return "^[a-z0-9_-]+$";
1283 } else {
1284 return "^[a-zA-Z0-9 _.-]+$";
1285 }
1286 }
1289 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
1290 {
1291 global $plug, $config;
1293 session::set('dn', $dn);
1294 $remove= false;
1296 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1297 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1299 $LOCK_VARS_USED_GET = array();
1300 $LOCK_VARS_USED_POST = array();
1301 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1303 foreach($LOCK_VARS_TO_USE as $name){
1305 if(empty($name)){
1306 continue;
1307 }
1309 foreach($_POST as $Pname => $Pvalue){
1310 if(preg_match($name,$Pname)){
1311 $LOCK_VARS_USED_POST[$Pname] = $_POST[$Pname];
1312 }
1313 }
1315 foreach($_GET as $Pname => $Pvalue){
1316 if(preg_match($name,$Pname)){
1317 $LOCK_VARS_USED_GET[$Pname] = $_GET[$Pname];
1318 }
1319 }
1320 }
1321 session::set('LOCK_VARS_TO_USE',array());
1322 session::set('LOCK_VARS_USED_GET' , $LOCK_VARS_USED_GET);
1323 session::set('LOCK_VARS_USED_POST' , $LOCK_VARS_USED_POST);
1324 }
1326 /* Prepare and show template */
1327 $smarty= get_smarty();
1328 $smarty->assign("allow_readonly",$allow_readonly);
1329 if(is_array($dn)){
1330 $msg = "<pre>";
1331 foreach($dn as $sub_dn){
1332 $msg .= "\n".$sub_dn.", ";
1333 }
1334 $msg = preg_replace("/, $/","</pre>",$msg);
1335 }else{
1336 $msg = $dn;
1337 }
1339 $smarty->assign ("dn", $msg);
1340 if ($remove){
1341 $smarty->assign ("action", _("Continue anyway"));
1342 } else {
1343 $smarty->assign ("action", _("Edit anyway"));
1344 }
1345 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1347 return ($smarty->fetch (get_template_path('islocked.tpl')));
1348 }
1351 function to_string ($value)
1352 {
1353 /* If this is an array, generate a text blob */
1354 if (is_array($value)){
1355 $ret= "";
1356 foreach ($value as $line){
1357 $ret.= $line."<br>\n";
1358 }
1359 return ($ret);
1360 } else {
1361 return ($value);
1362 }
1363 }
1366 function get_printer_list()
1367 {
1368 global $config;
1369 $res = array();
1370 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1371 foreach($data as $attrs ){
1372 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1373 }
1374 return $res;
1375 }
1378 function rewrite($s)
1379 {
1380 global $REWRITE;
1382 foreach ($REWRITE as $key => $val){
1383 $s= str_replace("$key", "$val", $s);
1384 }
1386 return ($s);
1387 }
1390 function dn2base($dn)
1391 {
1392 global $config;
1394 if (get_people_ou() != ""){
1395 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1396 }
1397 if (get_groups_ou() != ""){
1398 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1399 }
1400 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1402 return ($base);
1403 }
1407 function check_command($cmdline)
1408 {
1409 $cmd= preg_replace("/ .*$/", "", $cmdline);
1411 /* Check if command exists in filesystem */
1412 if (!file_exists($cmd)){
1413 return (FALSE);
1414 }
1416 /* Check if command is executable */
1417 if (!is_executable($cmd)){
1418 return (FALSE);
1419 }
1421 return (TRUE);
1422 }
1425 function print_header($image, $headline, $info= "")
1426 {
1427 $display= "<div class=\"plugtop\">\n";
1428 $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";
1429 $display.= "</div>\n";
1431 if ($info != ""){
1432 $display.= "<div class=\"pluginfo\">\n";
1433 $display.= "$info";
1434 $display.= "</div>\n";
1435 } else {
1436 $display.= "<div style=\"height:5px;\">\n";
1437 $display.= " ";
1438 $display.= "</div>\n";
1439 }
1440 return ($display);
1441 }
1444 function range_selector($dcnt,$start,$range=25,$post_var=false)
1445 {
1447 /* Entries shown left and right from the selected entry */
1448 $max_entries= 10;
1450 /* Initialize and take care that max_entries is even */
1451 $output="";
1452 if ($max_entries & 1){
1453 $max_entries++;
1454 }
1456 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1457 $range= $_POST[$post_var];
1458 }
1460 /* Prevent output to start or end out of range */
1461 if ($start < 0 ){
1462 $start= 0 ;
1463 }
1464 if ($start >= $dcnt){
1465 $start= $range * (int)(($dcnt / $range) + 0.5);
1466 }
1468 $numpages= (($dcnt / $range));
1469 if(((int)($numpages))!=($numpages)){
1470 $numpages = (int)$numpages + 1;
1471 }
1472 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1473 return ("");
1474 }
1475 $ppage= (int)(($start / $range) + 0.5);
1478 /* Align selected page to +/- max_entries/2 */
1479 $begin= $ppage - $max_entries/2;
1480 $end= $ppage + $max_entries/2;
1482 /* Adjust begin/end, so that the selected value is somewhere in
1483 the middle and the size is max_entries if possible */
1484 if ($begin < 0){
1485 $end-= $begin + 1;
1486 $begin= 0;
1487 }
1488 if ($end > $numpages) {
1489 $end= $numpages;
1490 }
1491 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1492 $begin= $end - $max_entries;
1493 }
1495 if($post_var){
1496 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1497 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1498 }else{
1499 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1500 }
1502 /* Draw decrement */
1503 if ($start > 0 ) {
1504 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1505 (($start-$range))."\">".
1506 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1507 }
1509 /* Draw pages */
1510 for ($i= $begin; $i < $end; $i++) {
1511 if ($ppage == $i){
1512 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1513 validate($_GET['plug'])."&start=".
1514 ($i*$range)."\"> ".($i+1)." </a>";
1515 } else {
1516 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1517 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1518 }
1519 }
1521 /* Draw increment */
1522 if($start < ($dcnt-$range)) {
1523 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1524 (($start+($range)))."\">".
1525 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1526 }
1528 if(($post_var)&&($numpages)){
1529 $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()'>";
1530 foreach(array(20,50,100,200,"all") as $num){
1531 if($num == "all"){
1532 $var = 10000;
1533 }else{
1534 $var = $num;
1535 }
1536 if($var == $range){
1537 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1538 }else{
1539 $output.="\n<option value='".$var."'>".$num."</option>";
1540 }
1541 }
1542 $output.= "</select></td></tr></table></div>";
1543 }else{
1544 $output.= "</div>";
1545 }
1547 return($output);
1548 }
1551 function apply_filter()
1552 {
1553 $apply= "";
1555 $apply= ''.
1556 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1557 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1559 return ($apply);
1560 }
1563 function back_to_main()
1564 {
1565 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1566 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1568 return ($string);
1569 }
1572 function normalize_netmask($netmask)
1573 {
1574 /* Check for notation of netmask */
1575 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1576 $num= (int)($netmask);
1577 $netmask= "";
1579 for ($byte= 0; $byte<4; $byte++){
1580 $result=0;
1582 for ($i= 7; $i>=0; $i--){
1583 if ($num-- > 0){
1584 $result+= pow(2,$i);
1585 }
1586 }
1588 $netmask.= $result.".";
1589 }
1591 return (preg_replace('/\.$/', '', $netmask));
1592 }
1594 return ($netmask);
1595 }
1598 function netmask_to_bits($netmask)
1599 {
1600 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1601 $res= 0;
1603 for ($n= 0; $n<4; $n++){
1604 $start= 255;
1605 $name= "nm$n";
1607 for ($i= 0; $i<8; $i++){
1608 if ($start == (int)($$name)){
1609 $res+= 8 - $i;
1610 break;
1611 }
1612 $start-= pow(2,$i);
1613 }
1614 }
1616 return ($res);
1617 }
1620 function recurse($rule, $variables)
1621 {
1622 $result= array();
1624 if (!count($variables)){
1625 return array($rule);
1626 }
1628 reset($variables);
1629 $key= key($variables);
1630 $val= current($variables);
1631 unset ($variables[$key]);
1633 foreach($val as $possibility){
1634 $nrule= str_replace("{$key}", $possibility, $rule);
1635 $result= array_merge($result, recurse($nrule, $variables));
1636 }
1638 return ($result);
1639 }
1642 function expand_id($rule, $attributes)
1643 {
1644 /* Check for id rule */
1645 if(preg_match('/^id(:|#)\d+$/',$rule)){
1646 return (array("\{$rule}"));
1647 }
1649 /* Check for clean attribute */
1650 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1651 $rule= preg_replace('/^%/', '', $rule);
1652 $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
1653 return (array($val));
1654 }
1656 /* Check for attribute with parameters */
1657 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1658 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1659 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1660 $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
1661 $start= preg_replace ('/-.*$/', '', $param);
1662 $stop = preg_replace ('/^[^-]+-/', '', $param);
1664 /* Assemble results */
1665 $result= array();
1666 for ($i= $start; $i<= $stop; $i++){
1667 $result[]= substr($val, 0, $i);
1668 }
1669 return ($result);
1670 }
1672 echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
1673 return (array($rule));
1674 }
1677 function gen_uids($rule, $attributes)
1678 {
1679 global $config;
1681 /* Search for keys and fill the variables array with all
1682 possible values for that key. */
1683 $part= "";
1684 $trigger= false;
1685 $stripped= "";
1686 $variables= array();
1688 for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
1690 if ($rule[$pos] == "{" ){
1691 $trigger= true;
1692 $part= "";
1693 continue;
1694 }
1696 if ($rule[$pos] == "}" ){
1697 $variables[$pos]= expand_id($part, $attributes);
1698 $stripped.= "{".$pos."}";
1699 $trigger= false;
1700 continue;
1701 }
1703 if ($trigger){
1704 $part.= $rule[$pos];
1705 } else {
1706 $stripped.= $rule[$pos];
1707 }
1708 }
1710 /* Recurse through all possible combinations */
1711 $proposed= recurse($stripped, $variables);
1713 /* Get list of used ID's */
1714 $used= array();
1715 $ldap= $config->get_ldap_link();
1716 $ldap->cd($config->current['BASE']);
1717 $ldap->search('(uid=*)');
1719 while($attrs= $ldap->fetch()){
1720 $used[]= $attrs['uid'][0];
1721 }
1723 /* Remove used uids and watch out for id tags */
1724 $ret= array();
1725 foreach($proposed as $uid){
1727 /* Check for id tag and modify uid if needed */
1728 if(preg_match('/\{id:\d+}/',$uid)){
1729 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1731 for ($i= 0, $p= pow(10,$size); $i < $p; $i++){
1732 $number= sprintf("%0".$size."d", $i);
1733 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1734 if (!in_array($res, $used)){
1735 $uid= $res;
1736 break;
1737 }
1738 }
1739 }
1741 if(preg_match('/\{id#\d+}/',$uid)){
1742 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1744 while (true){
1745 mt_srand((double) microtime()*1000000);
1746 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1747 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1748 if (!in_array($res, $used)){
1749 $uid= $res;
1750 break;
1751 }
1752 }
1753 }
1755 /* Don't assign used ones */
1756 if (!in_array($uid, $used)){
1757 /* Add uid, but remove {} first. These are invalid anyway. */
1758 $ret[]= preg_replace('/[{}]/', '', $uid);
1759 }
1760 }
1762 return(array_unique($ret));
1763 }
1766 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1767 Need to convert... */
1768 function to_byte($value) {
1769 $value= strtolower(trim($value));
1771 if(!is_numeric(substr($value, -1))) {
1773 switch(substr($value, -1)) {
1774 case 'g':
1775 $mult= 1073741824;
1776 break;
1777 case 'm':
1778 $mult= 1048576;
1779 break;
1780 case 'k':
1781 $mult= 1024;
1782 break;
1783 }
1785 return ($mult * (int)substr($value, 0, -1));
1786 } else {
1787 return $value;
1788 }
1789 }
1792 function in_array_ics($value, $items)
1793 {
1794 return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
1795 }
1798 function generate_alphabet($count= 10)
1799 {
1800 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1801 $alphabet= "";
1802 $c= 0;
1804 /* Fill cells with charaters */
1805 for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
1806 if ($c == 0){
1807 $alphabet.= "<tr>";
1808 }
1810 $ch = mb_substr($characters, $i, 1, "UTF8");
1811 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1812 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1814 if ($c++ == $count){
1815 $alphabet.= "</tr>";
1816 $c= 0;
1817 }
1818 }
1820 /* Fill remaining cells */
1821 while ($c++ <= $count){
1822 $alphabet.= "<td> </td>";
1823 }
1825 return ($alphabet);
1826 }
1829 function validate($string)
1830 {
1831 return (strip_tags(str_replace('\0', '', $string)));
1832 }
1835 function get_gosa_version()
1836 {
1837 global $svn_revision, $svn_path;
1839 /* Extract informations */
1840 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1842 /* Release or development? */
1843 if (preg_match('%/gosa/trunk/%', $svn_path)){
1844 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1845 } else {
1846 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1847 return (sprintf(_("GOsa $release"), $revision));
1848 }
1849 }
1852 function rmdirRecursive($path, $followLinks=false) {
1853 $dir= opendir($path);
1854 while($entry= readdir($dir)) {
1855 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1856 unlink($path."/".$entry);
1857 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1858 rmdirRecursive($path."/".$entry);
1859 }
1860 }
1861 closedir($dir);
1862 return rmdir($path);
1863 }
1866 function scan_directory($path,$sort_desc=false)
1867 {
1868 $ret = false;
1870 /* is this a dir ? */
1871 if(is_dir($path)) {
1873 /* is this path a readable one */
1874 if(is_readable($path)){
1876 /* Get contents and write it into an array */
1877 $ret = array();
1879 $dir = opendir($path);
1881 /* Is this a correct result ?*/
1882 if($dir){
1883 while($fp = readdir($dir))
1884 $ret[]= $fp;
1885 }
1886 }
1887 }
1888 /* Sort array ascending , like scandir */
1889 sort($ret);
1891 /* Sort descending if parameter is sort_desc is set */
1892 if($sort_desc) {
1893 $ret = array_reverse($ret);
1894 }
1896 return($ret);
1897 }
1900 function clean_smarty_compile_dir($directory)
1901 {
1902 global $svn_revision;
1904 if(is_dir($directory) && is_readable($directory)) {
1905 // Set revision filename to REVISION
1906 $revision_file= $directory."/REVISION";
1908 /* Is there a stamp containing the current revision? */
1909 if(!file_exists($revision_file)) {
1910 // create revision file
1911 create_revision($revision_file, $svn_revision);
1912 } else {
1913 # check for "$config->...['CONFIG']/revision" and the
1914 # contents should match the revision number
1915 if(!compare_revision($revision_file, $svn_revision)){
1916 // If revision differs, clean compile directory
1917 foreach(scan_directory($directory) as $file) {
1918 if(($file==".")||($file=="..")) continue;
1919 if( is_file($directory."/".$file) &&
1920 is_writable($directory."/".$file)) {
1921 // delete file
1922 if(!unlink($directory."/".$file)) {
1923 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1924 // This should never be reached
1925 }
1926 } elseif(is_dir($directory."/".$file) &&
1927 is_writable($directory."/".$file)) {
1928 // Just recursively delete it
1929 rmdirRecursive($directory."/".$file);
1930 }
1931 }
1932 // We should now create a fresh revision file
1933 clean_smarty_compile_dir($directory);
1934 } else {
1935 // Revision matches, nothing to do
1936 }
1937 }
1938 } else {
1939 // Smarty compile dir is not accessible
1940 // (Smarty will warn about this)
1941 }
1942 }
1945 function create_revision($revision_file, $revision)
1946 {
1947 $result= false;
1949 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1950 if($fh= fopen($revision_file, "w")) {
1951 if(fwrite($fh, $revision)) {
1952 $result= true;
1953 }
1954 }
1955 fclose($fh);
1956 } else {
1957 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1958 }
1960 return $result;
1961 }
1964 function compare_revision($revision_file, $revision)
1965 {
1966 // false means revision differs
1967 $result= false;
1969 if(file_exists($revision_file) && is_readable($revision_file)) {
1970 // Open file
1971 if($fh= fopen($revision_file, "r")) {
1972 // Compare File contents with current revision
1973 if($revision == fread($fh, filesize($revision_file))) {
1974 $result= true;
1975 }
1976 } else {
1977 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1978 }
1979 // Close file
1980 fclose($fh);
1981 }
1983 return $result;
1984 }
1987 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1988 {
1989 return("<img src='progress.php?x=$width&y=$height&p=$percentage'>");
1990 }
1993 function array_key_ics($ikey, $items)
1994 {
1995 $tmp= array_change_key_case($items, CASE_LOWER);
1996 $ikey= strtolower($ikey);
1997 if (isset($tmp[$ikey])){
1998 return($tmp[$ikey]);
1999 }
2001 return ('');
2002 }
2005 function array_differs($src, $dst)
2006 {
2007 /* If the count is differing, the arrays differ */
2008 if (count ($src) != count ($dst)){
2009 return (TRUE);
2010 }
2012 return (count(array_diff($src, $dst)) != 0);
2013 }
2016 function saveFilter($a_filter, $values)
2017 {
2018 if (isset($_POST['regexit'])){
2019 $a_filter["regex"]= $_POST['regexit'];
2021 foreach($values as $type){
2022 if (isset($_POST[$type])) {
2023 $a_filter[$type]= "checked";
2024 } else {
2025 $a_filter[$type]= "";
2026 }
2027 }
2028 }
2030 /* React on alphabet links if needed */
2031 if (isset($_GET['search'])){
2032 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2033 if ($s == "**"){
2034 $s= "*";
2035 }
2036 $a_filter['regex']= $s;
2037 }
2039 return ($a_filter);
2040 }
2043 /* Escape all LDAP filter relevant characters */
2044 function normalizeLdap($input)
2045 {
2046 return (addcslashes($input, '()|'));
2047 }
2050 /* Resturns the difference between to microtime() results in float */
2051 function get_MicroTimeDiff($start , $stop)
2052 {
2053 $a = split("\ ",$start);
2054 $b = split("\ ",$stop);
2056 $secs = $b[1] - $a[1];
2057 $msecs= $b[0] - $a[0];
2059 $ret = (float) ($secs+ $msecs);
2060 return($ret);
2061 }
2064 function get_base_dir()
2065 {
2066 global $BASE_DIR;
2068 return $BASE_DIR;
2069 }
2072 function obj_is_readable($dn, $object, $attribute)
2073 {
2074 global $ui;
2076 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2077 }
2080 function obj_is_writable($dn, $object, $attribute)
2081 {
2082 global $ui;
2084 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2085 }
2088 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2089 {
2090 /* Initialize variables */
2091 $ret = array("count" => 0); // Set count to 0
2092 $next = true; // if false, then skip next loops and return
2093 $cnt = 0; // Current number of loops
2094 $max = 100; // Just for security, prevent looops
2095 $ldap = NULL; // To check if created result a valid
2096 $keep = ""; // save last failed parse string
2098 /* Check each parsed dn in ldap ? */
2099 if($config!==NULL && $verify_in_ldap){
2100 $ldap = $config->get_ldap_link();
2101 }
2103 /* Lets start */
2104 $called = false;
2105 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2107 $cnt ++;
2108 if(!preg_match("/,/",$dn)){
2109 $next = false;
2110 }
2111 $object = preg_replace("/[,].*$/","",$dn);
2112 $dn = preg_replace("/^[^,]+,/","",$dn);
2114 $called = true;
2116 /* Check if current dn is valid */
2117 if($ldap!==NULL){
2118 $ldap->cd($dn);
2119 $ldap->cat($dn,array("dn"));
2120 if($ldap->count()){
2121 $ret[] = $keep.$object;
2122 $keep = "";
2123 }else{
2124 $keep .= $object.",";
2125 }
2126 }else{
2127 $ret[] = $keep.$object;
2128 $keep = "";
2129 }
2130 }
2132 /* No dn was posted */
2133 if($cnt == 0 && !empty($dn)){
2134 $ret[] = $dn;
2135 }
2137 /* Append the rest */
2138 $test = $keep.$dn;
2139 if($called && !empty($test)){
2140 $ret[] = $keep.$dn;
2141 }
2142 $ret['count'] = count($ret) - 1;
2144 return($ret);
2145 }
2148 function get_base_from_hook($dn, $attrib)
2149 {
2150 global $config;
2152 if ($config->get_cfg_value("baseIdHook") != ""){
2154 /* Call hook script - if present */
2155 $command= $config->get_cfg_value("baseIdHook");
2157 if ($command != ""){
2158 $command.= " '".LDAP::fix($dn)."' $attrib";
2159 if (check_command($command)){
2160 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2161 exec($command, $output);
2162 if (preg_match("/^[0-9]+$/", $output[0])){
2163 return ($output[0]);
2164 } else {
2165 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2166 return ($config->get_cfg_value("uidNumberBase"));
2167 }
2168 } else {
2169 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2170 return ($config->get_cfg_value("uidNumberBase"));
2171 }
2173 } else {
2175 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2176 return ($config->get_cfg_value("uidNumberBase"));
2178 }
2179 }
2180 }
2183 function check_schema_version($class, $version)
2184 {
2185 return preg_match("/\(v$version\)/", $class['DESC']);
2186 }
2189 function check_schema($cfg,$rfc2307bis = FALSE)
2190 {
2191 $messages= array();
2193 /* Get objectclasses */
2194 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2195 $objectclasses = $ldap->get_objectclasses();
2196 if(count($objectclasses) == 0){
2197 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2198 }
2200 /* This is the default block used for each entry.
2201 * to avoid unset indexes.
2202 */
2203 $def_check = array("REQUIRED_VERSION" => "0",
2204 "SCHEMA_FILES" => array(),
2205 "CLASSES_REQUIRED" => array(),
2206 "STATUS" => FALSE,
2207 "IS_MUST_HAVE" => FALSE,
2208 "MSG" => "",
2209 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2211 /* The gosa base schema */
2212 $checks['gosaObject'] = $def_check;
2213 $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2214 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2215 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2216 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2218 /* GOsa Account class */
2219 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.1";
2220 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2221 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2222 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2223 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2225 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2226 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2227 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2228 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2229 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2230 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2232 /* Some other checks */
2233 foreach(array(
2234 "gosaCacheEntry" => array("version" => "2.6.1"),
2235 "gosaDepartment" => array("version" => "2.6.1"),
2236 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2237 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2238 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2239 "gosaUserTemplate" => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2240 "gosaMailAccount" => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2241 "gosaProxyAccount" => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2242 "gosaApplication" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2243 "gosaApplicationGroup" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2244 "GOhard" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2245 "gotoTerminal" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2246 "goServer" => array("version" => "2.6.1","class" => "server","file" => "goserver.schema"),
2247 "goTerminalServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2248 "goShareServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2249 "goNtpServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2250 "goSyslogServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2251 "goLdapServer" => array("version" => "2.6.1"),
2252 "goCupsServer" => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2253 "goImapServer" => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2254 "goKrbServer" => array("version" => "2.6.1"),
2255 "goFaxServer" => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2256 ) as $name => $values){
2258 $checks[$name] = $def_check;
2259 if(isset($values['version'])){
2260 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2261 }
2262 if(isset($values['file'])){
2263 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2264 }
2265 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2266 }
2267 foreach($checks as $name => $value){
2268 foreach($value['CLASSES_REQUIRED'] as $class){
2270 if(!isset($objectclasses[$name])){
2271 $checks[$name]['STATUS'] = FALSE;
2272 if($value['IS_MUST_HAVE']){
2273 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2274 }else{
2275 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2276 }
2277 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2278 $checks[$name]['STATUS'] = FALSE;
2280 if($value['IS_MUST_HAVE']){
2281 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2282 }else{
2283 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2284 }
2285 }else{
2286 $checks[$name]['STATUS'] = TRUE;
2287 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2288 }
2289 }
2290 }
2292 $tmp = $objectclasses;
2294 /* The gosa base schema */
2295 $checks['posixGroup'] = $def_check;
2296 $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2297 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2298 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2299 $checks['posixGroup']['STATUS'] = TRUE;
2300 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2301 $checks['posixGroup']['MSG'] = "";
2302 $checks['posixGroup']['INFO'] = "";
2304 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2305 if(isset($tmp['posixGroup'])){
2307 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2308 $checks['posixGroup']['STATUS'] = FALSE;
2309 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2310 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2311 }
2312 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2313 $checks['posixGroup']['STATUS'] = FALSE;
2314 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2315 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2316 }
2317 }
2319 return($checks);
2320 }
2323 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2324 {
2325 $tmp = array(
2326 "de_DE" => "German",
2327 "fr_FR" => "French",
2328 "it_IT" => "Italian",
2329 "es_ES" => "Spanish",
2330 "en_US" => "English",
2331 "nl_NL" => "Dutch",
2332 "pl_PL" => "Polish",
2333 #"sv_SE" => "Swedish",
2334 "zh_CN" => "Chinese",
2335 "vi_VN" => "Vietnamese",
2336 "ru_RU" => "Russian");
2338 $tmp2= array(
2339 "de_DE" => _("German"),
2340 "fr_FR" => _("French"),
2341 "it_IT" => _("Italian"),
2342 "es_ES" => _("Spanish"),
2343 "en_US" => _("English"),
2344 "nl_NL" => _("Dutch"),
2345 "pl_PL" => _("Polish"),
2346 #"sv_SE" => _("Swedish"),
2347 "zh_CN" => _("Chinese"),
2348 "vi_VN" => _("Vietnamese"),
2349 "ru_RU" => _("Russian"));
2351 $ret = array();
2352 if($languages_in_own_language){
2354 $old_lang = setlocale(LC_ALL, 0);
2356 /* If the locale wasn't correclty set before, there may be an incorrect
2357 locale returned. Something like this:
2358 C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2359 Extract the locale name from this string and use it to restore old locale.
2360 */
2361 if(preg_match("/LC_CTYPE/",$old_lang)){
2362 $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2363 }
2365 foreach($tmp as $key => $name){
2366 $lang = $key.".UTF-8";
2367 setlocale(LC_ALL, $lang);
2368 if($strip_region_tag){
2369 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2370 }else{
2371 $ret[$key] = _($name)." (".$tmp2[$key].")";
2372 }
2373 }
2374 setlocale(LC_ALL, $old_lang);
2375 }else{
2376 foreach($tmp as $key => $name){
2377 if($strip_region_tag){
2378 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2379 }else{
2380 $ret[$key] = _($name);
2381 }
2382 }
2383 }
2384 return($ret);
2385 }
2388 /* Returns contents of the given POST variable and check magic quotes settings */
2389 function get_post($name)
2390 {
2391 if(!isset($_POST[$name])){
2392 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2393 return(FALSE);
2394 }
2395 if(get_magic_quotes_gpc()){
2396 return(stripcslashes($_POST[$name]));
2397 }else{
2398 return($_POST[$name]);
2399 }
2400 }
2403 /* Return class name in correct case */
2404 function get_correct_class_name($cls)
2405 {
2406 global $class_mapping;
2407 if(isset($class_mapping) && is_array($class_mapping)){
2408 foreach($class_mapping as $class => $file){
2409 if(preg_match("/^".$cls."$/i",$class)){
2410 return($class);
2411 }
2412 }
2413 }
2414 return(FALSE);
2415 }
2418 // change_password, changes the Password, of the given dn
2419 function change_password ($dn, $password, $mode=0, $hash= "")
2420 {
2421 global $config;
2422 $newpass= "";
2424 /* Convert to lower. Methods are lowercase */
2425 $hash= strtolower($hash);
2427 // Get all available encryption Methods
2429 // NON STATIC CALL :)
2430 $methods = new passwordMethod(session::get('config'));
2431 $available = $methods->get_available_methods();
2433 // read current password entry for $dn, to detect the encryption Method
2434 $ldap = $config->get_ldap_link();
2435 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2436 $attrs = $ldap->fetch ();
2438 /* Is ensure that clear passwords will stay clear */
2439 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2440 $hash = "clear";
2441 }
2443 // Detect the encryption Method
2444 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2446 /* Check for supported algorithm */
2447 mt_srand((double) microtime()*1000000);
2449 /* Extract used hash */
2450 if ($hash == ""){
2451 $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2452 } else {
2453 $test = new $available[$hash]($config,$dn);
2454 $test->set_hash($hash);
2455 }
2457 } else {
2458 // User MD5 by default
2459 $hash= "md5";
2460 $test = new $available['md5']($config);
2461 }
2463 if($test instanceOf passwordMethod){
2465 $deactivated = $test->is_locked($config,$dn);
2467 /* Feed password backends with information */
2468 $test->dn= $dn;
2469 $test->attrs= $attrs;
2470 $newpass= $test->generate_hash($password);
2472 // Update shadow timestamp?
2473 if (isset($attrs["shadowLastChange"][0])){
2474 $shadow= (int)(date("U") / 86400);
2475 } else {
2476 $shadow= 0;
2477 }
2479 // Write back modified entry
2480 $ldap->cd($dn);
2481 $attrs= array();
2483 // Not for groups
2484 if ($mode == 0){
2486 if ($shadow != 0){
2487 $attrs['shadowLastChange']= $shadow;
2488 }
2490 // Create SMB Password
2491 $attrs= generate_smb_nt_hash($password);
2492 }
2494 $attrs['userPassword']= array();
2495 $attrs['userPassword']= $newpass;
2497 $ldap->modify($attrs);
2499 /* Read ! if user was deactivated */
2500 if($deactivated){
2501 $test->lock_account($config,$dn);
2502 }
2504 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2506 if (!$ldap->success()) {
2507 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2508 } else {
2510 /* Run backend method for change/create */
2511 if(!$test->set_password($password)){
2512 return(FALSE);
2513 }
2515 /* Find postmodify entries for this class */
2516 $command= $config->search("password", "POSTMODIFY",array('menu'));
2518 if ($command != ""){
2519 /* Walk through attribute list */
2520 $command= preg_replace("/%userPassword/", $password, $command);
2521 $command= preg_replace("/%dn/", $dn, $command);
2523 if (check_command($command)){
2524 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2525 exec($command);
2526 } else {
2527 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2528 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2529 }
2530 }
2531 }
2532 return(TRUE);
2533 }
2534 }
2537 // Return something like array['sambaLMPassword']= "lalla..."
2538 function generate_smb_nt_hash($password)
2539 {
2540 global $config;
2542 # Try to use gosa-si?
2543 if ($config->get_cfg_value("gosaSupportURI") != ""){
2544 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2545 if (isset($res['XML']['HASH'])){
2546 $hash= $res['XML']['HASH'];
2547 } else {
2548 $hash= "";
2549 }
2551 if ($hash == "") {
2552 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2553 return ("");
2554 }
2555 } else {
2556 $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
2557 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2559 exec($tmp, $ar);
2560 flush();
2561 reset($ar);
2562 $hash= current($ar);
2564 if ($hash == "") {
2565 msg_dialog::display(_("Configuration error"), sprintf(_("Cannot generate samba hash: running '%s' failed, check the 'sambaHashHook'!"),$config->get_cfg_value('sambaHashHook')), ERROR_DIALOG);
2566 return ("");
2567 }
2568 }
2570 list($lm,$nt)= split (":", trim($hash));
2572 if ($config->get_cfg_value("sambaversion") == 3) {
2573 $attrs['sambaLMPassword']= $lm;
2574 $attrs['sambaNTPassword']= $nt;
2575 $attrs['sambaPwdLastSet']= date('U');
2576 $attrs['sambaBadPasswordCount']= "0";
2577 $attrs['sambaBadPasswordTime']= "0";
2578 } else {
2579 $attrs['lmPassword']= $lm;
2580 $attrs['ntPassword']= $nt;
2581 $attrs['pwdLastSet']= date('U');
2582 }
2583 return($attrs);
2584 }
2587 function getEntryCSN($dn)
2588 {
2589 global $config;
2590 if(empty($dn) || !is_object($config)){
2591 return("");
2592 }
2594 /* Get attribute that we should use as serial number */
2595 $attr= $config->get_cfg_value("modificationDetectionAttribute");
2596 if($attr != ""){
2597 $ldap = $config->get_ldap_link();
2598 $ldap->cat($dn,array($attr));
2599 $csn = $ldap->fetch();
2600 if(isset($csn[$attr][0])){
2601 return($csn[$attr][0]);
2602 }
2603 }
2604 return("");
2605 }
2608 /* Add a given objectClass to an attrs entry */
2609 function add_objectClass($classes, &$attrs)
2610 {
2611 if (is_array($classes)){
2612 $list= $classes;
2613 } else {
2614 $list= array($classes);
2615 }
2617 foreach ($list as $class){
2618 $attrs['objectClass'][]= $class;
2619 }
2620 }
2623 /* Removes a given objectClass from the attrs entry */
2624 function remove_objectClass($classes, &$attrs)
2625 {
2626 if (isset($attrs['objectClass'])){
2627 /* Array? */
2628 if (is_array($classes)){
2629 $list= $classes;
2630 } else {
2631 $list= array($classes);
2632 }
2634 $tmp= array();
2635 foreach ($attrs['objectClass'] as $oc) {
2636 foreach ($list as $class){
2637 if (strtolower($oc) != strtolower($class)){
2638 $tmp[]= $oc;
2639 }
2640 }
2641 }
2642 $attrs['objectClass']= $tmp;
2643 }
2644 }
2646 /*! \brief Initialize a file download with given content, name and data type.
2647 * @param data String The content to send.
2648 * @param name String The name of the file.
2649 * @param type String The content identifier, default value is "application/octet-stream";
2650 */
2651 function send_binary_content($data,$name,$type = "application/octet-stream")
2652 {
2653 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2654 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2655 header("Cache-Control: no-cache");
2656 header("Pragma: no-cache");
2657 header("Cache-Control: post-check=0, pre-check=0");
2658 header("Content-type: ".$type."");
2660 $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2662 /* Strip name if it is a complete path */
2663 if (preg_match ("/\//", $name)) {
2664 $name= basename($name);
2665 }
2667 /* force download dialog */
2668 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2669 header('Content-Disposition: filename="'.$name.'"');
2670 } else {
2671 header('Content-Disposition: attachment; filename="'.$name.'"');
2672 }
2674 echo $data;
2675 exit();
2676 }
2679 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2680 {
2681 if(is_string($str)){
2682 return(htmlentities($str,$type,$charset));
2683 }elseif(is_array($str)){
2684 foreach($str as $name => $value){
2685 $str[$name] = reverse_html_entities($value,$type,$charset);
2686 }
2687 }
2688 return($str);
2689 }
2692 /*! \brief Encode special string characters so we can use the string in \
2693 HTML output, without breaking quotes.
2694 @param The String we want to encode.
2695 @return The encoded String
2696 */
2697 function xmlentities($str)
2698 {
2699 if(is_string($str)){
2701 static $asc2uni= array();
2702 if (!count($asc2uni)){
2703 for($i=128;$i<256;$i++){
2704 # $asc2uni[chr($i)] = "&#x".dechex($i).";";
2705 }
2706 }
2708 $str = str_replace("&", "&", $str);
2709 $str = str_replace("<", "<", $str);
2710 $str = str_replace(">", ">", $str);
2711 $str = str_replace("'", "'", $str);
2712 $str = str_replace("\"", """, $str);
2713 $str = str_replace("\r", "", $str);
2714 $str = strtr($str,$asc2uni);
2715 return $str;
2716 }elseif(is_array($str)){
2717 foreach($str as $name => $value){
2718 $str[$name] = xmlentities($value);
2719 }
2720 }
2721 return($str);
2722 }
2725 /*! \brief Updates all accessTo attributes from a given value to a new one.
2726 For example if a host is renamed.
2727 @param String $from The source accessTo name.
2728 @param String $to The destination accessTo name.
2729 */
2730 function update_accessTo($from,$to)
2731 {
2732 global $config;
2733 $ldap = $config->get_ldap_link();
2734 $ldap->cd($config->current['BASE']);
2735 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2736 while($attrs = $ldap->fetch()){
2737 $new_attrs = array("accessTo" => array());
2738 $dn = $attrs['dn'];
2739 for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2740 $new_attrs['objectClass'][] = $attrs['objectClass'][$i];
2741 }
2742 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2743 if($attrs['accessTo'][$i] == $from){
2744 if(!empty($to)){
2745 $new_attrs['accessTo'][] = $to;
2746 }
2747 }else{
2748 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
2749 }
2750 }
2751 $ldap->cd($dn);
2752 $ldap->modify($new_attrs);
2753 if (!$ldap->success()){
2754 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2755 }
2756 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2757 }
2758 }
2761 function get_random_char () {
2762 $randno = rand (0, 63);
2763 if ($randno < 12) {
2764 return (chr ($randno + 46)); // Digits, '/' and '.'
2765 } else if ($randno < 38) {
2766 return (chr ($randno + 53)); // Uppercase
2767 } else {
2768 return (chr ($randno + 59)); // Lowercase
2769 }
2770 }
2773 function cred_encrypt($input, $password) {
2775 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2776 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2778 return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2780 }
2782 function cred_decrypt($input,$password) {
2783 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2784 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2786 return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2787 }
2789 function get_object_info()
2790 {
2791 return(session::get('objectinfo'));
2792 }
2794 function set_object_info($str = "")
2795 {
2796 session::set('objectinfo',$str);
2797 }
2800 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2801 ?>