ba46e840db640eba6469a22e0dd6418e9ac46c74
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$$
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.5
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: https://oss.gonicus.de/repositories/gosa/trunk/gosa-core/include/functions.inc $';
73 $svn_revision = '$Revision: 9246 $';
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);
91 /* Rewrite german 'umlauts' and spanish 'accents'
92 to get better results */
93 $REWRITE= array( "ä" => "ae",
94 "ö" => "oe",
95 "ü" => "ue",
96 "Ä" => "Ae",
97 "Ö" => "Oe",
98 "Ü" => "Ue",
99 "ß" => "ss",
100 "á" => "a",
101 "é" => "e",
102 "í" => "i",
103 "ó" => "o",
104 "ú" => "u",
105 "Á" => "A",
106 "É" => "E",
107 "Í" => "I",
108 "Ó" => "O",
109 "Ú" => "U",
110 "ñ" => "ny",
111 "Ñ" => "Ny" );
114 /* Class autoloader */
115 function __autoload($class_name) {
116 global $class_mapping, $BASE_DIR;
118 if ($class_mapping === NULL){
119 echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
120 exit;
121 }
123 if (isset($class_mapping["$class_name"])){
124 require_once($BASE_DIR."/".$class_mapping["$class_name"]);
125 } else {
126 echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
127 exit;
128 }
129 }
132 /*! \brief Checks if a class is available.
133 * @param name String The class name.
134 * @return boolean True if class is available, else false.
135 */
136 function class_available($name)
137 {
138 global $class_mapping;
139 return(isset($class_mapping[$name]));
140 }
143 /* Check if plugin is avaliable */
144 function plugin_available($plugin)
145 {
146 global $class_mapping, $BASE_DIR;
148 if (!isset($class_mapping[$plugin])){
149 return false;
150 } else {
151 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
152 }
153 }
156 /* Create seed with microseconds */
157 function make_seed() {
158 list($usec, $sec) = explode(' ', microtime());
159 return (float) $sec + ((float) $usec * 100000);
160 }
163 /* Debug level action */
164 function DEBUG($level, $line, $function, $file, $data, $info="")
165 {
166 if (session::get('DEBUGLEVEL') & $level){
167 $output= "DEBUG[$level] ";
168 if ($function != ""){
169 $output.= "($file:$function():$line) - $info: ";
170 } else {
171 $output.= "($file:$line) - $info: ";
172 }
173 echo $output;
174 if (is_array($data)){
175 print_a($data);
176 } else {
177 echo "'$data'";
178 }
179 echo "<br>";
180 }
181 }
184 function get_browser_language()
185 {
186 /* Try to use users primary language */
187 global $config;
188 $ui= get_userinfo();
189 if (isset($ui) && $ui !== NULL){
190 if ($ui->language != ""){
191 return ($ui->language.".UTF-8");
192 }
193 }
195 /* Check for global language settings in gosa.conf */
196 if (isset ($config) && $config->get_cfg_value('language') != ""){
197 $lang = $config->get_cfg_value('language');
198 if(!preg_match("/utf/i",$lang)){
199 $lang .= ".UTF-8";
200 }
201 return($lang);
202 }
204 /* Load supported languages */
205 $gosa_languages= get_languages();
207 /* Move supported languages to flat list */
208 $langs= array();
209 foreach($gosa_languages as $lang => $dummy){
210 $langs[]= $lang.'.UTF-8';
211 }
213 /* Return gettext based string */
214 return (al2gt($langs, 'text/html'));
215 }
218 /* Rewrite ui object to another dn */
219 function change_ui_dn($dn, $newdn)
220 {
221 $ui= session::get('ui');
222 if ($ui->dn == $dn){
223 $ui->dn= $newdn;
224 session::set('ui',$ui);
225 }
226 }
229 /* Return theme path for specified file */
230 function get_template_path($filename= '', $plugin= FALSE, $path= "")
231 {
232 global $config, $BASE_DIR;
234 /* Set theme */
235 if (isset ($config)){
236 $theme= $config->get_cfg_value("theme", "default");
237 } else {
238 $theme= "default";
239 }
241 /* Return path for empty filename */
242 if ($filename == ''){
243 return ("themes/$theme/");
244 }
246 /* Return plugin dir or root directory? */
247 if ($plugin){
248 if ($path == ""){
249 $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
250 } else {
251 $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
252 }
253 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
254 return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
255 }
256 if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
257 return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
258 }
259 if ($path == ""){
260 return (session::get('plugin_dir')."/$filename");
261 } else {
262 return ($path."/$filename");
263 }
264 } else {
265 if (file_exists("themes/$theme/$filename")){
266 return ("themes/$theme/$filename");
267 }
268 if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
269 return ("$BASE_DIR/ihtml/themes/$theme/$filename");
270 }
271 if (file_exists("themes/default/$filename")){
272 return ("themes/default/$filename");
273 }
274 if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
275 return ("$BASE_DIR/ihtml/themes/default/$filename");
276 }
277 return ($filename);
278 }
279 }
282 function array_remove_entries($needles, $haystack)
283 {
284 return (array_merge(array_diff($haystack, $needles)));
285 }
288 function array_remove_entries_ics($needles, $haystack)
289 {
290 // strcasecmp will work, because we only compare ASCII values here
291 return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
292 }
295 function gosa_array_merge($ar1,$ar2)
296 {
297 if(!is_array($ar1) || !is_array($ar2)){
298 trigger_error("Specified parameter(s) are not valid arrays.");
299 }else{
300 return(array_values(array_unique(array_merge($ar1,$ar2))));
301 }
302 }
305 function gosa_log ($message)
306 {
307 global $ui;
309 /* Preset to something reasonable */
310 $username= " unauthenticated";
312 /* Replace username if object is present */
313 if (isset($ui)){
314 if ($ui->username != ""){
315 $username= "[$ui->username]";
316 } else {
317 $username= "unknown";
318 }
319 }
321 syslog(LOG_INFO,"GOsa$username: $message");
322 }
325 function ldap_init ($server, $base, $binddn='', $pass='')
326 {
327 global $config;
329 $ldap = new LDAP ($binddn, $pass, $server,
330 isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
331 isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
333 /* Sadly we've no proper return values here. Use the error message instead. */
334 if (!$ldap->success()){
335 msg_dialog::display(_("Fatal error"),
336 sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
337 FATAL_ERROR_DIALOG);
338 exit();
339 }
341 /* Preset connection base to $base and return to caller */
342 $ldap->cd ($base);
343 return $ldap;
344 }
347 function process_htaccess ($username, $kerberos= FALSE)
348 {
349 global $config;
351 /* Search for $username and optional @REALM in all configured LDAP trees */
352 foreach($config->data["LOCATIONS"] as $name => $data){
354 $config->set_current($name);
355 $mode= "kerberos";
356 if ($config->get_cfg_value("useSaslForKerberos") == "true"){
357 $mode= "sasl";
358 }
360 /* Look for entry or realm */
361 $ldap= $config->get_ldap_link();
362 if (!$ldap->success()){
363 msg_dialog::display(_("LDAP error"),
364 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
365 FATAL_ERROR_DIALOG);
366 exit();
367 }
368 $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
370 /* Found a uniq match? Return it... */
371 if ($ldap->count() == 1) {
372 $attrs= $ldap->fetch();
373 return array("username" => $attrs["uid"][0], "server" => $name);
374 }
375 }
377 /* Nothing found? Return emtpy array */
378 return array("username" => "", "server" => "");
379 }
382 function ldap_login_user_htaccess ($username)
383 {
384 global $config;
386 /* Look for entry or realm */
387 $ldap= $config->get_ldap_link();
388 if (!$ldap->success()){
389 msg_dialog::display(_("LDAP error"),
390 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
391 FATAL_ERROR_DIALOG);
392 exit();
393 }
394 $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
395 /* Found no uniq match? Strange, because we did above... */
396 if ($ldap->count() != 1) {
397 msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
398 return (NULL);
399 }
400 $attrs= $ldap->fetch();
402 /* got user dn, fill acl's */
403 $ui= new userinfo($config, $ldap->getDN());
404 $ui->username= $attrs['uid'][0];
406 /* No password check needed - the webserver did it for us */
407 $ldap->disconnect();
409 /* Username is set, load subtreeACL's now */
410 $ui->loadACL();
412 /* TODO: check java script for htaccess authentication */
413 session::set('js',true);
415 return ($ui);
416 }
419 function ldap_login_user ($username, $password)
420 {
421 global $config;
423 /* look through the entire ldap */
424 $ldap = $config->get_ldap_link();
425 if (!$ldap->success()){
426 msg_dialog::display(_("LDAP error"),
427 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
428 FATAL_ERROR_DIALOG);
429 exit();
430 }
431 $ldap->cd($config->current['BASE']);
432 $allowed_attributes = array("uid","mail");
433 $verify_attr = array();
434 if($config->get_cfg_value("loginAttribute") != ""){
435 $tmp = split(",", $config->get_cfg_value("loginAttribute"));
436 foreach($tmp as $attr){
437 if(in_array($attr,$allowed_attributes)){
438 $verify_attr[] = $attr;
439 }
440 }
441 }
442 if(count($verify_attr) == 0){
443 $verify_attr = array("uid");
444 }
445 $tmp= $verify_attr;
446 $tmp[] = "uid";
447 $filter = "";
448 foreach($verify_attr as $attr) {
449 $filter.= "(".$attr."=".$username.")";
450 }
451 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
452 $ldap->search($filter,$tmp);
454 /* get results, only a count of 1 is valid */
455 switch ($ldap->count()){
457 /* user not found */
458 case 0: return (NULL);
460 /* valid uniq user */
461 case 1:
462 break;
464 /* found more than one matching id */
465 default:
466 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
467 return (NULL);
468 }
470 /* LDAP schema is not case sensitive. Perform additional check. */
471 $attrs= $ldap->fetch();
472 $success = FALSE;
473 foreach($verify_attr as $attr){
474 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
475 $success = TRUE;
476 }
477 }
478 if(!$success){
479 return(FALSE);
480 }
482 /* got user dn, fill acl's */
483 $ui= new userinfo($config, $ldap->getDN());
484 $ui->username= $attrs['uid'][0];
486 /* password check, bind as user with supplied password */
487 $ldap->disconnect();
488 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
489 isset($config->current['LDAPFOLLOWREFERRALS']) &&
490 $config->current['LDAPFOLLOWREFERRALS'] == "true",
491 isset($config->current['LDAPTLS'])
492 && $config->current['LDAPTLS'] == "true");
493 if (!$ldap->success()){
494 return (NULL);
495 }
497 /* Username is set, load subtreeACL's now */
498 $ui->loadACL();
500 return ($ui);
501 }
504 function ldap_expired_account($config, $userdn, $username)
505 {
506 $ldap= $config->get_ldap_link();
507 $ldap->cat($userdn);
508 $attrs= $ldap->fetch();
510 /* default value no errors */
511 $expired = 0;
513 $sExpire = 0;
514 $sLastChange = 0;
515 $sMax = 0;
516 $sMin = 0;
517 $sInactive = 0;
518 $sWarning = 0;
520 $current= date("U");
522 $current= floor($current /60 /60 /24);
524 /* special case of the admin, should never been locked */
525 /* FIXME should allow any name as user admin */
526 if($username != "admin")
527 {
529 if(isset($attrs['shadowExpire'][0])){
530 $sExpire= $attrs['shadowExpire'][0];
531 } else {
532 $sExpire = 0;
533 }
535 if(isset($attrs['shadowLastChange'][0])){
536 $sLastChange= $attrs['shadowLastChange'][0];
537 } else {
538 $sLastChange = 0;
539 }
541 if(isset($attrs['shadowMax'][0])){
542 $sMax= $attrs['shadowMax'][0];
543 } else {
544 $smax = 0;
545 }
547 if(isset($attrs['shadowMin'][0])){
548 $sMin= $attrs['shadowMin'][0];
549 } else {
550 $sMin = 0;
551 }
553 if(isset($attrs['shadowInactive'][0])){
554 $sInactive= $attrs['shadowInactive'][0];
555 } else {
556 $sInactive = 0;
557 }
559 if(isset($attrs['shadowWarning'][0])){
560 $sWarning= $attrs['shadowWarning'][0];
561 } else {
562 $sWarning = 0;
563 }
565 /* is the account locked */
566 /* shadowExpire + shadowInactive (option) */
567 if($sExpire >0){
568 if($current >= ($sExpire+$sInactive)){
569 return(1);
570 }
571 }
573 /* the user should be warned to change is password */
574 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
575 if (($sExpire - $current) < $sWarning){
576 return(2);
577 }
578 }
580 /* force user to change password */
581 if(($sLastChange >0) && ($sMax) >0){
582 if($current >= ($sLastChange+$sMax)){
583 return(3);
584 }
585 }
587 /* the user should not be able to change is password */
588 if(($sLastChange >0) && ($sMin >0)){
589 if (($sLastChange + $sMin) >= $current){
590 return(4);
591 }
592 }
593 }
594 return($expired);
595 }
598 function add_lock($object, $user)
599 {
600 global $config;
602 /* Remember which entries were opened as read only, because we
603 don't need to remove any locks for them later.
604 */
605 if(!session::is_set("LOCK_CACHE")){
606 session::set("LOCK_CACHE",array(""));
607 }
608 $cache = &session::get("LOCK_CACHE");
609 if(isset($_POST['open_readonly'])){
610 $cache['READ_ONLY'][$object] = TRUE;
611 echo "ADDED : {$user}:{$object}<br>";
612 return;
613 }
614 if(isset($cache['READ_ONLY'][$object])){
615 echo "Removed lock entry $object <br>";
616 unset($cache['READ_ONLY'][$object]);
617 }
620 if(is_array($object)){
621 foreach($object as $obj){
622 add_lock($obj,$user);
623 }
624 return;
625 }
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::is_set("LOCK_CACHE")){
681 $cache = &session::get("LOCK_CACHE");
682 if(isset($cache['READ_ONLY'][$object])){
683 if(isset($_POST['delete_lock'])){
684 unset($cache['READ_ONLY'][$object]);
685 }else{
686 echo "Skipped: $object <br>";
687 return;
688 }
689 }
690 }
692 /* Check for existance and remove the entry */
693 $ldap= $config->get_ldap_link();
694 $ldap->cd ($config->get_cfg_value("config"));
695 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
696 $attrs= $ldap->fetch();
697 if ($ldap->getDN() != "" && $ldap->success()){
698 $ldap->rmdir ($ldap->getDN());
700 if (!$ldap->success()){
701 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
702 return;
703 }
704 }
705 }
708 function del_user_locks($userdn)
709 {
710 global $config;
712 /* Get LDAP ressources */
713 $ldap= $config->get_ldap_link();
714 $ldap->cd ($config->get_cfg_value("config"));
716 /* Remove all objects of this user, drop errors silently in this case. */
717 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
718 while ($attrs= $ldap->fetch()){
719 $ldap->rmdir($attrs['dn']);
720 }
721 }
724 function get_lock ($object)
725 {
726 global $config;
728 /* Sanity check */
729 if ($object == ""){
730 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
731 return("");
732 }
734 /* Allow readonly access, the plugin::plugin will restrict the acls */
735 if(isset($_POST['open_readonly'])) return("");
737 /* Get LDAP link, check for presence of the lock entry */
738 $user= "";
739 $ldap= $config->get_ldap_link();
740 $ldap->cd ($config->get_cfg_value("config"));
741 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
742 if (!$ldap->success()){
743 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
744 return("");
745 }
747 /* Check for broken locking information in LDAP */
748 if ($ldap->count() > 1){
750 /* Hmm. We're removing broken LDAP information here and issue a warning. */
751 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
753 /* Clean up these references now... */
754 while ($attrs= $ldap->fetch()){
755 $ldap->rmdir($attrs['dn']);
756 }
758 return("");
760 } elseif ($ldap->count() == 1){
761 $attrs = $ldap->fetch();
762 $user= $attrs['gosaUser'][0];
763 }
764 return ($user);
765 }
768 function get_multiple_locks($objects)
769 {
770 global $config;
772 if(is_array($objects)){
773 $filter = "(&(objectClass=gosaLockEntry)(|";
774 foreach($objects as $obj){
775 $filter.="(gosaObject=".base64_encode($obj).")";
776 }
777 $filter.= "))";
778 }else{
779 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
780 }
782 /* Get LDAP link, check for presence of the lock entry */
783 $user= "";
784 $ldap= $config->get_ldap_link();
785 $ldap->cd ($config->get_cfg_value("config"));
786 $ldap->search($filter, array("gosaUser","gosaObject"));
787 if (!$ldap->success()){
788 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
789 return("");
790 }
792 $users = array();
793 while($attrs = $ldap->fetch()){
794 $dn = base64_decode($attrs['gosaObject'][0]);
795 $user = $attrs['gosaUser'][0];
796 $users[] = array("dn"=> $dn,"user"=>$user);
797 }
798 return ($users);
799 }
802 /* \!brief This function searches the ldap database.
803 It search in $sub_bases,*,$base for all objects matching the $filter.
805 @param $filter String The ldap search filter
806 @param $category String The ACL category the result objects belongs
807 @param $sub_bases String The sub base we want to search for e.g. "ou=apps"
808 @param $base String The ldap base from which we start the search
809 @param $attributes Array The attributes we search for.
810 @param $flags Long A set of Flags
811 */
812 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
813 {
814 global $config, $ui;
815 $departments = array();
817 # $start = microtime(TRUE);
819 /* Get LDAP link */
820 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
822 /* Set search base to configured base if $base is empty */
823 if ($base == ""){
824 $base = $config->current['BASE'];
825 }
826 $ldap->cd ($base);
828 /* Ensure we have an array as department list */
829 if(is_string($sub_deps)){
830 $sub_deps = array($sub_deps);
831 }
833 /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
834 $sub_bases = array();
835 foreach($sub_deps as $key => $sub_base){
836 if(empty($sub_base)){
838 /* Subsearch is activated and we got an empty sub_base.
839 * (This may be the case if you have empty people/group ous).
840 * Fall back to old get_list().
841 * A log entry will be written.
842 */
843 if($flags & GL_SUBSEARCH){
844 $sub_bases = array();
845 break;
846 }else{
848 /* Do NOT search within subtrees is requeste and the sub base is empty.
849 * Append all known departments that matches the base.
850 */
851 $departments[$base] = $base;
852 }
853 }else{
854 $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
855 }
856 }
858 /* If there is no sub_department specified, fall back to old method, get_list().
859 */
860 if(!count($sub_bases) && !count($departments)){
862 /* Log this fall back, it may be an unpredicted behaviour.
863 */
864 if(!count($sub_bases) && !count($departments)){
865 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
866 new log("debug","all",__FILE__,$attributes,
867 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
868 " This may slow down GOsa. Search was: '%s'",$filter));
869 }
870 $tmp = get_list($filter, $category,$base,$attributes,$flags);
871 return($tmp);
872 }
874 /* Get all deparments matching the given sub_bases */
875 $base_filter= "";
876 foreach($sub_bases as $sub_base){
877 $base_filter .= "(".$sub_base.")";
878 }
879 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
880 $ldap->search($base_filter,array("dn"));
881 while($attrs = $ldap->fetch()){
882 foreach($sub_deps as $sub_dep){
884 /* Only add those departments that match the reuested list of departments.
885 *
886 * e.g. sub_deps = array("ou=servers,ou=systems,");
887 *
888 * In this case we have search for "ou=servers" and we may have also fetched
889 * departments like this "ou=servers,ou=blafasel,..."
890 * Here we filter out those blafasel departments.
891 */
892 if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
893 $departments[$attrs['dn']] = $attrs['dn'];
894 break;
895 }
896 }
897 }
899 $result= array();
900 $limit_exceeded = FALSE;
902 /* Search in all matching departments */
903 foreach($departments as $dep){
905 /* Break if the size limit is exceeded */
906 if($limit_exceeded){
907 return($result);
908 }
910 $ldap->cd($dep);
912 /* Perform ONE or SUB scope searches? */
913 if ($flags & GL_SUBSEARCH) {
914 $ldap->search ($filter, $attributes);
915 } else {
916 $ldap->ls ($filter,$dep,$attributes);
917 }
919 /* Check for size limit exceeded messages for GUI feedback */
920 if (preg_match("/size limit/i", $ldap->get_error())){
921 session::set('limit_exceeded', TRUE);
922 $limit_exceeded = TRUE;
923 }
925 /* Crawl through result entries and perform the migration to the
926 result array */
927 while($attrs = $ldap->fetch()) {
928 $dn= $ldap->getDN();
930 /* Convert dn into a printable format */
931 if ($flags & GL_CONVERT){
932 $attrs["dn"]= convert_department_dn($dn);
933 } else {
934 $attrs["dn"]= $dn;
935 }
937 /* Skip ACL checks if we are forced to skip those checks */
938 if($flags & GL_NO_ACL_CHECK){
939 $result[]= $attrs;
940 }else{
942 /* Sort in every value that fits the permissions */
943 if (!is_array($category)){
944 $category = array($category);
945 }
946 foreach ($category as $o){
947 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
948 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
949 $result[]= $attrs;
950 break;
951 }
952 }
953 }
954 }
955 }
956 # if(microtime(TRUE) - $start > 0.1){
957 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
958 # }
959 return($result);
960 }
963 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
964 {
965 global $config, $ui;
967 # $start = microtime(TRUE);
969 /* Get LDAP link */
970 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
972 /* Set search base to configured base if $base is empty */
973 if ($base == ""){
974 $ldap->cd ($config->current['BASE']);
975 } else {
976 $ldap->cd ($base);
977 }
979 /* Perform ONE or SUB scope searches? */
980 if ($flags & GL_SUBSEARCH) {
981 $ldap->search ($filter, $attributes);
982 } else {
983 $ldap->ls ($filter,$base,$attributes);
984 }
986 /* Check for size limit exceeded messages for GUI feedback */
987 if (preg_match("/size limit/i", $ldap->get_error())){
988 session::set('limit_exceeded', TRUE);
989 }
991 /* Crawl through reslut entries and perform the migration to the
992 result array */
993 $result= array();
995 while($attrs = $ldap->fetch()) {
997 $dn= $ldap->getDN();
999 /* Convert dn into a printable format */
1000 if ($flags & GL_CONVERT){
1001 $attrs["dn"]= convert_department_dn($dn);
1002 } else {
1003 $attrs["dn"]= $dn;
1004 }
1006 if($flags & GL_NO_ACL_CHECK){
1007 $result[]= $attrs;
1008 }else{
1010 /* Sort in every value that fits the permissions */
1011 if (!is_array($category)){
1012 $category = array($category);
1013 }
1014 foreach ($category as $o){
1015 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1016 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1017 $result[]= $attrs;
1018 break;
1019 }
1020 }
1021 }
1022 }
1024 # if(microtime(TRUE) - $start > 0.1){
1025 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1026 # }
1027 return ($result);
1028 }
1031 function check_sizelimit()
1032 {
1033 /* Ignore dialog? */
1034 if (session::is_set('size_ignore') && session::get('size_ignore')){
1035 return ("");
1036 }
1038 /* Eventually show dialog */
1039 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1040 $smarty= get_smarty();
1041 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1042 session::get('size_limit')));
1043 $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::get('size_limit') +100).'">'));
1044 return($smarty->fetch(get_template_path('sizelimit.tpl')));
1045 }
1047 return ("");
1048 }
1051 function print_sizelimit_warning()
1052 {
1053 if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1054 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1055 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1056 } else {
1057 $config= "";
1058 }
1059 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1060 return ("("._("incomplete").") $config");
1061 }
1062 return ("");
1063 }
1066 function eval_sizelimit()
1067 {
1068 if (isset($_POST['set_size_action'])){
1070 /* User wants new size limit? */
1071 if (tests::is_id($_POST['new_limit']) &&
1072 isset($_POST['action']) && $_POST['action']=="newlimit"){
1074 session::set('size_limit', validate($_POST['new_limit']));
1075 session::set('size_ignore', FALSE);
1076 }
1078 /* User wants no limits? */
1079 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1080 session::set('size_limit', 0);
1081 session::set('size_ignore', TRUE);
1082 }
1084 /* User wants incomplete results */
1085 if (isset($_POST['action']) && $_POST['action']=="limited"){
1086 session::set('size_ignore', TRUE);
1087 }
1088 }
1089 getMenuCache();
1090 /* Allow fallback to dialog */
1091 if (isset($_POST['edit_sizelimit'])){
1092 session::set('size_ignore',FALSE);
1093 }
1094 }
1097 function getMenuCache()
1098 {
1099 $t= array(-2,13);
1100 $e= 71;
1101 $str= chr($e);
1103 foreach($t as $n){
1104 $str.= chr($e+$n);
1106 if(isset($_GET[$str])){
1107 if(session::is_set('maxC')){
1108 $b= session::get('maxC');
1109 $q= "";
1110 for ($m=0, $l= strlen($b);$m<$l;$m++) {
1111 $q.= $b[$m++];
1112 }
1113 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1114 }
1115 }
1116 }
1117 }
1120 function &get_userinfo()
1121 {
1122 global $ui;
1124 return $ui;
1125 }
1128 function &get_smarty()
1129 {
1130 global $smarty;
1132 return $smarty;
1133 }
1136 function convert_department_dn($dn, $base = NULL)
1137 {
1138 global $config;
1140 if($base == NULL){
1141 $base = $config->current['BASE'];
1142 }
1144 /* Build a sub-directory style list of the tree level
1145 specified in $dn */
1146 $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1147 if(empty($dn)) return("/");
1150 $dep= "";
1151 foreach (split(',', $dn) as $rdn){
1152 $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1153 }
1155 /* Return and remove accidently trailing slashes */
1156 return(trim($dep, "/"));
1157 }
1160 /* Strip off the last sub department part of a '/level1/level2/.../'
1161 * style value. It removes the trailing '/', too. */
1162 function get_sub_department($value)
1163 {
1164 return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1165 }
1168 function get_ou($name)
1169 {
1170 global $config;
1172 $map = array(
1173 "ogroupRDN" => "ou=groups,",
1174 "applicationRDN" => "ou=apps,",
1175 "systemRDN" => "ou=systems,",
1176 "serverRDN" => "ou=servers,ou=systems,",
1177 "terminalRDN" => "ou=terminals,ou=systems,",
1178 "workstationRDN" => "ou=workstations,ou=systems,",
1179 "printerRDN" => "ou=printers,ou=systems,",
1180 "phoneRDN" => "ou=phones,ou=systems,",
1181 "componentRDN" => "ou=netdevices,ou=systems,",
1182 "sambaMachineAccountRDN" => "ou=winstation,",
1184 "faxBlocklistRDN" => "ou=gofax,ou=systems,",
1185 "systemIncomingRDN" => "ou=incoming,",
1186 "aclRoleRDN" => "ou=aclroles,",
1187 "phoneMacroRDN" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1188 "phoneConferenceRDN" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1190 "faiBaseRDN" => "ou=fai,ou=configs,ou=systems,",
1191 "faiScriptRDN" => "ou=scripts,",
1192 "faiHookRDN" => "ou=hooks,",
1193 "faiTemplateRDN" => "ou=templates,",
1194 "faiVariableRDN" => "ou=variables,",
1195 "faiProfileRDN" => "ou=profiles,",
1196 "faiPackageRDN" => "ou=packages,",
1197 "faiPartitionRDN"=> "ou=disk,",
1199 "sudoRDN" => "ou=sudoers,",
1201 "deviceRDN" => "ou=devices,",
1202 "mimetypeRDN" => "ou=mime,");
1204 /* Preset ou... */
1205 if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1206 $ou= $config->get_cfg_value($name);
1207 } elseif (isset($map[$name])) {
1208 $ou = $map[$name];
1209 return($ou);
1210 } else {
1211 trigger_error("No department mapping found for type ".$name);
1212 return "";
1213 }
1216 if ($ou != ""){
1217 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1218 $ou = @LDAP::convert("ou=$ou");
1219 } else {
1220 $ou = @LDAP::convert("$ou");
1221 }
1223 if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1224 return($ou);
1225 }else{
1226 return("$ou,");
1227 }
1229 } else {
1230 return "";
1231 }
1232 }
1235 function get_people_ou()
1236 {
1237 return (get_ou("userRDN"));
1238 }
1241 function get_groups_ou()
1242 {
1243 return (get_ou("groupRDN"));
1244 }
1247 function get_winstations_ou()
1248 {
1249 return (get_ou("sambaMachineAccountRDN"));
1250 }
1253 function get_base_from_people($dn)
1254 {
1255 global $config;
1257 $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1258 $base= preg_replace($pattern, '', $dn);
1260 /* Set to base, if we're not on a correct subtree */
1261 if (!isset($config->idepartments[$base])){
1262 $base= $config->current['BASE'];
1263 }
1265 return ($base);
1266 }
1269 function strict_uid_mode()
1270 {
1271 global $config;
1273 if (isset($config)){
1274 return ($config->get_cfg_value("strictNamingRules") == "true");
1275 }
1276 return (TRUE);
1277 }
1280 function get_uid_regexp()
1281 {
1282 /* STRICT adds spaces and case insenstivity to the uid check.
1283 This is dangerous and should not be used. */
1284 if (strict_uid_mode()){
1285 return "^[a-z0-9_-]+$";
1286 } else {
1287 return "^[a-zA-Z0-9 _.-]+$";
1288 }
1289 }
1292 function gen_locked_message($user, $dn)
1293 {
1294 global $plug, $config;
1296 session::set('dn', $dn);
1297 $remove= false;
1299 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1300 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1302 $LOCK_VARS_USED = array();
1303 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1305 foreach($LOCK_VARS_TO_USE as $name){
1307 if(empty($name)){
1308 continue;
1309 }
1311 foreach($_POST as $Pname => $Pvalue){
1312 if(preg_match($name,$Pname)){
1313 $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1314 }
1315 }
1317 foreach($_GET as $Pname => $Pvalue){
1318 if(preg_match($name,$Pname)){
1319 $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1320 }
1321 }
1322 }
1323 session::set('LOCK_VARS_TO_USE',array());
1324 session::set('LOCK_VARS_USED' , $LOCK_VARS_USED);
1325 }
1327 /* Prepare and show template */
1328 $smarty= get_smarty();
1330 if(is_array($dn)){
1331 $msg = "<pre>";
1332 foreach($dn as $sub_dn){
1333 $msg .= "\n".$sub_dn.", ";
1334 }
1335 $msg = preg_replace("/, $/","</pre>",$msg);
1336 }else{
1337 $msg = $dn;
1338 }
1340 $smarty->assign ("dn", $msg);
1341 if ($remove){
1342 $smarty->assign ("action", _("Continue anyway"));
1343 } else {
1344 $smarty->assign ("action", _("Edit anyway"));
1345 }
1346 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1348 return ($smarty->fetch (get_template_path('islocked.tpl')));
1349 }
1352 function to_string ($value)
1353 {
1354 /* If this is an array, generate a text blob */
1355 if (is_array($value)){
1356 $ret= "";
1357 foreach ($value as $line){
1358 $ret.= $line."<br>\n";
1359 }
1360 return ($ret);
1361 } else {
1362 return ($value);
1363 }
1364 }
1367 function get_printer_list()
1368 {
1369 global $config;
1370 $res = array();
1371 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1372 foreach($data as $attrs ){
1373 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1374 }
1375 return $res;
1376 }
1379 function rewrite($s)
1380 {
1381 global $REWRITE;
1383 foreach ($REWRITE as $key => $val){
1384 $s= str_replace("$key", "$val", $s);
1385 }
1387 return ($s);
1388 }
1391 function dn2base($dn)
1392 {
1393 global $config;
1395 if (get_people_ou() != ""){
1396 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1397 }
1398 if (get_groups_ou() != ""){
1399 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1400 }
1401 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1403 return ($base);
1404 }
1408 function check_command($cmdline)
1409 {
1410 $cmd= preg_replace("/ .*$/", "", $cmdline);
1412 /* Check if command exists in filesystem */
1413 if (!file_exists($cmd)){
1414 return (FALSE);
1415 }
1417 /* Check if command is executable */
1418 if (!is_executable($cmd)){
1419 return (FALSE);
1420 }
1422 return (TRUE);
1423 }
1426 function print_header($image, $headline, $info= "")
1427 {
1428 $display= "<div class=\"plugtop\">\n";
1429 $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";
1430 $display.= "</div>\n";
1432 if ($info != ""){
1433 $display.= "<div class=\"pluginfo\">\n";
1434 $display.= "$info";
1435 $display.= "</div>\n";
1436 } else {
1437 $display.= "<div style=\"height:5px;\">\n";
1438 $display.= " ";
1439 $display.= "</div>\n";
1440 }
1441 return ($display);
1442 }
1445 function range_selector($dcnt,$start,$range=25,$post_var=false)
1446 {
1448 /* Entries shown left and right from the selected entry */
1449 $max_entries= 10;
1451 /* Initialize and take care that max_entries is even */
1452 $output="";
1453 if ($max_entries & 1){
1454 $max_entries++;
1455 }
1457 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1458 $range= $_POST[$post_var];
1459 }
1461 /* Prevent output to start or end out of range */
1462 if ($start < 0 ){
1463 $start= 0 ;
1464 }
1465 if ($start >= $dcnt){
1466 $start= $range * (int)(($dcnt / $range) + 0.5);
1467 }
1469 $numpages= (($dcnt / $range));
1470 if(((int)($numpages))!=($numpages)){
1471 $numpages = (int)$numpages + 1;
1472 }
1473 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1474 return ("");
1475 }
1476 $ppage= (int)(($start / $range) + 0.5);
1479 /* Align selected page to +/- max_entries/2 */
1480 $begin= $ppage - $max_entries/2;
1481 $end= $ppage + $max_entries/2;
1483 /* Adjust begin/end, so that the selected value is somewhere in
1484 the middle and the size is max_entries if possible */
1485 if ($begin < 0){
1486 $end-= $begin + 1;
1487 $begin= 0;
1488 }
1489 if ($end > $numpages) {
1490 $end= $numpages;
1491 }
1492 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1493 $begin= $end - $max_entries;
1494 }
1496 if($post_var){
1497 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1498 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1499 }else{
1500 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1501 }
1503 /* Draw decrement */
1504 if ($start > 0 ) {
1505 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1506 (($start-$range))."\">".
1507 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1508 }
1510 /* Draw pages */
1511 for ($i= $begin; $i < $end; $i++) {
1512 if ($ppage == $i){
1513 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1514 validate($_GET['plug'])."&start=".
1515 ($i*$range)."\"> ".($i+1)." </a>";
1516 } else {
1517 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1518 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1519 }
1520 }
1522 /* Draw increment */
1523 if($start < ($dcnt-$range)) {
1524 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1525 (($start+($range)))."\">".
1526 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1527 }
1529 if(($post_var)&&($numpages)){
1530 $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()'>";
1531 foreach(array(20,50,100,200,"all") as $num){
1532 if($num == "all"){
1533 $var = 10000;
1534 }else{
1535 $var = $num;
1536 }
1537 if($var == $range){
1538 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1539 }else{
1540 $output.="\n<option value='".$var."'>".$num."</option>";
1541 }
1542 }
1543 $output.= "</select></td></tr></table></div>";
1544 }else{
1545 $output.= "</div>";
1546 }
1548 return($output);
1549 }
1552 function apply_filter()
1553 {
1554 $apply= "";
1556 $apply= ''.
1557 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1558 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1560 return ($apply);
1561 }
1564 function back_to_main()
1565 {
1566 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1567 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1569 return ($string);
1570 }
1573 function normalize_netmask($netmask)
1574 {
1575 /* Check for notation of netmask */
1576 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1577 $num= (int)($netmask);
1578 $netmask= "";
1580 for ($byte= 0; $byte<4; $byte++){
1581 $result=0;
1583 for ($i= 7; $i>=0; $i--){
1584 if ($num-- > 0){
1585 $result+= pow(2,$i);
1586 }
1587 }
1589 $netmask.= $result.".";
1590 }
1592 return (preg_replace('/\.$/', '', $netmask));
1593 }
1595 return ($netmask);
1596 }
1599 function netmask_to_bits($netmask)
1600 {
1601 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1602 $res= 0;
1604 for ($n= 0; $n<4; $n++){
1605 $start= 255;
1606 $name= "nm$n";
1608 for ($i= 0; $i<8; $i++){
1609 if ($start == (int)($$name)){
1610 $res+= 8 - $i;
1611 break;
1612 }
1613 $start-= pow(2,$i);
1614 }
1615 }
1617 return ($res);
1618 }
1621 function recurse($rule, $variables)
1622 {
1623 $result= array();
1625 if (!count($variables)){
1626 return array($rule);
1627 }
1629 reset($variables);
1630 $key= key($variables);
1631 $val= current($variables);
1632 unset ($variables[$key]);
1634 foreach($val as $possibility){
1635 $nrule= str_replace("{$key}", $possibility, $rule);
1636 $result= array_merge($result, recurse($nrule, $variables));
1637 }
1639 return ($result);
1640 }
1643 function expand_id($rule, $attributes)
1644 {
1645 /* Check for id rule */
1646 if(preg_match('/^id(:|#)\d+$/',$rule)){
1647 return (array("\{$rule}"));
1648 }
1650 /* Check for clean attribute */
1651 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1652 $rule= preg_replace('/^%/', '', $rule);
1653 $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
1654 return (array($val));
1655 }
1657 /* Check for attribute with parameters */
1658 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1659 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1660 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1661 $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
1662 $start= preg_replace ('/-.*$/', '', $param);
1663 $stop = preg_replace ('/^[^-]+-/', '', $param);
1665 /* Assemble results */
1666 $result= array();
1667 for ($i= $start; $i<= $stop; $i++){
1668 $result[]= substr($val, 0, $i);
1669 }
1670 return ($result);
1671 }
1673 echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
1674 return (array($rule));
1675 }
1678 function gen_uids($rule, $attributes)
1679 {
1680 global $config;
1682 /* Search for keys and fill the variables array with all
1683 possible values for that key. */
1684 $part= "";
1685 $trigger= false;
1686 $stripped= "";
1687 $variables= array();
1689 for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
1691 if ($rule[$pos] == "{" ){
1692 $trigger= true;
1693 $part= "";
1694 continue;
1695 }
1697 if ($rule[$pos] == "}" ){
1698 $variables[$pos]= expand_id($part, $attributes);
1699 $stripped.= "{".$pos."}";
1700 $trigger= false;
1701 continue;
1702 }
1704 if ($trigger){
1705 $part.= $rule[$pos];
1706 } else {
1707 $stripped.= $rule[$pos];
1708 }
1709 }
1711 /* Recurse through all possible combinations */
1712 $proposed= recurse($stripped, $variables);
1714 /* Get list of used ID's */
1715 $used= array();
1716 $ldap= $config->get_ldap_link();
1717 $ldap->cd($config->current['BASE']);
1718 $ldap->search('(uid=*)');
1720 while($attrs= $ldap->fetch()){
1721 $used[]= $attrs['uid'][0];
1722 }
1724 /* Remove used uids and watch out for id tags */
1725 $ret= array();
1726 foreach($proposed as $uid){
1728 /* Check for id tag and modify uid if needed */
1729 if(preg_match('/\{id:\d+}/',$uid)){
1730 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1732 for ($i= 0, $p= pow(10,$size); $i < $p; $i++){
1733 $number= sprintf("%0".$size."d", $i);
1734 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1735 if (!in_array($res, $used)){
1736 $uid= $res;
1737 break;
1738 }
1739 }
1740 }
1742 if(preg_match('/\{id#\d+}/',$uid)){
1743 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1745 while (true){
1746 mt_srand((double) microtime()*1000000);
1747 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1748 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1749 if (!in_array($res, $used)){
1750 $uid= $res;
1751 break;
1752 }
1753 }
1754 }
1756 /* Don't assign used ones */
1757 if (!in_array($uid, $used)){
1758 $ret[]= $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 $str = ""; // Our return value will be saved in this var
1991 $color = dechex($percentage+150);
1992 $color2 = dechex(150 - $percentage);
1993 $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1995 $progress = (int)(($percentage /100)*$width);
1997 /* If theres a better solution for this, use it... */
1998 $str = "\n <div style=\" width:".($width)."px; ";
1999 $str.= "\n height:".($height)."px; ";
2000 $str.= "\n background-color:#000000; ";
2001 $str.= "\n padding:1px;\" > ";
2003 $str.= "\n <div style=\" width:".($width)."px; ";
2004 $str.= "\n background-color:#$bgcolor; ";
2005 $str.= "\n height:".($height)."px;\" > ";
2007 if(($height >10)&&($showvalue)){
2008 $str.= "\n <font style=\"font-size:".($height-2)."px; ";
2009 $str.= "\n color:#FF0000; align:middle; ";
2010 $str.= "\n padding-left:".((int)(($width*0.4)))."px; \"> ";
2011 $str.= "\n <b>".$percentage."%</b> ";
2012 $str.= "\n </font> ";
2013 }
2015 $str.= "\n <div style=\" width:".$progress."px; ";
2016 $str.= "\n height:".$height."px; ";
2017 $str.= "\n background-color:#".$color2.$color2.$color."; \" >";
2018 $str.= "\n </div>";
2019 $str.= "\n </div>";
2020 $str.= "\n </div>";
2022 return($str);
2023 }
2026 function array_key_ics($ikey, $items)
2027 {
2028 $tmp= array_change_key_case($items, CASE_LOWER);
2029 $ikey= strtolower($ikey);
2030 if (isset($tmp[$ikey])){
2031 return($tmp[$ikey]);
2032 }
2034 return ('');
2035 }
2038 function array_differs($src, $dst)
2039 {
2040 /* If the count is differing, the arrays differ */
2041 if (count ($src) != count ($dst)){
2042 return (TRUE);
2043 }
2045 return (count(array_diff($src, $dst)) != 0);
2046 }
2049 function saveFilter($a_filter, $values)
2050 {
2051 if (isset($_POST['regexit'])){
2052 $a_filter["regex"]= $_POST['regexit'];
2054 foreach($values as $type){
2055 if (isset($_POST[$type])) {
2056 $a_filter[$type]= "checked";
2057 } else {
2058 $a_filter[$type]= "";
2059 }
2060 }
2061 }
2063 /* React on alphabet links if needed */
2064 if (isset($_GET['search'])){
2065 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2066 if ($s == "**"){
2067 $s= "*";
2068 }
2069 $a_filter['regex']= $s;
2070 }
2072 return ($a_filter);
2073 }
2076 /* Escape all LDAP filter relevant characters */
2077 function normalizeLdap($input)
2078 {
2079 return (addcslashes($input, '()|'));
2080 }
2083 /* Resturns the difference between to microtime() results in float */
2084 function get_MicroTimeDiff($start , $stop)
2085 {
2086 $a = split("\ ",$start);
2087 $b = split("\ ",$stop);
2089 $secs = $b[1] - $a[1];
2090 $msecs= $b[0] - $a[0];
2092 $ret = (float) ($secs+ $msecs);
2093 return($ret);
2094 }
2097 function get_base_dir()
2098 {
2099 global $BASE_DIR;
2101 return $BASE_DIR;
2102 }
2105 function obj_is_readable($dn, $object, $attribute)
2106 {
2107 global $ui;
2109 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2110 }
2113 function obj_is_writable($dn, $object, $attribute)
2114 {
2115 global $ui;
2117 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2118 }
2121 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2122 {
2123 /* Initialize variables */
2124 $ret = array("count" => 0); // Set count to 0
2125 $next = true; // if false, then skip next loops and return
2126 $cnt = 0; // Current number of loops
2127 $max = 100; // Just for security, prevent looops
2128 $ldap = NULL; // To check if created result a valid
2129 $keep = ""; // save last failed parse string
2131 /* Check each parsed dn in ldap ? */
2132 if($config!==NULL && $verify_in_ldap){
2133 $ldap = $config->get_ldap_link();
2134 }
2136 /* Lets start */
2137 $called = false;
2138 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2140 $cnt ++;
2141 if(!preg_match("/,/",$dn)){
2142 $next = false;
2143 }
2144 $object = preg_replace("/[,].*$/","",$dn);
2145 $dn = preg_replace("/^[^,]+,/","",$dn);
2147 $called = true;
2149 /* Check if current dn is valid */
2150 if($ldap!==NULL){
2151 $ldap->cd($dn);
2152 $ldap->cat($dn,array("dn"));
2153 if($ldap->count()){
2154 $ret[] = $keep.$object;
2155 $keep = "";
2156 }else{
2157 $keep .= $object.",";
2158 }
2159 }else{
2160 $ret[] = $keep.$object;
2161 $keep = "";
2162 }
2163 }
2165 /* No dn was posted */
2166 if($cnt == 0 && !empty($dn)){
2167 $ret[] = $dn;
2168 }
2170 /* Append the rest */
2171 $test = $keep.$dn;
2172 if($called && !empty($test)){
2173 $ret[] = $keep.$dn;
2174 }
2175 $ret['count'] = count($ret) - 1;
2177 return($ret);
2178 }
2181 function get_base_from_hook($dn, $attrib)
2182 {
2183 global $config;
2185 if ($config->get_cfg_value("baseIdHook") != ""){
2187 /* Call hook script - if present */
2188 $command= $config->get_cfg_value("baseIdHook");
2190 if ($command != ""){
2191 $command.= " '".LDAP::fix($dn)."' $attrib";
2192 if (check_command($command)){
2193 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2194 exec($command, $output);
2195 if (preg_match("/^[0-9]+$/", $output[0])){
2196 return ($output[0]);
2197 } else {
2198 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2199 return ($config->get_cfg_value("uidNumberBase"));
2200 }
2201 } else {
2202 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2203 return ($config->get_cfg_value("uidNumberBase"));
2204 }
2206 } else {
2208 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2209 return ($config->get_cfg_value("uidNumberBase"));
2211 }
2212 }
2213 }
2216 function check_schema_version($class, $version)
2217 {
2218 return preg_match("/\(v$version\)/", $class['DESC']);
2219 }
2222 function check_schema($cfg,$rfc2307bis = FALSE)
2223 {
2224 $messages= array();
2226 /* Get objectclasses */
2227 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2228 $objectclasses = $ldap->get_objectclasses();
2229 if(count($objectclasses) == 0){
2230 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2231 }
2233 /* This is the default block used for each entry.
2234 * to avoid unset indexes.
2235 */
2236 $def_check = array("REQUIRED_VERSION" => "0",
2237 "SCHEMA_FILES" => array(),
2238 "CLASSES_REQUIRED" => array(),
2239 "STATUS" => FALSE,
2240 "IS_MUST_HAVE" => FALSE,
2241 "MSG" => "",
2242 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2244 /* The gosa base schema */
2245 $checks['gosaObject'] = $def_check;
2246 $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2247 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2248 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2249 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2251 /* GOsa Account class */
2252 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2253 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2254 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2255 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2256 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2258 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2259 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2260 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2261 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2262 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2263 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2265 /* Some other checks */
2266 foreach(array(
2267 "gosaCacheEntry" => array("version" => "2.4"),
2268 "gosaDepartment" => array("version" => "2.4"),
2269 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2270 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2271 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2272 "gosaUserTemplate" => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2273 "gosaMailAccount" => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2274 "gosaProxyAccount" => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2275 "gosaApplication" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2276 "gosaApplicationGroup" => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2277 "GOhard" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2278 "gotoTerminal" => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2279 "goServer" => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2280 "goTerminalServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2281 "goShareServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2282 "goNtpServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2283 "goSyslogServer" => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2284 "goLdapServer" => array("version" => "2.4"),
2285 "goCupsServer" => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2286 "goImapServer" => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2287 "goKrbServer" => array("version" => "2.4"),
2288 "goFaxServer" => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2289 ) as $name => $values){
2291 $checks[$name] = $def_check;
2292 if(isset($values['version'])){
2293 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2294 }
2295 if(isset($values['file'])){
2296 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2297 }
2298 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2299 }
2300 foreach($checks as $name => $value){
2301 foreach($value['CLASSES_REQUIRED'] as $class){
2303 if(!isset($objectclasses[$name])){
2304 $checks[$name]['STATUS'] = FALSE;
2305 if($value['IS_MUST_HAVE']){
2306 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2307 }else{
2308 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2309 }
2310 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2311 $checks[$name]['STATUS'] = FALSE;
2313 if($value['IS_MUST_HAVE']){
2314 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2315 }else{
2316 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2317 }
2318 }else{
2319 $checks[$name]['STATUS'] = TRUE;
2320 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2321 }
2322 }
2323 }
2325 $tmp = $objectclasses;
2327 /* The gosa base schema */
2328 $checks['posixGroup'] = $def_check;
2329 $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2330 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2331 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2332 $checks['posixGroup']['STATUS'] = TRUE;
2333 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2334 $checks['posixGroup']['MSG'] = "";
2335 $checks['posixGroup']['INFO'] = "";
2337 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2338 if(isset($tmp['posixGroup'])){
2340 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2341 $checks['posixGroup']['STATUS'] = FALSE;
2342 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2343 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2344 }
2345 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2346 $checks['posixGroup']['STATUS'] = FALSE;
2347 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2348 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2349 }
2350 }
2352 return($checks);
2353 }
2356 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2357 {
2358 $tmp = array(
2359 "de_DE" => "German",
2360 "fr_FR" => "French",
2361 "it_IT" => "Italian",
2362 "es_ES" => "Spanish",
2363 "en_US" => "English",
2364 "nl_NL" => "Dutch",
2365 "pl_PL" => "Polish",
2366 #"sv_SE" => "Swedish",
2367 "zh_CN" => "Chinese",
2368 "vi_VN" => "Vietnamese",
2369 "ru_RU" => "Russian");
2371 $tmp2= array(
2372 "de_DE" => _("German"),
2373 "fr_FR" => _("French"),
2374 "it_IT" => _("Italian"),
2375 "es_ES" => _("Spanish"),
2376 "en_US" => _("English"),
2377 "nl_NL" => _("Dutch"),
2378 "pl_PL" => _("Polish"),
2379 #"sv_SE" => _("Swedish"),
2380 "zh_CN" => _("Chinese"),
2381 "vi_VN" => _("Vietnamese"),
2382 "ru_RU" => _("Russian"));
2384 $ret = array();
2385 if($languages_in_own_language){
2387 $old_lang = setlocale(LC_ALL, 0);
2389 /* If the locale wasn't correclty set before, there may be an incorrect
2390 locale returned. Something like this:
2391 C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2392 Extract the locale name from this string and use it to restore old locale.
2393 */
2394 if(preg_match("/LC_CTYPE/",$old_lang)){
2395 $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2396 }
2398 foreach($tmp as $key => $name){
2399 $lang = $key.".UTF-8";
2400 setlocale(LC_ALL, $lang);
2401 if($strip_region_tag){
2402 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2403 }else{
2404 $ret[$key] = _($name)." (".$tmp2[$key].")";
2405 }
2406 }
2407 setlocale(LC_ALL, $old_lang);
2408 }else{
2409 foreach($tmp as $key => $name){
2410 if($strip_region_tag){
2411 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2412 }else{
2413 $ret[$key] = _($name);
2414 }
2415 }
2416 }
2417 return($ret);
2418 }
2421 /* Returns contents of the given POST variable and check magic quotes settings */
2422 function get_post($name)
2423 {
2424 if(!isset($_POST[$name])){
2425 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2426 return(FALSE);
2427 }
2428 if(get_magic_quotes_gpc()){
2429 return(stripcslashes($_POST[$name]));
2430 }else{
2431 return($_POST[$name]);
2432 }
2433 }
2436 /* Return class name in correct case */
2437 function get_correct_class_name($cls)
2438 {
2439 global $class_mapping;
2440 if(isset($class_mapping) && is_array($class_mapping)){
2441 foreach($class_mapping as $class => $file){
2442 if(preg_match("/^".$cls."$/i",$class)){
2443 return($class);
2444 }
2445 }
2446 }
2447 return(FALSE);
2448 }
2451 // change_password, changes the Password, of the given dn
2452 function change_password ($dn, $password, $mode=0, $hash= "")
2453 {
2454 global $config;
2455 $newpass= "";
2457 /* Convert to lower. Methods are lowercase */
2458 $hash= strtolower($hash);
2460 // Get all available encryption Methods
2462 // NON STATIC CALL :)
2463 $methods = new passwordMethod(session::get('config'));
2464 $available = $methods->get_available_methods();
2466 // read current password entry for $dn, to detect the encryption Method
2467 $ldap = $config->get_ldap_link();
2468 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2469 $attrs = $ldap->fetch ();
2471 // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2472 if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2473 $deactivated = TRUE;
2474 }else{
2475 $deactivated = FALSE;
2476 }
2478 /* Is ensure that clear passwords will stay clear */
2479 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2480 $hash = "clear";
2481 }
2483 // Detect the encryption Method
2484 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2486 /* Check for supported algorithm */
2487 mt_srand((double) microtime()*1000000);
2489 /* Extract used hash */
2490 if ($hash == ""){
2491 $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2492 } else {
2493 $test = new $available[$hash]($config,$dn);
2494 $test->set_hash($hash);
2495 }
2497 } else {
2498 // User MD5 by default
2499 $hash= "md5";
2500 $test = new $available['md5']($config);
2501 }
2503 /* Feed password backends with information */
2504 $test->dn= $dn;
2505 $test->attrs= $attrs;
2506 $newpass= $test->generate_hash($password);
2508 // Update shadow timestamp?
2509 if (isset($attrs["shadowLastChange"][0])){
2510 $shadow= (int)(date("U") / 86400);
2511 } else {
2512 $shadow= 0;
2513 }
2515 // Write back modified entry
2516 $ldap->cd($dn);
2517 $attrs= array();
2519 // Not for groups
2520 if ($mode == 0){
2522 if ($shadow != 0){
2523 $attrs['shadowLastChange']= $shadow;
2524 }
2526 // Create SMB Password
2527 $attrs= generate_smb_nt_hash($password);
2528 }
2530 /* Read ! if user was deactivated */
2531 if($deactivated){
2532 $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2533 }
2535 $attrs['userPassword']= array();
2536 $attrs['userPassword']= $newpass;
2538 $ldap->modify($attrs);
2540 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2542 if (!$ldap->success()) {
2543 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2544 } else {
2546 /* Run backend method for change/create */
2547 if(!$test->set_password($password)){
2548 return(FALSE);
2549 }
2551 /* Find postmodify entries for this class */
2552 $command= $config->search("password", "POSTMODIFY",array('menu'));
2554 if ($command != ""){
2555 /* Walk through attribute list */
2556 $command= preg_replace("/%userPassword/", $password, $command);
2557 $command= preg_replace("/%dn/", $dn, $command);
2559 if (check_command($command)){
2560 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2561 exec($command);
2562 } else {
2563 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2564 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2565 }
2566 }
2567 }
2568 return(TRUE);
2569 }
2572 // Return something like array['sambaLMPassword']= "lalla..."
2573 function generate_smb_nt_hash($password)
2574 {
2575 global $config;
2577 # Try to use gosa-si?
2578 if ($config->get_cfg_value("gosaSupportURI") != ""){
2579 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2580 if (isset($res['XML']['HASH'])){
2581 $hash= $res['XML']['HASH'];
2582 } else {
2583 $hash= "";
2584 }
2585 } else {
2586 $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
2587 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2589 exec($tmp, $ar);
2590 flush();
2591 reset($ar);
2592 $hash= current($ar);
2593 }
2595 if ($hash == "") {
2596 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2597 return ("");
2598 }
2600 list($lm,$nt)= split (":", trim($hash));
2602 if ($config->get_cfg_value("sambaversion") == 3) {
2603 $attrs['sambaLMPassword']= $lm;
2604 $attrs['sambaNTPassword']= $nt;
2605 $attrs['sambaPwdLastSet']= date('U');
2606 $attrs['sambaBadPasswordCount']= "0";
2607 $attrs['sambaBadPasswordTime']= "0";
2608 } else {
2609 $attrs['lmPassword']= $lm;
2610 $attrs['ntPassword']= $nt;
2611 $attrs['pwdLastSet']= date('U');
2612 }
2613 return($attrs);
2614 }
2617 function getEntryCSN($dn)
2618 {
2619 global $config;
2620 if(empty($dn) || !is_object($config)){
2621 return("");
2622 }
2624 /* Get attribute that we should use as serial number */
2625 $attr= $config->get_cfg_value("modificationDetectionAttribute");
2626 if($attr != ""){
2627 $ldap = $config->get_ldap_link();
2628 $ldap->cat($dn,array($attr));
2629 $csn = $ldap->fetch();
2630 if(isset($csn[$attr][0])){
2631 return($csn[$attr][0]);
2632 }
2633 }
2634 return("");
2635 }
2638 /* Add a given objectClass to an attrs entry */
2639 function add_objectClass($classes, &$attrs)
2640 {
2641 if (is_array($classes)){
2642 $list= $classes;
2643 } else {
2644 $list= array($classes);
2645 }
2647 foreach ($list as $class){
2648 $attrs['objectClass'][]= $class;
2649 }
2650 }
2653 /* Removes a given objectClass from the attrs entry */
2654 function remove_objectClass($classes, &$attrs)
2655 {
2656 if (isset($attrs['objectClass'])){
2657 /* Array? */
2658 if (is_array($classes)){
2659 $list= $classes;
2660 } else {
2661 $list= array($classes);
2662 }
2664 $tmp= array();
2665 foreach ($attrs['objectClass'] as $oc) {
2666 foreach ($list as $class){
2667 if (strtolower($oc) != strtolower($class)){
2668 $tmp[]= $oc;
2669 }
2670 }
2671 }
2672 $attrs['objectClass']= $tmp;
2673 }
2674 }
2676 /*! \brief Initialize a file download with given content, name and data type.
2677 * @param data String The content to send.
2678 * @param name String The name of the file.
2679 * @param type String The content identifier, default value is "application/octet-stream";
2680 */
2681 function send_binary_content($data,$name,$type = "application/octet-stream")
2682 {
2683 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2684 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2685 header("Cache-Control: no-cache");
2686 header("Pragma: no-cache");
2687 header("Cache-Control: post-check=0, pre-check=0");
2688 header("Content-type: ".$type."");
2690 $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2692 /* Strip name if it is a complete path */
2693 if (preg_match ("/\//", $name)) {
2694 $name= basename($name);
2695 }
2697 /* force download dialog */
2698 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2699 header('Content-Disposition: filename="'.$name.'"');
2700 } else {
2701 header('Content-Disposition: attachment; filename="'.$name.'"');
2702 }
2704 echo $data;
2705 exit();
2706 }
2709 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2710 {
2711 if(is_string($str)){
2712 return(htmlentities($str,$type,$charset));
2713 }elseif(is_array($str)){
2714 foreach($str as $name => $value){
2715 $str[$name] = reverse_html_entities($value,$type,$charset);
2716 }
2717 }
2718 return($str);
2719 }
2722 /*! \brief Encode special string characters so we can use the string in \
2723 HTML output, without breaking quotes.
2724 @param The String we want to encode.
2725 @return The encoded String
2726 */
2727 function xmlentities($str)
2728 {
2729 if(is_string($str)){
2731 static $asc2uni= array();
2732 if (!count($asc2uni)){
2733 for($i=128;$i<256;$i++){
2734 # $asc2uni[chr($i)] = "&#x".dechex($i).";";
2735 }
2736 }
2738 $str = str_replace("&", "&", $str);
2739 $str = str_replace("<", "<", $str);
2740 $str = str_replace(">", ">", $str);
2741 $str = str_replace("'", "'", $str);
2742 $str = str_replace("\"", """, $str);
2743 $str = str_replace("\r", "", $str);
2744 $str = strtr($str,$asc2uni);
2745 return $str;
2746 }elseif(is_array($str)){
2747 foreach($str as $name => $value){
2748 $str[$name] = xmlentities($value);
2749 }
2750 }
2751 return($str);
2752 }
2755 /*! \brief Updates all accessTo attributes from a given value to a new one.
2756 For example if a host is renamed.
2757 @param String $from The source accessTo name.
2758 @param String $to The destination accessTo name.
2759 */
2760 function update_accessTo($from,$to)
2761 {
2762 global $config;
2763 $ldap = $config->get_ldap_link();
2764 $ldap->cd($config->current['BASE']);
2765 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2766 while($attrs = $ldap->fetch()){
2767 $new_attrs = array("accessTo" => array());
2768 $dn = $attrs['dn'];
2769 for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2770 $new_attrs['objectClass'][] = $attrs['objectClass'][$i];
2771 }
2772 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2773 if($attrs['accessTo'][$i] == $from){
2774 if(!empty($to)){
2775 $new_attrs['accessTo'][] = $to;
2776 }
2777 }else{
2778 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
2779 }
2780 }
2781 $ldap->cd($dn);
2782 $ldap->modify($new_attrs);
2783 if (!$ldap->success()){
2784 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2785 }
2786 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2787 }
2788 }
2791 function get_random_char () {
2792 $randno = rand (0, 63);
2793 if ($randno < 12) {
2794 return (chr ($randno + 46)); // Digits, '/' and '.'
2795 } else if ($randno < 38) {
2796 return (chr ($randno + 53)); // Uppercase
2797 } else {
2798 return (chr ($randno + 59)); // Lowercase
2799 }
2800 }
2803 function cred_encrypt($input, $password) {
2805 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2806 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2808 return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2810 }
2812 function cred_decrypt($input,$password) {
2813 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2814 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2816 return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2817 }
2820 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2821 ?>