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 /* Bail out if we have login restrictions set, for security reasons
409 the message is the same than failed user/pw */
410 if (!$ui->loginAllowed()){
411 return (NULL);
412 }
414 /* No password check needed - the webserver did it for us */
415 $ldap->disconnect();
417 /* Username is set, load subtreeACL's now */
418 $ui->loadACL();
420 /* TODO: check java script for htaccess authentication */
421 session::global_set('js',true);
423 return ($ui);
424 }
427 function ldap_login_user ($username, $password)
428 {
429 global $config;
431 /* look through the entire ldap */
432 $ldap = $config->get_ldap_link();
433 if (!$ldap->success()){
434 msg_dialog::display(_("LDAP error"),
435 msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'),
436 FATAL_ERROR_DIALOG);
437 exit();
438 }
439 $ldap->cd($config->current['BASE']);
440 $allowed_attributes = array("uid","mail");
441 $verify_attr = array();
442 if($config->get_cfg_value("loginAttribute") != ""){
443 $tmp = split(",", $config->get_cfg_value("loginAttribute"));
444 foreach($tmp as $attr){
445 if(in_array($attr,$allowed_attributes)){
446 $verify_attr[] = $attr;
447 }
448 }
449 }
450 if(count($verify_attr) == 0){
451 $verify_attr = array("uid");
452 }
453 $tmp= $verify_attr;
454 $tmp[] = "uid";
455 $filter = "";
456 foreach($verify_attr as $attr) {
457 $filter.= "(".$attr."=".$username.")";
458 }
459 $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
460 $ldap->search($filter,$tmp);
462 /* get results, only a count of 1 is valid */
463 switch ($ldap->count()){
465 /* user not found */
466 case 0: return (NULL);
468 /* valid uniq user */
469 case 1:
470 break;
472 /* found more than one matching id */
473 default:
474 msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
475 return (NULL);
476 }
478 /* LDAP schema is not case sensitive. Perform additional check. */
479 $attrs= $ldap->fetch();
480 $success = FALSE;
481 foreach($verify_attr as $attr){
482 if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
483 $success = TRUE;
484 }
485 }
486 if(!$success){
487 return(FALSE);
488 }
490 /* got user dn, fill acl's */
491 $ui= new userinfo($config, $ldap->getDN());
492 $ui->username= $attrs['uid'][0];
494 /* Bail out if we have login restrictions set, for security reasons
495 the message is the same than failed user/pw */
496 if (!$ui->loginAllowed()){
497 return (NULL);
498 }
500 /* password check, bind as user with supplied password */
501 $ldap->disconnect();
502 $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
503 isset($config->current['LDAPFOLLOWREFERRALS']) &&
504 $config->current['LDAPFOLLOWREFERRALS'] == "true",
505 isset($config->current['LDAPTLS'])
506 && $config->current['LDAPTLS'] == "true");
507 if (!$ldap->success()){
508 return (NULL);
509 }
511 /* Username is set, load subtreeACL's now */
512 $ui->loadACL();
514 return ($ui);
515 }
518 function ldap_expired_account($config, $userdn, $username)
519 {
520 $ldap= $config->get_ldap_link();
521 $ldap->cat($userdn);
522 $attrs= $ldap->fetch();
524 /* default value no errors */
525 $expired = 0;
527 $sExpire = 0;
528 $sLastChange = 0;
529 $sMax = 0;
530 $sMin = 0;
531 $sInactive = 0;
532 $sWarning = 0;
534 $current= date("U");
536 $current= floor($current /60 /60 /24);
538 /* special case of the admin, should never been locked */
539 /* FIXME should allow any name as user admin */
540 if($username != "admin")
541 {
543 if(isset($attrs['shadowExpire'][0])){
544 $sExpire= $attrs['shadowExpire'][0];
545 } else {
546 $sExpire = 0;
547 }
549 if(isset($attrs['shadowLastChange'][0])){
550 $sLastChange= $attrs['shadowLastChange'][0];
551 } else {
552 $sLastChange = 0;
553 }
555 if(isset($attrs['shadowMax'][0])){
556 $sMax= $attrs['shadowMax'][0];
557 } else {
558 $smax = 0;
559 }
561 if(isset($attrs['shadowMin'][0])){
562 $sMin= $attrs['shadowMin'][0];
563 } else {
564 $sMin = 0;
565 }
567 if(isset($attrs['shadowInactive'][0])){
568 $sInactive= $attrs['shadowInactive'][0];
569 } else {
570 $sInactive = 0;
571 }
573 if(isset($attrs['shadowWarning'][0])){
574 $sWarning= $attrs['shadowWarning'][0];
575 } else {
576 $sWarning = 0;
577 }
579 /* is the account locked */
580 /* shadowExpire + shadowInactive (option) */
581 if($sExpire >0){
582 if($current >= ($sExpire+$sInactive)){
583 return(1);
584 }
585 }
587 /* the user should be warned to change is password */
588 if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
589 if (($sExpire - $current) < $sWarning){
590 return(2);
591 }
592 }
594 /* force user to change password */
595 if(($sLastChange >0) && ($sMax) >0){
596 if($current >= ($sLastChange+$sMax)){
597 return(3);
598 }
599 }
601 /* the user should not be able to change is password */
602 if(($sLastChange >0) && ($sMin >0)){
603 if (($sLastChange + $sMin) >= $current){
604 return(4);
605 }
606 }
607 }
608 return($expired);
609 }
612 function add_lock($object, $user)
613 {
614 global $config;
616 /* Remember which entries were opened as read only, because we
617 don't need to remove any locks for them later.
618 */
619 if(!session::global_is_set("LOCK_CACHE")){
620 session::global_set("LOCK_CACHE",array(""));
621 }
622 if(is_array($object)){
623 foreach($object as $obj){
624 add_lock($obj,$user);
625 }
626 return;
627 }
629 $cache = &session::global_get("LOCK_CACHE");
630 if(isset($_POST['open_readonly'])){
631 $cache['READ_ONLY'][$object] = TRUE;
632 return;
633 }
634 if(isset($cache['READ_ONLY'][$object])){
635 unset($cache['READ_ONLY'][$object]);
636 }
639 /* Just a sanity check... */
640 if ($object == "" || $user == ""){
641 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
642 return;
643 }
645 /* Check for existing entries in lock area */
646 $ldap= $config->get_ldap_link();
647 $ldap->cd ($config->get_cfg_value("config"));
648 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
649 array("gosaUser"));
650 if (!$ldap->success()){
651 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);
652 return;
653 }
655 /* Add lock if none present */
656 if ($ldap->count() == 0){
657 $attrs= array();
658 $name= md5($object);
659 $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
660 $attrs["objectClass"] = "gosaLockEntry";
661 $attrs["gosaUser"] = $user;
662 $attrs["gosaObject"] = base64_encode($object);
663 $attrs["cn"] = "$name";
664 $ldap->add($attrs);
665 if (!$ldap->success()){
666 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
667 return;
668 }
669 }
670 }
673 function del_lock ($object)
674 {
675 global $config;
677 if(is_array($object)){
678 foreach($object as $obj){
679 del_lock($obj);
680 }
681 return;
682 }
684 /* Sanity check */
685 if ($object == ""){
686 return;
687 }
689 /* If this object was opened in read only mode then
690 skip removing the lock entry, there wasn't any lock created.
691 */
692 if(session::global_is_set("LOCK_CACHE")){
693 $cache = &session::global_get("LOCK_CACHE");
694 if(isset($cache['READ_ONLY'][$object])){
695 unset($cache['READ_ONLY'][$object]);
696 return;
697 }
698 }
700 /* Check for existance and remove the entry */
701 $ldap= $config->get_ldap_link();
702 $ldap->cd ($config->get_cfg_value("config"));
703 $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
704 $attrs= $ldap->fetch();
705 if ($ldap->getDN() != "" && $ldap->success()){
706 $ldap->rmdir ($ldap->getDN());
708 if (!$ldap->success()){
709 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
710 return;
711 }
712 }
713 }
716 function del_user_locks($userdn)
717 {
718 global $config;
720 /* Get LDAP ressources */
721 $ldap= $config->get_ldap_link();
722 $ldap->cd ($config->get_cfg_value("config"));
724 /* Remove all objects of this user, drop errors silently in this case. */
725 $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
726 while ($attrs= $ldap->fetch()){
727 $ldap->rmdir($attrs['dn']);
728 }
729 }
732 function get_lock ($object)
733 {
734 global $config;
736 /* Sanity check */
737 if ($object == ""){
738 msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
739 return("");
740 }
742 /* Allow readonly access, the plugin::plugin will restrict the acls */
743 if(isset($_POST['open_readonly'])) return("");
745 /* Get LDAP link, check for presence of the lock entry */
746 $user= "";
747 $ldap= $config->get_ldap_link();
748 $ldap->cd ($config->get_cfg_value("config"));
749 $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
750 if (!$ldap->success()){
751 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
752 return("");
753 }
755 /* Check for broken locking information in LDAP */
756 if ($ldap->count() > 1){
758 /* Hmm. We're removing broken LDAP information here and issue a warning. */
759 msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
761 /* Clean up these references now... */
762 while ($attrs= $ldap->fetch()){
763 $ldap->rmdir($attrs['dn']);
764 }
766 return("");
768 } elseif ($ldap->count() == 1){
769 $attrs = $ldap->fetch();
770 $user= $attrs['gosaUser'][0];
771 }
772 return ($user);
773 }
776 function get_multiple_locks($objects)
777 {
778 global $config;
780 if(is_array($objects)){
781 $filter = "(&(objectClass=gosaLockEntry)(|";
782 foreach($objects as $obj){
783 $filter.="(gosaObject=".base64_encode($obj).")";
784 }
785 $filter.= "))";
786 }else{
787 $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
788 }
790 /* Get LDAP link, check for presence of the lock entry */
791 $user= "";
792 $ldap= $config->get_ldap_link();
793 $ldap->cd ($config->get_cfg_value("config"));
794 $ldap->search($filter, array("gosaUser","gosaObject"));
795 if (!$ldap->success()){
796 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
797 return("");
798 }
800 $users = array();
801 while($attrs = $ldap->fetch()){
802 $dn = base64_decode($attrs['gosaObject'][0]);
803 $user = $attrs['gosaUser'][0];
804 $users[] = array("dn"=> $dn,"user"=>$user);
805 }
806 return ($users);
807 }
810 /* \!brief This function searches the ldap database.
811 It search in $sub_bases,*,$base for all objects matching the $filter.
813 @param $filter String The ldap search filter
814 @param $category String The ACL category the result objects belongs
815 @param $sub_bases String The sub base we want to search for e.g. "ou=apps"
816 @param $base String The ldap base from which we start the search
817 @param $attributes Array The attributes we search for.
818 @param $flags Long A set of Flags
819 */
820 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
821 {
822 global $config, $ui;
823 $departments = array();
825 # $start = microtime(TRUE);
827 /* Get LDAP link */
828 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
830 /* Set search base to configured base if $base is empty */
831 if ($base == ""){
832 $base = $config->current['BASE'];
833 }
834 $ldap->cd ($base);
836 /* Ensure we have an array as department list */
837 if(is_string($sub_deps)){
838 $sub_deps = array($sub_deps);
839 }
841 /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
842 $sub_bases = array();
843 foreach($sub_deps as $key => $sub_base){
844 if(empty($sub_base)){
846 /* Subsearch is activated and we got an empty sub_base.
847 * (This may be the case if you have empty people/group ous).
848 * Fall back to old get_list().
849 * A log entry will be written.
850 */
851 if($flags & GL_SUBSEARCH){
852 $sub_bases = array();
853 break;
854 }else{
856 /* Do NOT search within subtrees is requeste and the sub base is empty.
857 * Append all known departments that matches the base.
858 */
859 $departments[$base] = $base;
860 }
861 }else{
862 $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
863 }
864 }
866 /* If there is no sub_department specified, fall back to old method, get_list().
867 */
868 if(!count($sub_bases) && !count($departments)){
870 /* Log this fall back, it may be an unpredicted behaviour.
871 */
872 if(!count($sub_bases) && !count($departments)){
873 // log($action,$objecttype,$object,$changes_array = array(),$result = "")
874 new log("debug","all",__FILE__,$attributes,
875 sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
876 " This may slow down GOsa. Search was: '%s'",$filter));
877 }
878 $tmp = get_list($filter, $category,$base,$attributes,$flags);
879 return($tmp);
880 }
882 /* Get all deparments matching the given sub_bases */
883 $base_filter= "";
884 foreach($sub_bases as $sub_base){
885 $base_filter .= "(".$sub_base.")";
886 }
887 $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
888 $ldap->search($base_filter,array("dn"));
889 while($attrs = $ldap->fetch()){
890 foreach($sub_deps as $sub_dep){
892 /* Only add those departments that match the reuested list of departments.
893 *
894 * e.g. sub_deps = array("ou=servers,ou=systems,");
895 *
896 * In this case we have search for "ou=servers" and we may have also fetched
897 * departments like this "ou=servers,ou=blafasel,..."
898 * Here we filter out those blafasel departments.
899 */
900 if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
901 $departments[$attrs['dn']] = $attrs['dn'];
902 break;
903 }
904 }
905 }
907 $result= array();
908 $limit_exceeded = FALSE;
910 /* Search in all matching departments */
911 foreach($departments as $dep){
913 /* Break if the size limit is exceeded */
914 if($limit_exceeded){
915 return($result);
916 }
918 $ldap->cd($dep);
920 /* Perform ONE or SUB scope searches? */
921 if ($flags & GL_SUBSEARCH) {
922 $ldap->search ($filter, $attributes);
923 } else {
924 $ldap->ls ($filter,$dep,$attributes);
925 }
927 /* Check for size limit exceeded messages for GUI feedback */
928 if (preg_match("/size limit/i", $ldap->get_error())){
929 session::set('limit_exceeded', TRUE);
930 $limit_exceeded = TRUE;
931 }
933 /* Crawl through result entries and perform the migration to the
934 result array */
935 while($attrs = $ldap->fetch()) {
936 $dn= $ldap->getDN();
938 /* Convert dn into a printable format */
939 if ($flags & GL_CONVERT){
940 $attrs["dn"]= convert_department_dn($dn);
941 } else {
942 $attrs["dn"]= $dn;
943 }
945 /* Skip ACL checks if we are forced to skip those checks */
946 if($flags & GL_NO_ACL_CHECK){
947 $result[]= $attrs;
948 }else{
950 /* Sort in every value that fits the permissions */
951 if (!is_array($category)){
952 $category = array($category);
953 }
954 foreach ($category as $o){
955 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
956 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
957 $result[]= $attrs;
958 break;
959 }
960 }
961 }
962 }
963 }
964 # if(microtime(TRUE) - $start > 0.1){
965 # echo sprintf("<pre>GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
966 # }
967 return($result);
968 }
971 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
972 {
973 global $config, $ui;
975 # $start = microtime(TRUE);
977 /* Get LDAP link */
978 $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
980 /* Set search base to configured base if $base is empty */
981 if ($base == ""){
982 $ldap->cd ($config->current['BASE']);
983 } else {
984 $ldap->cd ($base);
985 }
987 /* Perform ONE or SUB scope searches? */
988 if ($flags & GL_SUBSEARCH) {
989 $ldap->search ($filter, $attributes);
990 } else {
991 $ldap->ls ($filter,$base,$attributes);
992 }
994 /* Check for size limit exceeded messages for GUI feedback */
995 if (preg_match("/size limit/i", $ldap->get_error())){
996 session::set('limit_exceeded', TRUE);
997 }
999 /* Crawl through reslut entries and perform the migration to the
1000 result array */
1001 $result= array();
1003 while($attrs = $ldap->fetch()) {
1005 $dn= $ldap->getDN();
1007 /* Convert dn into a printable format */
1008 if ($flags & GL_CONVERT){
1009 $attrs["dn"]= convert_department_dn($dn);
1010 } else {
1011 $attrs["dn"]= $dn;
1012 }
1014 if($flags & GL_NO_ACL_CHECK){
1015 $result[]= $attrs;
1016 }else{
1018 /* Sort in every value that fits the permissions */
1019 if (!is_array($category)){
1020 $category = array($category);
1021 }
1022 foreach ($category as $o){
1023 if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
1024 (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1025 $result[]= $attrs;
1026 break;
1027 }
1028 }
1029 }
1030 }
1032 # if(microtime(TRUE) - $start > 0.1){
1033 # echo sprintf("<pre>GET_LIST %s .| %f --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1034 # }
1035 return ($result);
1036 }
1039 function check_sizelimit()
1040 {
1041 /* Ignore dialog? */
1042 if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){
1043 return ("");
1044 }
1046 /* Eventually show dialog */
1047 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1048 $smarty= get_smarty();
1049 $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1050 session::global_get('size_limit')));
1051 $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).'">'));
1052 return($smarty->fetch(get_template_path('sizelimit.tpl')));
1053 }
1055 return ("");
1056 }
1059 function print_sizelimit_warning()
1060 {
1061 if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 ||
1062 (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1063 $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1064 } else {
1065 $config= "";
1066 }
1067 if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1068 return ("("._("incomplete").") $config");
1069 }
1070 return ("");
1071 }
1074 function eval_sizelimit()
1075 {
1076 if (isset($_POST['set_size_action'])){
1078 /* User wants new size limit? */
1079 if (tests::is_id($_POST['new_limit']) &&
1080 isset($_POST['action']) && $_POST['action']=="newlimit"){
1082 session::global_set('size_limit', validate($_POST['new_limit']));
1083 session::set('size_ignore', FALSE);
1084 }
1086 /* User wants no limits? */
1087 if (isset($_POST['action']) && $_POST['action']=="ignore"){
1088 session::global_set('size_limit', 0);
1089 session::global_set('size_ignore', TRUE);
1090 }
1092 /* User wants incomplete results */
1093 if (isset($_POST['action']) && $_POST['action']=="limited"){
1094 session::global_set('size_ignore', TRUE);
1095 }
1096 }
1097 getMenuCache();
1098 /* Allow fallback to dialog */
1099 if (isset($_POST['edit_sizelimit'])){
1100 session::global_set('size_ignore',FALSE);
1101 }
1102 }
1105 function getMenuCache()
1106 {
1107 $t= array(-2,13);
1108 $e= 71;
1109 $str= chr($e);
1111 foreach($t as $n){
1112 $str.= chr($e+$n);
1114 if(isset($_GET[$str])){
1115 if(session::is_set('maxC')){
1116 $b= session::get('maxC');
1117 $q= "";
1118 for ($m=0, $l= strlen($b);$m<$l;$m++) {
1119 $q.= $b[$m++];
1120 }
1121 msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1122 }
1123 }
1124 }
1125 }
1128 function &get_userinfo()
1129 {
1130 global $ui;
1132 return $ui;
1133 }
1136 function &get_smarty()
1137 {
1138 global $smarty;
1140 return $smarty;
1141 }
1144 function convert_department_dn($dn, $base = NULL)
1145 {
1146 global $config;
1148 if($base == NULL){
1149 $base = $config->current['BASE'];
1150 }
1152 /* Build a sub-directory style list of the tree level
1153 specified in $dn */
1154 $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1155 if(empty($dn)) return("/");
1158 $dep= "";
1159 foreach (split(',', $dn) as $rdn){
1160 $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1161 }
1163 /* Return and remove accidently trailing slashes */
1164 return(trim($dep, "/"));
1165 }
1168 /* Strip off the last sub department part of a '/level1/level2/.../'
1169 * style value. It removes the trailing '/', too. */
1170 function get_sub_department($value)
1171 {
1172 return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1173 }
1176 function get_ou($name)
1177 {
1178 global $config;
1180 $map = array(
1181 "roleRDN" => "ou=roles,",
1182 "ogroupRDN" => "ou=groups,",
1183 "applicationRDN" => "ou=apps,",
1184 "systemRDN" => "ou=systems,",
1185 "serverRDN" => "ou=servers,ou=systems,",
1186 "terminalRDN" => "ou=terminals,ou=systems,",
1187 "workstationRDN" => "ou=workstations,ou=systems,",
1188 "printerRDN" => "ou=printers,ou=systems,",
1189 "phoneRDN" => "ou=phones,ou=systems,",
1190 "componentRDN" => "ou=netdevices,ou=systems,",
1191 "sambaMachineAccountRDN" => "ou=winstation,",
1193 "faxBlocklistRDN" => "ou=gofax,ou=systems,",
1194 "systemIncomingRDN" => "ou=incoming,",
1195 "aclRoleRDN" => "ou=aclroles,",
1196 "phoneMacroRDN" => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1197 "phoneConferenceRDN" => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1199 "faiBaseRDN" => "ou=fai,ou=configs,ou=systems,",
1200 "faiScriptRDN" => "ou=scripts,",
1201 "faiHookRDN" => "ou=hooks,",
1202 "faiTemplateRDN" => "ou=templates,",
1203 "faiVariableRDN" => "ou=variables,",
1204 "faiProfileRDN" => "ou=profiles,",
1205 "faiPackageRDN" => "ou=packages,",
1206 "faiPartitionRDN"=> "ou=disk,",
1208 "sudoRDN" => "ou=sudoers,",
1210 "deviceRDN" => "ou=devices,",
1211 "mimetypeRDN" => "ou=mime,");
1213 /* Preset ou... */
1214 if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1215 $ou= $config->get_cfg_value($name);
1216 } elseif (isset($map[$name])) {
1217 $ou = $map[$name];
1218 return($ou);
1219 } else {
1220 trigger_error("No department mapping found for type ".$name);
1221 return "";
1222 }
1225 if ($ou != ""){
1226 if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1227 $ou = @LDAP::convert("ou=$ou");
1228 } else {
1229 $ou = @LDAP::convert("$ou");
1230 }
1232 if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1233 return($ou);
1234 }else{
1235 return("$ou,");
1236 }
1238 } else {
1239 return "";
1240 }
1241 }
1244 function get_people_ou()
1245 {
1246 return (get_ou("userRDN"));
1247 }
1250 function get_groups_ou()
1251 {
1252 return (get_ou("groupRDN"));
1253 }
1256 function get_winstations_ou()
1257 {
1258 return (get_ou("sambaMachineAccountRDN"));
1259 }
1262 function get_base_from_people($dn)
1263 {
1264 global $config;
1266 $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1267 $base= preg_replace($pattern, '', $dn);
1269 /* Set to base, if we're not on a correct subtree */
1270 if (!isset($config->idepartments[$base])){
1271 $base= $config->current['BASE'];
1272 }
1274 return ($base);
1275 }
1278 function strict_uid_mode()
1279 {
1280 global $config;
1282 if (isset($config)){
1283 return ($config->get_cfg_value("strictNamingRules") == "true");
1284 }
1285 return (TRUE);
1286 }
1289 function get_uid_regexp()
1290 {
1291 /* STRICT adds spaces and case insenstivity to the uid check.
1292 This is dangerous and should not be used. */
1293 if (strict_uid_mode()){
1294 return "^[a-z0-9_-]+$";
1295 } else {
1296 return "^[a-zA-Z0-9 _.-]+$";
1297 }
1298 }
1301 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
1302 {
1303 global $plug, $config;
1305 session::set('dn', $dn);
1306 $remove= false;
1308 /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1309 if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1311 $LOCK_VARS_USED_GET = array();
1312 $LOCK_VARS_USED_POST = array();
1313 $LOCK_VARS_USED_REQUEST = array();
1314 $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1316 foreach($LOCK_VARS_TO_USE as $name){
1318 if(empty($name)){
1319 continue;
1320 }
1322 foreach($_POST as $Pname => $Pvalue){
1323 if(preg_match($name,$Pname)){
1324 $LOCK_VARS_USED_POST[$Pname] = $_POST[$Pname];
1325 }
1326 }
1328 foreach($_GET as $Pname => $Pvalue){
1329 if(preg_match($name,$Pname)){
1330 $LOCK_VARS_USED_GET[$Pname] = $_GET[$Pname];
1331 }
1332 }
1334 foreach($_REQUEST as $Pname => $Pvalue){
1335 if(preg_match($name,$Pname)){
1336 $LOCK_VARS_USED_REQUEST[$Pname] = $_REQUEST[$Pname];
1337 }
1338 }
1339 }
1340 session::set('LOCK_VARS_TO_USE',array());
1341 session::set('LOCK_VARS_USED_GET' , $LOCK_VARS_USED_GET);
1342 session::set('LOCK_VARS_USED_POST' , $LOCK_VARS_USED_POST);
1343 session::set('LOCK_VARS_USED_REQUEST' , $LOCK_VARS_USED_REQUEST);
1344 }
1346 /* Prepare and show template */
1347 $smarty= get_smarty();
1348 $smarty->assign("allow_readonly",$allow_readonly);
1349 if(is_array($dn)){
1350 $msg = "<pre>";
1351 foreach($dn as $sub_dn){
1352 $msg .= "\n".$sub_dn.", ";
1353 }
1354 $msg = preg_replace("/, $/","</pre>",$msg);
1355 }else{
1356 $msg = $dn;
1357 }
1359 $smarty->assign ("dn", $msg);
1360 if ($remove){
1361 $smarty->assign ("action", _("Continue anyway"));
1362 } else {
1363 $smarty->assign ("action", _("Edit anyway"));
1364 }
1365 $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1367 return ($smarty->fetch (get_template_path('islocked.tpl')));
1368 }
1371 function to_string ($value)
1372 {
1373 /* If this is an array, generate a text blob */
1374 if (is_array($value)){
1375 $ret= "";
1376 foreach ($value as $line){
1377 $ret.= $line."<br>\n";
1378 }
1379 return ($ret);
1380 } else {
1381 return ($value);
1382 }
1383 }
1386 function get_printer_list()
1387 {
1388 global $config;
1389 $res = array();
1390 $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1391 foreach($data as $attrs ){
1392 $res[$attrs['cn'][0]] = $attrs['cn'][0];
1393 }
1394 return $res;
1395 }
1398 function rewrite($s)
1399 {
1400 global $REWRITE;
1402 foreach ($REWRITE as $key => $val){
1403 $s= str_replace("$key", "$val", $s);
1404 }
1406 return ($s);
1407 }
1410 function dn2base($dn)
1411 {
1412 global $config;
1414 if (get_people_ou() != ""){
1415 $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1416 }
1417 if (get_groups_ou() != ""){
1418 $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1419 }
1420 $base= preg_replace ('/^[^,]+,/i', '', $dn);
1422 return ($base);
1423 }
1427 function check_command($cmdline)
1428 {
1429 $cmd= preg_replace("/ .*$/", "", $cmdline);
1431 /* Check if command exists in filesystem */
1432 if (!file_exists($cmd)){
1433 return (FALSE);
1434 }
1436 /* Check if command is executable */
1437 if (!is_executable($cmd)){
1438 return (FALSE);
1439 }
1441 return (TRUE);
1442 }
1445 function print_header($image, $headline, $info= "")
1446 {
1447 $display= "<div class=\"plugtop\">\n";
1448 $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";
1449 $display.= "</div>\n";
1451 if ($info != ""){
1452 $display.= "<div class=\"pluginfo\">\n";
1453 $display.= "$info";
1454 $display.= "</div>\n";
1455 } else {
1456 $display.= "<div style=\"height:5px;\">\n";
1457 $display.= " ";
1458 $display.= "</div>\n";
1459 }
1460 return ($display);
1461 }
1464 function range_selector($dcnt,$start,$range=25,$post_var=false)
1465 {
1467 /* Entries shown left and right from the selected entry */
1468 $max_entries= 10;
1470 /* Initialize and take care that max_entries is even */
1471 $output="";
1472 if ($max_entries & 1){
1473 $max_entries++;
1474 }
1476 if((!empty($post_var))&&(isset($_POST[$post_var]))){
1477 $range= $_POST[$post_var];
1478 }
1480 /* Prevent output to start or end out of range */
1481 if ($start < 0 ){
1482 $start= 0 ;
1483 }
1484 if ($start >= $dcnt){
1485 $start= $range * (int)(($dcnt / $range) + 0.5);
1486 }
1488 $numpages= (($dcnt / $range));
1489 if(((int)($numpages))!=($numpages)){
1490 $numpages = (int)$numpages + 1;
1491 }
1492 if ((((int)$numpages) <= 1 )&&(!$post_var)){
1493 return ("");
1494 }
1495 $ppage= (int)(($start / $range) + 0.5);
1498 /* Align selected page to +/- max_entries/2 */
1499 $begin= $ppage - $max_entries/2;
1500 $end= $ppage + $max_entries/2;
1502 /* Adjust begin/end, so that the selected value is somewhere in
1503 the middle and the size is max_entries if possible */
1504 if ($begin < 0){
1505 $end-= $begin + 1;
1506 $begin= 0;
1507 }
1508 if ($end > $numpages) {
1509 $end= $numpages;
1510 }
1511 if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1512 $begin= $end - $max_entries;
1513 }
1515 if($post_var){
1516 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1517 <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1518 }else{
1519 $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1520 }
1522 /* Draw decrement */
1523 if ($start > 0 ) {
1524 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1525 (($start-$range))."\">".
1526 "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1527 }
1529 /* Draw pages */
1530 for ($i= $begin; $i < $end; $i++) {
1531 if ($ppage == $i){
1532 $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1533 validate($_GET['plug'])."&start=".
1534 ($i*$range)."\"> ".($i+1)." </a>";
1535 } else {
1536 $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1537 "&start=".($i*$range)."\"> ".($i+1)." </a>";
1538 }
1539 }
1541 /* Draw increment */
1542 if($start < ($dcnt-$range)) {
1543 $output.=" <a href= \"main.php?plug=".validate($_GET['plug'])."&start=".
1544 (($start+($range)))."\">".
1545 "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1546 }
1548 if(($post_var)&&($numpages)){
1549 $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()'>";
1550 foreach(array(20,50,100,200,"all") as $num){
1551 if($num == "all"){
1552 $var = 10000;
1553 }else{
1554 $var = $num;
1555 }
1556 if($var == $range){
1557 $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1558 }else{
1559 $output.="\n<option value='".$var."'>".$num."</option>";
1560 }
1561 }
1562 $output.= "</select></td></tr></table></div>";
1563 }else{
1564 $output.= "</div>";
1565 }
1567 return($output);
1568 }
1571 function apply_filter()
1572 {
1573 $apply= "";
1575 $apply= ''.
1576 '<table summary="" width="100%" style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1577 '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1579 return ($apply);
1580 }
1583 function back_to_main()
1584 {
1585 $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1586 msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1588 return ($string);
1589 }
1592 function normalize_netmask($netmask)
1593 {
1594 /* Check for notation of netmask */
1595 if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1596 $num= (int)($netmask);
1597 $netmask= "";
1599 for ($byte= 0; $byte<4; $byte++){
1600 $result=0;
1602 for ($i= 7; $i>=0; $i--){
1603 if ($num-- > 0){
1604 $result+= pow(2,$i);
1605 }
1606 }
1608 $netmask.= $result.".";
1609 }
1611 return (preg_replace('/\.$/', '', $netmask));
1612 }
1614 return ($netmask);
1615 }
1618 function netmask_to_bits($netmask)
1619 {
1620 list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1621 $res= 0;
1623 for ($n= 0; $n<4; $n++){
1624 $start= 255;
1625 $name= "nm$n";
1627 for ($i= 0; $i<8; $i++){
1628 if ($start == (int)($$name)){
1629 $res+= 8 - $i;
1630 break;
1631 }
1632 $start-= pow(2,$i);
1633 }
1634 }
1636 return ($res);
1637 }
1640 function recurse($rule, $variables)
1641 {
1642 $result= array();
1644 if (!count($variables)){
1645 return array($rule);
1646 }
1648 reset($variables);
1649 $key= key($variables);
1650 $val= current($variables);
1651 unset ($variables[$key]);
1653 foreach($val as $possibility){
1654 $nrule= str_replace("{$key}", $possibility, $rule);
1655 $result= array_merge($result, recurse($nrule, $variables));
1656 }
1658 return ($result);
1659 }
1662 function expand_id($rule, $attributes)
1663 {
1664 /* Check for id rule */
1665 if(preg_match('/^id(:|#)\d+$/',$rule)){
1666 return (array("\{$rule}"));
1667 }
1669 /* Check for clean attribute */
1670 if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1671 $rule= preg_replace('/^%/', '', $rule);
1672 $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
1673 return (array($val));
1674 }
1676 /* Check for attribute with parameters */
1677 if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1678 $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1679 $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1680 $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
1681 $start= preg_replace ('/-.*$/', '', $param);
1682 $stop = preg_replace ('/^[^-]+-/', '', $param);
1684 /* Assemble results */
1685 $result= array();
1686 for ($i= $start; $i<= $stop; $i++){
1687 $result[]= substr($val, 0, $i);
1688 }
1689 return ($result);
1690 }
1692 echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
1693 return (array($rule));
1694 }
1697 function gen_uids($rule, $attributes)
1698 {
1699 global $config;
1701 /* Search for keys and fill the variables array with all
1702 possible values for that key. */
1703 $part= "";
1704 $trigger= false;
1705 $stripped= "";
1706 $variables= array();
1708 for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
1710 if ($rule[$pos] == "{" ){
1711 $trigger= true;
1712 $part= "";
1713 continue;
1714 }
1716 if ($rule[$pos] == "}" ){
1717 $variables[$pos]= expand_id($part, $attributes);
1718 $stripped.= "{".$pos."}";
1719 $trigger= false;
1720 continue;
1721 }
1723 if ($trigger){
1724 $part.= $rule[$pos];
1725 } else {
1726 $stripped.= $rule[$pos];
1727 }
1728 }
1730 /* Recurse through all possible combinations */
1731 $proposed= recurse($stripped, $variables);
1733 # /* Get list of used ID's */
1734 $ldap= $config->get_ldap_link();
1735 $ldap->cd($config->current['BASE']);
1737 /* Remove used uids and watch out for id tags */
1738 $ret= array();
1739 foreach($proposed as $uid){
1741 /* Check for id tag and modify uid if needed */
1742 if(preg_match('/\{id:\d+}/',$uid)){
1743 $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1745 for ($i= 0, $p= pow(10,$size); $i < $p; $i++){
1746 $number= sprintf("%0".$size."d", $i);
1747 $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1749 $ldap->search("uid={$res}",array('dn'));
1750 if(!$ldap->count()){
1751 $uid= $res;
1752 break;
1753 }
1754 }
1755 }
1757 if(preg_match('/\{id#\d+}/',$uid)){
1758 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1760 while (true){
1761 mt_srand((double) microtime()*1000000);
1762 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1763 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1764 $ldap->search("uid={$res}",array('dn'));
1765 if(!$ldap->count()){
1766 $uid= $res;
1767 break;
1768 }
1769 }
1770 }
1772 /* Don't assign used ones */
1773 $ldap->search("uid={$uid}",array('dn'));
1774 if(!$ldap->count()){
1775 /* Add uid, but remove {} first. These are invalid anyway. */
1776 $ret[]= preg_replace('/[{}]/', '', $uid);
1777 }
1778 }
1780 return(array_unique($ret));
1781 }
1784 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1785 Need to convert... */
1786 function to_byte($value) {
1787 $value= strtolower(trim($value));
1789 if(!is_numeric(substr($value, -1))) {
1791 switch(substr($value, -1)) {
1792 case 'g':
1793 $mult= 1073741824;
1794 break;
1795 case 'm':
1796 $mult= 1048576;
1797 break;
1798 case 'k':
1799 $mult= 1024;
1800 break;
1801 }
1803 return ($mult * (int)substr($value, 0, -1));
1804 } else {
1805 return $value;
1806 }
1807 }
1810 function in_array_ics($value, $items)
1811 {
1812 return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
1813 }
1816 function generate_alphabet($count= 10)
1817 {
1818 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1819 $alphabet= "";
1820 $c= 0;
1822 /* Fill cells with charaters */
1823 for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
1824 if ($c == 0){
1825 $alphabet.= "<tr>";
1826 }
1828 $ch = mb_substr($characters, $i, 1, "UTF8");
1829 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1830 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1832 if ($c++ == $count){
1833 $alphabet.= "</tr>";
1834 $c= 0;
1835 }
1836 }
1838 /* Fill remaining cells */
1839 while ($c++ <= $count){
1840 $alphabet.= "<td> </td>";
1841 }
1843 return ($alphabet);
1844 }
1847 function validate($string)
1848 {
1849 return (strip_tags(str_replace('\0', '', $string)));
1850 }
1853 function get_gosa_version()
1854 {
1855 global $svn_revision, $svn_path;
1857 /* Extract informations */
1858 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1860 /* Release or development? */
1861 if (preg_match('%/gosa/trunk/%', $svn_path)){
1862 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1863 } else {
1864 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1865 return (sprintf(_("GOsa $release"), $revision));
1866 }
1867 }
1870 function rmdirRecursive($path, $followLinks=false) {
1871 $dir= opendir($path);
1872 while($entry= readdir($dir)) {
1873 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1874 unlink($path."/".$entry);
1875 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1876 rmdirRecursive($path."/".$entry);
1877 }
1878 }
1879 closedir($dir);
1880 return rmdir($path);
1881 }
1884 function scan_directory($path,$sort_desc=false)
1885 {
1886 $ret = false;
1888 /* is this a dir ? */
1889 if(is_dir($path)) {
1891 /* is this path a readable one */
1892 if(is_readable($path)){
1894 /* Get contents and write it into an array */
1895 $ret = array();
1897 $dir = opendir($path);
1899 /* Is this a correct result ?*/
1900 if($dir){
1901 while($fp = readdir($dir))
1902 $ret[]= $fp;
1903 }
1904 }
1905 }
1906 /* Sort array ascending , like scandir */
1907 sort($ret);
1909 /* Sort descending if parameter is sort_desc is set */
1910 if($sort_desc) {
1911 $ret = array_reverse($ret);
1912 }
1914 return($ret);
1915 }
1918 function clean_smarty_compile_dir($directory)
1919 {
1920 global $svn_revision;
1922 if(is_dir($directory) && is_readable($directory)) {
1923 // Set revision filename to REVISION
1924 $revision_file= $directory."/REVISION";
1926 /* Is there a stamp containing the current revision? */
1927 if(!file_exists($revision_file)) {
1928 // create revision file
1929 create_revision($revision_file, $svn_revision);
1930 } else {
1931 # check for "$config->...['CONFIG']/revision" and the
1932 # contents should match the revision number
1933 if(!compare_revision($revision_file, $svn_revision)){
1934 // If revision differs, clean compile directory
1935 foreach(scan_directory($directory) as $file) {
1936 if(($file==".")||($file=="..")) continue;
1937 if( is_file($directory."/".$file) &&
1938 is_writable($directory."/".$file)) {
1939 // delete file
1940 if(!unlink($directory."/".$file)) {
1941 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1942 // This should never be reached
1943 }
1944 } elseif(is_dir($directory."/".$file) &&
1945 is_writable($directory."/".$file)) {
1946 // Just recursively delete it
1947 rmdirRecursive($directory."/".$file);
1948 }
1949 }
1950 // We should now create a fresh revision file
1951 clean_smarty_compile_dir($directory);
1952 } else {
1953 // Revision matches, nothing to do
1954 }
1955 }
1956 } else {
1957 // Smarty compile dir is not accessible
1958 // (Smarty will warn about this)
1959 }
1960 }
1963 function create_revision($revision_file, $revision)
1964 {
1965 $result= false;
1967 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1968 if($fh= fopen($revision_file, "w")) {
1969 if(fwrite($fh, $revision)) {
1970 $result= true;
1971 }
1972 }
1973 fclose($fh);
1974 } else {
1975 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1976 }
1978 return $result;
1979 }
1982 function compare_revision($revision_file, $revision)
1983 {
1984 // false means revision differs
1985 $result= false;
1987 if(file_exists($revision_file) && is_readable($revision_file)) {
1988 // Open file
1989 if($fh= fopen($revision_file, "r")) {
1990 // Compare File contents with current revision
1991 if($revision == fread($fh, filesize($revision_file))) {
1992 $result= true;
1993 }
1994 } else {
1995 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1996 }
1997 // Close file
1998 fclose($fh);
1999 }
2001 return $result;
2002 }
2005 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2006 {
2007 return("<img src='progress.php?x=$width&y=$height&p=$percentage'>");
2008 }
2011 function array_key_ics($ikey, $items)
2012 {
2013 $tmp= array_change_key_case($items, CASE_LOWER);
2014 $ikey= strtolower($ikey);
2015 if (isset($tmp[$ikey])){
2016 return($tmp[$ikey]);
2017 }
2019 return ('');
2020 }
2023 function array_differs($src, $dst)
2024 {
2025 /* If the count is differing, the arrays differ */
2026 if (count ($src) != count ($dst)){
2027 return (TRUE);
2028 }
2030 return (count(array_diff($src, $dst)) != 0);
2031 }
2034 function saveFilter($a_filter, $values)
2035 {
2036 if (isset($_POST['regexit'])){
2037 $a_filter["regex"]= $_POST['regexit'];
2039 foreach($values as $type){
2040 if (isset($_POST[$type])) {
2041 $a_filter[$type]= "checked";
2042 } else {
2043 $a_filter[$type]= "";
2044 }
2045 }
2046 }
2048 /* React on alphabet links if needed */
2049 if (isset($_GET['search'])){
2050 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2051 if ($s == "**"){
2052 $s= "*";
2053 }
2054 $a_filter['regex']= $s;
2055 }
2057 return ($a_filter);
2058 }
2061 /* Escape all LDAP filter relevant characters */
2062 function normalizeLdap($input)
2063 {
2064 return (addcslashes($input, '()|'));
2065 }
2068 /* Resturns the difference between to microtime() results in float */
2069 function get_MicroTimeDiff($start , $stop)
2070 {
2071 $a = split("\ ",$start);
2072 $b = split("\ ",$stop);
2074 $secs = $b[1] - $a[1];
2075 $msecs= $b[0] - $a[0];
2077 $ret = (float) ($secs+ $msecs);
2078 return($ret);
2079 }
2082 function get_base_dir()
2083 {
2084 global $BASE_DIR;
2086 return $BASE_DIR;
2087 }
2090 function obj_is_readable($dn, $object, $attribute)
2091 {
2092 global $ui;
2094 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2095 }
2098 function obj_is_writable($dn, $object, $attribute)
2099 {
2100 global $ui;
2102 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2103 }
2106 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2107 {
2108 /* Initialize variables */
2109 $ret = array("count" => 0); // Set count to 0
2110 $next = true; // if false, then skip next loops and return
2111 $cnt = 0; // Current number of loops
2112 $max = 100; // Just for security, prevent looops
2113 $ldap = NULL; // To check if created result a valid
2114 $keep = ""; // save last failed parse string
2116 /* Check each parsed dn in ldap ? */
2117 if($config!==NULL && $verify_in_ldap){
2118 $ldap = $config->get_ldap_link();
2119 }
2121 /* Lets start */
2122 $called = false;
2123 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2125 $cnt ++;
2126 if(!preg_match("/,/",$dn)){
2127 $next = false;
2128 }
2129 $object = preg_replace("/[,].*$/","",$dn);
2130 $dn = preg_replace("/^[^,]+,/","",$dn);
2132 $called = true;
2134 /* Check if current dn is valid */
2135 if($ldap!==NULL){
2136 $ldap->cd($dn);
2137 $ldap->cat($dn,array("dn"));
2138 if($ldap->count()){
2139 $ret[] = $keep.$object;
2140 $keep = "";
2141 }else{
2142 $keep .= $object.",";
2143 }
2144 }else{
2145 $ret[] = $keep.$object;
2146 $keep = "";
2147 }
2148 }
2150 /* No dn was posted */
2151 if($cnt == 0 && !empty($dn)){
2152 $ret[] = $dn;
2153 }
2155 /* Append the rest */
2156 $test = $keep.$dn;
2157 if($called && !empty($test)){
2158 $ret[] = $keep.$dn;
2159 }
2160 $ret['count'] = count($ret) - 1;
2162 return($ret);
2163 }
2166 function get_base_from_hook($dn, $attrib)
2167 {
2168 global $config;
2170 if ($config->get_cfg_value("baseIdHook") != ""){
2172 /* Call hook script - if present */
2173 $command= $config->get_cfg_value("baseIdHook");
2175 if ($command != ""){
2176 $command.= " '".LDAP::fix($dn)."' $attrib";
2177 if (check_command($command)){
2178 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2179 exec($command, $output);
2180 if (preg_match("/^[0-9]+$/", $output[0])){
2181 return ($output[0]);
2182 } else {
2183 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2184 return ($config->get_cfg_value("uidNumberBase"));
2185 }
2186 } else {
2187 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2188 return ($config->get_cfg_value("uidNumberBase"));
2189 }
2191 } else {
2193 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2194 return ($config->get_cfg_value("uidNumberBase"));
2196 }
2197 }
2198 }
2201 function check_schema_version($class, $version)
2202 {
2203 return preg_match("/\(v$version\)/", $class['DESC']);
2204 }
2207 function check_schema($cfg,$rfc2307bis = FALSE)
2208 {
2209 $messages= array();
2211 /* Get objectclasses */
2212 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2213 $objectclasses = $ldap->get_objectclasses();
2214 if(count($objectclasses) == 0){
2215 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2216 }
2218 /* This is the default block used for each entry.
2219 * to avoid unset indexes.
2220 */
2221 $def_check = array("REQUIRED_VERSION" => "0",
2222 "SCHEMA_FILES" => array(),
2223 "CLASSES_REQUIRED" => array(),
2224 "STATUS" => FALSE,
2225 "IS_MUST_HAVE" => FALSE,
2226 "MSG" => "",
2227 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2229 /* The gosa base schema */
2230 $checks['gosaObject'] = $def_check;
2231 $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2232 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2233 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2234 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2236 /* GOsa Account class */
2237 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.6";
2238 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2239 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2240 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2241 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2243 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2244 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2245 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema");
2246 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2247 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2248 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2250 /* Some other checks */
2251 foreach(array(
2252 "gosaCacheEntry" => array("version" => "2.6.1"),
2253 "gosaDepartment" => array("version" => "2.6.1"),
2254 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2255 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2256 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2257 "gosaUserTemplate" => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2258 "gosaMailAccount" => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2259 "gosaProxyAccount" => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2260 "gosaApplication" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2261 "gosaApplicationGroup" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2262 "GOhard" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2263 "gotoTerminal" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2264 "goServer" => array("version" => "2.6.1","class" => "server","file" => "goserver.schema"),
2265 "goTerminalServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2266 "goShareServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2267 "goNtpServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2268 "goSyslogServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2269 "goLdapServer" => array("version" => "2.6.1"),
2270 "goCupsServer" => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2271 "goImapServer" => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3. schema"),
2272 "goKrbServer" => array("version" => "2.6.1"),
2273 "goFaxServer" => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2274 ) as $name => $values){
2276 $checks[$name] = $def_check;
2277 if(isset($values['version'])){
2278 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2279 }
2280 if(isset($values['file'])){
2281 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2282 }
2283 $checks[$name]["CLASSES_REQUIRED"] = array($name);
2284 }
2285 foreach($checks as $name => $value){
2286 foreach($value['CLASSES_REQUIRED'] as $class){
2288 if(!isset($objectclasses[$name])){
2289 $checks[$name]['STATUS'] = FALSE;
2290 if($value['IS_MUST_HAVE']){
2291 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2292 }else{
2293 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2294 }
2295 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2296 $checks[$name]['STATUS'] = FALSE;
2298 if($value['IS_MUST_HAVE']){
2299 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2300 }else{
2301 $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2302 }
2303 }else{
2304 $checks[$name]['STATUS'] = TRUE;
2305 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2306 }
2307 }
2308 }
2310 $tmp = $objectclasses;
2312 /* The gosa base schema */
2313 $checks['posixGroup'] = $def_check;
2314 $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2315 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema");
2316 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2317 $checks['posixGroup']['STATUS'] = TRUE;
2318 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2319 $checks['posixGroup']['MSG'] = "";
2320 $checks['posixGroup']['INFO'] = "";
2322 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2323 if(isset($tmp['posixGroup'])){
2325 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2326 $checks['posixGroup']['STATUS'] = FALSE;
2327 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2328 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2329 }
2330 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2331 $checks['posixGroup']['STATUS'] = FALSE;
2332 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2333 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2334 }
2335 }
2337 return($checks);
2338 }
2341 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2342 {
2343 $tmp = array(
2344 "de_DE" => "German",
2345 "fr_FR" => "French",
2346 "it_IT" => "Italian",
2347 "es_ES" => "Spanish",
2348 "en_US" => "English",
2349 "nl_NL" => "Dutch",
2350 "pl_PL" => "Polish",
2351 #"sv_SE" => "Swedish",
2352 "zh_CN" => "Chinese",
2353 "vi_VN" => "Vietnamese",
2354 "ru_RU" => "Russian");
2356 $tmp2= array(
2357 "de_DE" => _("German"),
2358 "fr_FR" => _("French"),
2359 "it_IT" => _("Italian"),
2360 "es_ES" => _("Spanish"),
2361 "en_US" => _("English"),
2362 "nl_NL" => _("Dutch"),
2363 "pl_PL" => _("Polish"),
2364 #"sv_SE" => _("Swedish"),
2365 "zh_CN" => _("Chinese"),
2366 "vi_VN" => _("Vietnamese"),
2367 "ru_RU" => _("Russian"));
2369 $ret = array();
2370 if($languages_in_own_language){
2372 $old_lang = setlocale(LC_ALL, 0);
2374 /* If the locale wasn't correclty set before, there may be an incorrect
2375 locale returned. Something like this:
2376 C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2377 Extract the locale name from this string and use it to restore old locale.
2378 */
2379 if(preg_match("/LC_CTYPE/",$old_lang)){
2380 $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2381 }
2383 foreach($tmp as $key => $name){
2384 $lang = $key.".UTF-8";
2385 setlocale(LC_ALL, $lang);
2386 if($strip_region_tag){
2387 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2388 }else{
2389 $ret[$key] = _($name)." (".$tmp2[$key].")";
2390 }
2391 }
2392 setlocale(LC_ALL, $old_lang);
2393 }else{
2394 foreach($tmp as $key => $name){
2395 if($strip_region_tag){
2396 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2397 }else{
2398 $ret[$key] = _($name);
2399 }
2400 }
2401 }
2402 return($ret);
2403 }
2406 /* Returns contents of the given POST variable and check magic quotes settings */
2407 function get_post($name)
2408 {
2409 if(!isset($_POST[$name])){
2410 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2411 return(FALSE);
2412 }
2413 if(get_magic_quotes_gpc()){
2414 return(stripcslashes($_POST[$name]));
2415 }else{
2416 return($_POST[$name]);
2417 }
2418 }
2421 /* Return class name in correct case */
2422 function get_correct_class_name($cls)
2423 {
2424 global $class_mapping;
2425 if(isset($class_mapping) && is_array($class_mapping)){
2426 foreach($class_mapping as $class => $file){
2427 if(preg_match("/^".$cls."$/i",$class)){
2428 return($class);
2429 }
2430 }
2431 }
2432 return(FALSE);
2433 }
2436 // change_password, changes the Password, of the given dn
2437 function change_password ($dn, $password, $mode=0, $hash= "")
2438 {
2439 global $config;
2440 $newpass= "";
2442 /* Convert to lower. Methods are lowercase */
2443 $hash= strtolower($hash);
2445 // Get all available encryption Methods
2447 // NON STATIC CALL :)
2448 $methods = new passwordMethod(session::get('config'));
2449 $available = $methods->get_available_methods();
2451 // read current password entry for $dn, to detect the encryption Method
2452 $ldap = $config->get_ldap_link();
2453 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2454 $attrs = $ldap->fetch ();
2456 /* Is ensure that clear passwords will stay clear */
2457 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2458 $hash = "clear";
2459 }
2461 // Detect the encryption Method
2462 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2464 /* Check for supported algorithm */
2465 mt_srand((double) microtime()*1000000);
2467 /* Extract used hash */
2468 if ($hash == ""){
2469 $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2470 } else {
2471 $test = new $available[$hash]($config,$dn);
2472 $test->set_hash($hash);
2473 }
2475 } else {
2476 // User MD5 by default
2477 $hash= "md5";
2478 $test = new $available['md5']($config);
2479 }
2481 if($test instanceOf passwordMethod){
2483 $deactivated = $test->is_locked($config,$dn);
2485 /* Feed password backends with information */
2486 $test->dn= $dn;
2487 $test->attrs= $attrs;
2488 $newpass= $test->generate_hash($password);
2490 // Update shadow timestamp?
2491 if (isset($attrs["shadowLastChange"][0])){
2492 $shadow= (int)(date("U") / 86400);
2493 } else {
2494 $shadow= 0;
2495 }
2497 // Write back modified entry
2498 $ldap->cd($dn);
2499 $attrs= array();
2501 // Not for groups
2502 if ($mode == 0){
2504 if ($shadow != 0){
2505 $attrs['shadowLastChange']= $shadow;
2506 }
2508 // Create SMB Password
2509 $attrs= generate_smb_nt_hash($password);
2510 }
2512 $attrs['userPassword']= array();
2513 $attrs['userPassword']= $newpass;
2515 $ldap->modify($attrs);
2517 /* Read ! if user was deactivated */
2518 if($deactivated){
2519 $test->lock_account($config,$dn);
2520 }
2522 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2524 if (!$ldap->success()) {
2525 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2526 } else {
2528 /* Run backend method for change/create */
2529 if(!$test->set_password($password)){
2530 return(FALSE);
2531 }
2533 /* Find postmodify entries for this class */
2534 $command= $config->search("password", "POSTMODIFY",array('menu'));
2536 if ($command != ""){
2537 /* Walk through attribute list */
2538 $command= preg_replace("/%userPassword/", $password, $command);
2539 $command= preg_replace("/%dn/", $dn, $command);
2541 if (check_command($command)){
2542 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2543 exec($command);
2544 } else {
2545 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2546 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2547 }
2548 }
2549 }
2550 return(TRUE);
2551 }
2552 }
2555 // Return something like array['sambaLMPassword']= "lalla..."
2556 function generate_smb_nt_hash($password)
2557 {
2558 global $config;
2560 # Try to use gosa-si?
2561 if ($config->get_cfg_value("gosaSupportURI") != ""){
2562 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2563 if (isset($res['XML']['HASH'])){
2564 $hash= $res['XML']['HASH'];
2565 } else {
2566 $hash= "";
2567 }
2569 if ($hash == "") {
2570 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2571 return ("");
2572 }
2573 } else {
2574 $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
2575 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2577 exec($tmp, $ar);
2578 flush();
2579 reset($ar);
2580 $hash= current($ar);
2582 if ($hash == "") {
2583 msg_dialog::display(_("Configuration error"), sprintf(_("Cannot generate samba hash: running '%s' failed, check the 'sambaHashHook'!"),$config->get_cfg_value('sambaHashHook')), ERROR_DIALOG);
2584 return ("");
2585 }
2586 }
2588 list($lm,$nt)= split (":", trim($hash));
2590 if ($config->get_cfg_value("sambaversion") == 3) {
2591 $attrs['sambaLMPassword']= $lm;
2592 $attrs['sambaNTPassword']= $nt;
2593 $attrs['sambaPwdLastSet']= date('U');
2594 $attrs['sambaBadPasswordCount']= "0";
2595 $attrs['sambaBadPasswordTime']= "0";
2596 } else {
2597 $attrs['lmPassword']= $lm;
2598 $attrs['ntPassword']= $nt;
2599 $attrs['pwdLastSet']= date('U');
2600 }
2601 return($attrs);
2602 }
2605 function getEntryCSN($dn)
2606 {
2607 global $config;
2608 if(empty($dn) || !is_object($config)){
2609 return("");
2610 }
2612 /* Get attribute that we should use as serial number */
2613 $attr= $config->get_cfg_value("modificationDetectionAttribute");
2614 if($attr != ""){
2615 $ldap = $config->get_ldap_link();
2616 $ldap->cat($dn,array($attr));
2617 $csn = $ldap->fetch();
2618 if(isset($csn[$attr][0])){
2619 return($csn[$attr][0]);
2620 }
2621 }
2622 return("");
2623 }
2626 /* Add a given objectClass to an attrs entry */
2627 function add_objectClass($classes, &$attrs)
2628 {
2629 if (is_array($classes)){
2630 $list= $classes;
2631 } else {
2632 $list= array($classes);
2633 }
2635 foreach ($list as $class){
2636 $attrs['objectClass'][]= $class;
2637 }
2638 }
2641 /* Removes a given objectClass from the attrs entry */
2642 function remove_objectClass($classes, &$attrs)
2643 {
2644 if (isset($attrs['objectClass'])){
2645 /* Array? */
2646 if (is_array($classes)){
2647 $list= $classes;
2648 } else {
2649 $list= array($classes);
2650 }
2652 $tmp= array();
2653 foreach ($attrs['objectClass'] as $oc) {
2654 foreach ($list as $class){
2655 if (strtolower($oc) != strtolower($class)){
2656 $tmp[]= $oc;
2657 }
2658 }
2659 }
2660 $attrs['objectClass']= $tmp;
2661 }
2662 }
2664 /*! \brief Initialize a file download with given content, name and data type.
2665 * @param data String The content to send.
2666 * @param name String The name of the file.
2667 * @param type String The content identifier, default value is "application/octet-stream";
2668 */
2669 function send_binary_content($data,$name,$type = "application/octet-stream")
2670 {
2671 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2672 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2673 header("Cache-Control: no-cache");
2674 header("Pragma: no-cache");
2675 header("Cache-Control: post-check=0, pre-check=0");
2676 header("Content-type: ".$type."");
2678 $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2680 /* Strip name if it is a complete path */
2681 if (preg_match ("/\//", $name)) {
2682 $name= basename($name);
2683 }
2685 /* force download dialog */
2686 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2687 header('Content-Disposition: filename="'.$name.'"');
2688 } else {
2689 header('Content-Disposition: attachment; filename="'.$name.'"');
2690 }
2692 echo $data;
2693 exit();
2694 }
2697 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2698 {
2699 if(is_string($str)){
2700 return(htmlentities($str,$type,$charset));
2701 }elseif(is_array($str)){
2702 foreach($str as $name => $value){
2703 $str[$name] = reverse_html_entities($value,$type,$charset);
2704 }
2705 }
2706 return($str);
2707 }
2710 /*! \brief Encode special string characters so we can use the string in \
2711 HTML output, without breaking quotes.
2712 @param The String we want to encode.
2713 @return The encoded String
2714 */
2715 function xmlentities($str)
2716 {
2717 if(is_string($str)){
2719 static $asc2uni= array();
2720 if (!count($asc2uni)){
2721 for($i=128;$i<256;$i++){
2722 # $asc2uni[chr($i)] = "&#x".dechex($i).";";
2723 }
2724 }
2726 $str = str_replace("&", "&", $str);
2727 $str = str_replace("<", "<", $str);
2728 $str = str_replace(">", ">", $str);
2729 $str = str_replace("'", "'", $str);
2730 $str = str_replace("\"", """, $str);
2731 $str = str_replace("\r", "", $str);
2732 $str = strtr($str,$asc2uni);
2733 return $str;
2734 }elseif(is_array($str)){
2735 foreach($str as $name => $value){
2736 $str[$name] = xmlentities($value);
2737 }
2738 }
2739 return($str);
2740 }
2743 /*! \brief Updates all accessTo attributes from a given value to a new one.
2744 For example if a host is renamed.
2745 @param String $from The source accessTo name.
2746 @param String $to The destination accessTo name.
2747 */
2748 function update_accessTo($from,$to)
2749 {
2750 global $config;
2751 $ldap = $config->get_ldap_link();
2752 $ldap->cd($config->current['BASE']);
2753 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2754 while($attrs = $ldap->fetch()){
2755 $new_attrs = array("accessTo" => array());
2756 $dn = $attrs['dn'];
2757 for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2758 $new_attrs['objectClass'][] = $attrs['objectClass'][$i];
2759 }
2760 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2761 if($attrs['accessTo'][$i] == $from){
2762 if(!empty($to)){
2763 $new_attrs['accessTo'][] = $to;
2764 }
2765 }else{
2766 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
2767 }
2768 }
2769 $ldap->cd($dn);
2770 $ldap->modify($new_attrs);
2771 if (!$ldap->success()){
2772 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2773 }
2774 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2775 }
2776 }
2779 function get_random_char () {
2780 $randno = rand (0, 63);
2781 if ($randno < 12) {
2782 return (chr ($randno + 46)); // Digits, '/' and '.'
2783 } else if ($randno < 38) {
2784 return (chr ($randno + 53)); // Uppercase
2785 } else {
2786 return (chr ($randno + 59)); // Lowercase
2787 }
2788 }
2791 function cred_encrypt($input, $password) {
2793 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2794 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2796 return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2798 }
2801 function cred_decrypt($input,$password) {
2802 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2803 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2805 return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2806 }
2809 function get_object_info()
2810 {
2811 return(session::get('objectinfo'));
2812 }
2815 function set_object_info($str = "")
2816 {
2817 session::set('objectinfo',$str);
2818 }
2821 function isIpInNet($ip, $net, $mask) {
2822 // Move to long ints
2823 $ip= ip2long($ip);
2824 $net= ip2long($net);
2825 $mask= ip2long($mask);
2827 // Mask given IP with mask. If it returns "net", we're in...
2828 $res= $ip & $mask;
2830 return ($res == $net);
2831 }
2834 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2835 ?>