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, $m)){
1743 $size= preg_replace('/^.*{id(:|!)(\d+)}.*$/', '\\2', $uid);
1745 $start= $m[1]==":"?0:-1;
1746 for ($i= $start, $p= pow(10,$size)-1; $i < $p; $i++){
1747 if ($i == -1) {
1748 $number= "";
1749 } else {
1750 $number= sprintf("%0".$size."d", $i+1);
1751 }
1752 $res= preg_replace('/{id(:|!)\d+}/', $number, $uid);
1754 $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
1755 if($ldap->count() == 0){
1756 $uid= $res;
1757 break;
1758 }
1759 }
1761 /* Remove link if nothing has been found */
1762 $uid= preg_replace('/{id(:|!)\d+}/', '', $uid);
1763 }
1765 if(preg_match('/\{id#\d+}/',$uid)){
1766 $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1768 while (true){
1769 mt_srand((double) microtime()*1000000);
1770 $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1771 $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1772 $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
1773 if($ldap->count() == 0){
1774 $uid= $res;
1775 break;
1776 }
1777 }
1779 /* Remove link if nothing has been found */
1780 $uid= preg_replace('/{id#\d+}/', '', $uid);
1781 }
1783 /* Don't assign used ones */
1784 $ldap->search("(uid=".preg_replace('/[{}]/', '', $uid).")",array('dn'));
1785 if($ldap->count() == 0){
1786 /* Add uid, but remove {} first. These are invalid anyway. */
1787 $ret[]= preg_replace('/[{}]/', '', $uid);
1788 }
1789 }
1791 return(array_unique($ret));
1792 }
1795 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1796 Need to convert... */
1797 function to_byte($value) {
1798 $value= strtolower(trim($value));
1800 if(!is_numeric(substr($value, -1))) {
1802 switch(substr($value, -1)) {
1803 case 'g':
1804 $mult= 1073741824;
1805 break;
1806 case 'm':
1807 $mult= 1048576;
1808 break;
1809 case 'k':
1810 $mult= 1024;
1811 break;
1812 }
1814 return ($mult * (int)substr($value, 0, -1));
1815 } else {
1816 return $value;
1817 }
1818 }
1821 function in_array_ics($value, $items)
1822 {
1823 return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
1824 }
1827 function generate_alphabet($count= 10)
1828 {
1829 $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1830 $alphabet= "";
1831 $c= 0;
1833 /* Fill cells with charaters */
1834 for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
1835 if ($c == 0){
1836 $alphabet.= "<tr>";
1837 }
1839 $ch = mb_substr($characters, $i, 1, "UTF8");
1840 $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1841 validate($_GET['plug'])."&search=".$ch."\"> ".$ch." </a></td>";
1843 if ($c++ == $count){
1844 $alphabet.= "</tr>";
1845 $c= 0;
1846 }
1847 }
1849 /* Fill remaining cells */
1850 while ($c++ <= $count){
1851 $alphabet.= "<td> </td>";
1852 }
1854 return ($alphabet);
1855 }
1858 function validate($string)
1859 {
1860 return (strip_tags(str_replace('\0', '', $string)));
1861 }
1864 function get_gosa_version()
1865 {
1866 global $svn_revision, $svn_path;
1868 /* Extract informations */
1869 $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1871 /* Release or development? */
1872 if (preg_match('%/gosa/trunk/%', $svn_path)){
1873 return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1874 } else {
1875 $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1876 return (sprintf(_("GOsa $release"), $revision));
1877 }
1878 }
1881 function rmdirRecursive($path, $followLinks=false) {
1882 $dir= opendir($path);
1883 while($entry= readdir($dir)) {
1884 if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1885 unlink($path."/".$entry);
1886 } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1887 rmdirRecursive($path."/".$entry);
1888 }
1889 }
1890 closedir($dir);
1891 return rmdir($path);
1892 }
1895 function scan_directory($path,$sort_desc=false)
1896 {
1897 $ret = false;
1899 /* is this a dir ? */
1900 if(is_dir($path)) {
1902 /* is this path a readable one */
1903 if(is_readable($path)){
1905 /* Get contents and write it into an array */
1906 $ret = array();
1908 $dir = opendir($path);
1910 /* Is this a correct result ?*/
1911 if($dir){
1912 while($fp = readdir($dir))
1913 $ret[]= $fp;
1914 }
1915 }
1916 }
1917 /* Sort array ascending , like scandir */
1918 sort($ret);
1920 /* Sort descending if parameter is sort_desc is set */
1921 if($sort_desc) {
1922 $ret = array_reverse($ret);
1923 }
1925 return($ret);
1926 }
1929 function clean_smarty_compile_dir($directory)
1930 {
1931 global $svn_revision;
1933 if(is_dir($directory) && is_readable($directory)) {
1934 // Set revision filename to REVISION
1935 $revision_file= $directory."/REVISION";
1937 /* Is there a stamp containing the current revision? */
1938 if(!file_exists($revision_file)) {
1939 // create revision file
1940 create_revision($revision_file, $svn_revision);
1941 } else {
1942 # check for "$config->...['CONFIG']/revision" and the
1943 # contents should match the revision number
1944 if(!compare_revision($revision_file, $svn_revision)){
1945 // If revision differs, clean compile directory
1946 foreach(scan_directory($directory) as $file) {
1947 if(($file==".")||($file=="..")) continue;
1948 if( is_file($directory."/".$file) &&
1949 is_writable($directory."/".$file)) {
1950 // delete file
1951 if(!unlink($directory."/".$file)) {
1952 msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1953 // This should never be reached
1954 }
1955 } elseif(is_dir($directory."/".$file) &&
1956 is_writable($directory."/".$file)) {
1957 // Just recursively delete it
1958 rmdirRecursive($directory."/".$file);
1959 }
1960 }
1961 // We should now create a fresh revision file
1962 clean_smarty_compile_dir($directory);
1963 } else {
1964 // Revision matches, nothing to do
1965 }
1966 }
1967 } else {
1968 // Smarty compile dir is not accessible
1969 // (Smarty will warn about this)
1970 }
1971 }
1974 function create_revision($revision_file, $revision)
1975 {
1976 $result= false;
1978 if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1979 if($fh= fopen($revision_file, "w")) {
1980 if(fwrite($fh, $revision)) {
1981 $result= true;
1982 }
1983 }
1984 fclose($fh);
1985 } else {
1986 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1987 }
1989 return $result;
1990 }
1993 function compare_revision($revision_file, $revision)
1994 {
1995 // false means revision differs
1996 $result= false;
1998 if(file_exists($revision_file) && is_readable($revision_file)) {
1999 // Open file
2000 if($fh= fopen($revision_file, "r")) {
2001 // Compare File contents with current revision
2002 if($revision == fread($fh, filesize($revision_file))) {
2003 $result= true;
2004 }
2005 } else {
2006 msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2007 }
2008 // Close file
2009 fclose($fh);
2010 }
2012 return $result;
2013 }
2016 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2017 {
2018 return("<img src='progress.php?x=$width&y=$height&p=$percentage'>");
2019 }
2022 function array_key_ics($ikey, $items)
2023 {
2024 $tmp= array_change_key_case($items, CASE_LOWER);
2025 $ikey= strtolower($ikey);
2026 if (isset($tmp[$ikey])){
2027 return($tmp[$ikey]);
2028 }
2030 return ('');
2031 }
2034 function array_differs($src, $dst)
2035 {
2036 /* If the count is differing, the arrays differ */
2037 if (count ($src) != count ($dst)){
2038 return (TRUE);
2039 }
2041 return (count(array_diff($src, $dst)) != 0);
2042 }
2045 function saveFilter($a_filter, $values)
2046 {
2047 if (isset($_POST['regexit'])){
2048 $a_filter["regex"]= $_POST['regexit'];
2050 foreach($values as $type){
2051 if (isset($_POST[$type])) {
2052 $a_filter[$type]= "checked";
2053 } else {
2054 $a_filter[$type]= "";
2055 }
2056 }
2057 }
2059 /* React on alphabet links if needed */
2060 if (isset($_GET['search'])){
2061 $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2062 if ($s == "**"){
2063 $s= "*";
2064 }
2065 $a_filter['regex']= $s;
2066 }
2068 return ($a_filter);
2069 }
2072 /* Escape all LDAP filter relevant characters */
2073 function normalizeLdap($input)
2074 {
2075 return (addcslashes($input, '()|'));
2076 }
2079 /* Resturns the difference between to microtime() results in float */
2080 function get_MicroTimeDiff($start , $stop)
2081 {
2082 $a = split("\ ",$start);
2083 $b = split("\ ",$stop);
2085 $secs = $b[1] - $a[1];
2086 $msecs= $b[0] - $a[0];
2088 $ret = (float) ($secs+ $msecs);
2089 return($ret);
2090 }
2093 function get_base_dir()
2094 {
2095 global $BASE_DIR;
2097 return $BASE_DIR;
2098 }
2101 function obj_is_readable($dn, $object, $attribute)
2102 {
2103 global $ui;
2105 return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2106 }
2109 function obj_is_writable($dn, $object, $attribute)
2110 {
2111 global $ui;
2113 return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2114 }
2117 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2118 {
2119 /* Initialize variables */
2120 $ret = array("count" => 0); // Set count to 0
2121 $next = true; // if false, then skip next loops and return
2122 $cnt = 0; // Current number of loops
2123 $max = 100; // Just for security, prevent looops
2124 $ldap = NULL; // To check if created result a valid
2125 $keep = ""; // save last failed parse string
2127 /* Check each parsed dn in ldap ? */
2128 if($config!==NULL && $verify_in_ldap){
2129 $ldap = $config->get_ldap_link();
2130 }
2132 /* Lets start */
2133 $called = false;
2134 while(preg_match("/,/",$dn) && $next && $cnt < $max){
2136 $cnt ++;
2137 if(!preg_match("/,/",$dn)){
2138 $next = false;
2139 }
2140 $object = preg_replace("/[,].*$/","",$dn);
2141 $dn = preg_replace("/^[^,]+,/","",$dn);
2143 $called = true;
2145 /* Check if current dn is valid */
2146 if($ldap!==NULL){
2147 $ldap->cd($dn);
2148 $ldap->cat($dn,array("dn"));
2149 if($ldap->count()){
2150 $ret[] = $keep.$object;
2151 $keep = "";
2152 }else{
2153 $keep .= $object.",";
2154 }
2155 }else{
2156 $ret[] = $keep.$object;
2157 $keep = "";
2158 }
2159 }
2161 /* No dn was posted */
2162 if($cnt == 0 && !empty($dn)){
2163 $ret[] = $dn;
2164 }
2166 /* Append the rest */
2167 $test = $keep.$dn;
2168 if($called && !empty($test)){
2169 $ret[] = $keep.$dn;
2170 }
2171 $ret['count'] = count($ret) - 1;
2173 return($ret);
2174 }
2177 function get_base_from_hook($dn, $attrib)
2178 {
2179 global $config;
2181 if ($config->get_cfg_value("baseIdHook") != ""){
2183 /* Call hook script - if present */
2184 $command= $config->get_cfg_value("baseIdHook");
2186 if ($command != ""){
2187 $command.= " '".LDAP::fix($dn)."' $attrib";
2188 if (check_command($command)){
2189 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2190 exec($command, $output);
2191 if (preg_match("/^[0-9]+$/", $output[0])){
2192 return ($output[0]);
2193 } else {
2194 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2195 return ($config->get_cfg_value("uidNumberBase"));
2196 }
2197 } else {
2198 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2199 return ($config->get_cfg_value("uidNumberBase"));
2200 }
2202 } else {
2204 msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2205 return ($config->get_cfg_value("uidNumberBase"));
2207 }
2208 }
2209 }
2212 function check_schema_version($class, $version)
2213 {
2214 return preg_match("/\(v$version\)/", $class['DESC']);
2215 }
2218 function check_schema($cfg,$rfc2307bis = FALSE)
2219 {
2220 $messages= array();
2222 /* Get objectclasses */
2223 $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2224 $objectclasses = $ldap->get_objectclasses();
2225 if(count($objectclasses) == 0){
2226 msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2227 }
2229 /* This is the default block used for each entry.
2230 * to avoid unset indexes.
2231 */
2232 $def_check = array("REQUIRED_VERSION" => "0",
2233 "SCHEMA_FILES" => array(),
2234 "CLASSES_REQUIRED" => array(),
2235 "STATUS" => FALSE,
2236 "IS_MUST_HAVE" => FALSE,
2237 "MSG" => "",
2238 "INFO" => "");#_("There is currently no information specified for this schema extension."));
2240 /* The gosa base schema */
2241 $checks['gosaObject'] = $def_check;
2242 $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2243 $checks['gosaObject']['SCHEMA_FILES'] = array("gosa-samba3.schema","gosa-samba2.schema");
2244 $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2245 $checks['gosaObject']['IS_MUST_HAVE'] = TRUE;
2247 /* GOsa Account class */
2248 $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.6";
2249 $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa-samba3.schema","gosa-samba2.schema");
2250 $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2251 $checks["gosaAccount"]["IS_MUST_HAVE"] = TRUE;
2252 $checks["gosaAccount"]["INFO"] = _("Used to store account specific informations.");
2254 /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2255 $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2256 $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa-samba3.schema","gosa-samba2.schema");
2257 $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2258 $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE;
2259 $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2261 /* Some other checks */
2262 foreach(array(
2263 "gosaCacheEntry" => array("version" => "2.6.1", "class" => "gosaAccount"),
2264 "gosaDepartment" => array("version" => "2.6.1", "class" => "gosaAccount"),
2265 "goFaxAccount" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2266 "goFaxSBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2267 "goFaxRBlock" => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2268 "gosaUserTemplate" => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2269 "gosaMailAccount" => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa-samba3.schema"),
2270 "gosaProxyAccount" => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa-samba3.schema"),
2271 "gosaApplication" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2272 "gosaApplicationGroup" => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2273 "GOhard" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2274 "gotoTerminal" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2275 "goServer" => array("version" => "2.6.1", "class" => "server","file" => "goserver.schema"),
2276 "goTerminalServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2277 "goShareServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2278 "goNtpServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2279 "goSyslogServer" => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2280 "goLdapServer" => array("version" => "2.6.1", "class" => "goServer"),
2281 "goCupsServer" => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2282 "goImapServer" => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa-samba3.schema"),
2283 "goKrbServer" => array("version" => "2.6.1", "class" => "goServer"),
2284 "goFaxServer" => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2285 ) as $name => $values){
2287 $checks[$name] = $def_check;
2288 if(isset($values['version'])){
2289 $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2290 }
2291 if(isset($values['file'])){
2292 $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2293 }
2294 if (isset($values['class'])) {
2295 $checks[$name]["CLASSES_REQUIRED"] = is_array($values['class'])?$values['class']:array($values['class']);
2296 }
2297 }
2298 foreach($checks as $name => $value){
2299 foreach($value['CLASSES_REQUIRED'] as $class){
2301 if(!isset($objectclasses[$name])){
2302 if($value['IS_MUST_HAVE']){
2303 $checks[$name]['STATUS'] = FALSE;
2304 $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class);
2305 } else {
2306 $checks[$name]['STATUS'] = TRUE;
2307 $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class);
2308 }
2309 }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2310 $checks[$name]['STATUS'] = FALSE;
2312 $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']);
2313 }else{
2314 $checks[$name]['STATUS'] = TRUE;
2315 $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2316 }
2317 }
2318 }
2320 $tmp = $objectclasses;
2322 /* The gosa base schema */
2323 $checks['posixGroup'] = $def_check;
2324 $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2325 $checks['posixGroup']['SCHEMA_FILES'] = array("gosa-samba3.schema","gosa-samba2.schema");
2326 $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2327 $checks['posixGroup']['STATUS'] = TRUE;
2328 $checks['posixGroup']['IS_MUST_HAVE'] = TRUE;
2329 $checks['posixGroup']['MSG'] = "";
2330 $checks['posixGroup']['INFO'] = "";
2332 /* Depending on selected rfc2307bis mode, we need different schema configurations */
2333 if(isset($tmp['posixGroup'])){
2335 if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2336 $checks['posixGroup']['STATUS'] = FALSE;
2337 $checks['posixGroup']['MSG'] = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema configuration do not support this option.");
2338 $checks['posixGroup']['INFO'] = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be AUXILIARY");
2339 }
2340 if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2341 $checks['posixGroup']['STATUS'] = FALSE;
2342 $checks['posixGroup']['MSG'] = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2343 $checks['posixGroup']['INFO'] = _("The objectClass 'posixGroup' must be STRUCTURAL");
2344 }
2345 }
2347 return($checks);
2348 }
2351 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2352 {
2353 $tmp = array(
2354 "de_DE" => "German",
2355 "fr_FR" => "French",
2356 "it_IT" => "Italian",
2357 "es_ES" => "Spanish",
2358 "en_US" => "English",
2359 "nl_NL" => "Dutch",
2360 "pl_PL" => "Polish",
2361 #"sv_SE" => "Swedish",
2362 "zh_CN" => "Chinese",
2363 "vi_VN" => "Vietnamese",
2364 "ru_RU" => "Russian");
2366 $tmp2= array(
2367 "de_DE" => _("German"),
2368 "fr_FR" => _("French"),
2369 "it_IT" => _("Italian"),
2370 "es_ES" => _("Spanish"),
2371 "en_US" => _("English"),
2372 "nl_NL" => _("Dutch"),
2373 "pl_PL" => _("Polish"),
2374 #"sv_SE" => _("Swedish"),
2375 "zh_CN" => _("Chinese"),
2376 "vi_VN" => _("Vietnamese"),
2377 "ru_RU" => _("Russian"));
2379 $ret = array();
2380 if($languages_in_own_language){
2382 $old_lang = setlocale(LC_ALL, 0);
2384 /* If the locale wasn't correclty set before, there may be an incorrect
2385 locale returned. Something like this:
2386 C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2387 Extract the locale name from this string and use it to restore old locale.
2388 */
2389 if(preg_match("/LC_CTYPE/",$old_lang)){
2390 $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2391 }
2393 foreach($tmp as $key => $name){
2394 $lang = $key.".UTF-8";
2395 setlocale(LC_ALL, $lang);
2396 if($strip_region_tag){
2397 $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2398 }else{
2399 $ret[$key] = _($name)." (".$tmp2[$key].")";
2400 }
2401 }
2402 setlocale(LC_ALL, $old_lang);
2403 }else{
2404 foreach($tmp as $key => $name){
2405 if($strip_region_tag){
2406 $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2407 }else{
2408 $ret[$key] = _($name);
2409 }
2410 }
2411 }
2412 return($ret);
2413 }
2416 /* Returns contents of the given POST variable and check magic quotes settings */
2417 function get_post($name)
2418 {
2419 if(!isset($_POST[$name])){
2420 trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2421 return(FALSE);
2422 }
2424 if(get_magic_quotes_gpc()){
2425 return(stripcslashes(validate($_POST[$name])));
2426 }else{
2427 return(validate($_POST[$name]));
2428 }
2429 }
2432 /* Return class name in correct case */
2433 function get_correct_class_name($cls)
2434 {
2435 global $class_mapping;
2436 if(isset($class_mapping) && is_array($class_mapping)){
2437 foreach($class_mapping as $class => $file){
2438 if(preg_match("/^".$cls."$/i",$class)){
2439 return($class);
2440 }
2441 }
2442 }
2443 return(FALSE);
2444 }
2447 // change_password, changes the Password, of the given dn
2448 function change_password ($dn, $password, $mode=0, $hash= "")
2449 {
2450 global $config;
2451 $newpass= "";
2453 /* Convert to lower. Methods are lowercase */
2454 $hash= strtolower($hash);
2456 // Get all available encryption Methods
2458 // NON STATIC CALL :)
2459 $methods = new passwordMethod(session::get('config'));
2460 $available = $methods->get_available_methods();
2462 // read current password entry for $dn, to detect the encryption Method
2463 $ldap = $config->get_ldap_link();
2464 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2465 $attrs = $ldap->fetch ();
2467 /* Is ensure that clear passwords will stay clear */
2468 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2469 $hash = "clear";
2470 }
2472 // Detect the encryption Method
2473 if ( (isset($attrs['userPassword'][0]) && preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) || $hash != ""){
2475 /* Check for supported algorithm */
2476 mt_srand((double) microtime()*1000000);
2478 /* Extract used hash */
2479 if ($hash == ""){
2480 $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2481 } else {
2482 $test = new $available[$hash]($config,$dn);
2483 $test->set_hash($hash);
2484 }
2486 } else {
2487 // User MD5 by default
2488 $hash= "md5";
2489 $test = new $available['md5']($config);
2490 }
2492 if($test instanceOf passwordMethod){
2494 $deactivated = $test->is_locked($config,$dn);
2496 /* Feed password backends with information */
2497 $test->dn= $dn;
2498 $test->attrs= $attrs;
2499 $newpass= $test->generate_hash($password);
2501 // Update shadow timestamp?
2502 if (isset($attrs["shadowLastChange"][0])){
2503 $shadow= (int)(date("U") / 86400);
2504 } else {
2505 $shadow= 0;
2506 }
2508 // Write back modified entry
2509 $ldap->cd($dn);
2510 $attrs= array();
2512 // Not for groups
2513 if ($mode == 0){
2515 if ($shadow != 0){
2516 $attrs['shadowLastChange']= $shadow;
2517 }
2519 // Create SMB Password
2520 $attrs= generate_smb_nt_hash($password);
2521 }
2523 $attrs['userPassword']= array();
2524 $attrs['userPassword']= $newpass;
2526 $ldap->modify($attrs);
2528 /* Read ! if user was deactivated */
2529 if($deactivated){
2530 $test->lock_account($config,$dn);
2531 }
2533 new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2535 if (!$ldap->success()) {
2536 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2537 } else {
2539 /* Run backend method for change/create */
2540 if(!$test->set_password($password)){
2541 return(FALSE);
2542 }
2544 /* Find postmodify entries for this class */
2545 $command= $config->search("password", "POSTMODIFY",array('menu'));
2547 if ($command != ""){
2548 /* Walk through attribute list */
2549 $command= preg_replace("/%userPassword/", $password, $command);
2550 $command= preg_replace("/%dn/", $dn, $command);
2552 if (check_command($command)){
2553 @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2554 exec($command);
2555 } else {
2556 $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2557 msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2558 }
2559 }
2560 }
2561 return(TRUE);
2562 }
2563 }
2566 // Return something like array['sambaLMPassword']= "lalla..."
2567 function generate_smb_nt_hash($password)
2568 {
2569 global $config;
2571 # Try to use gosa-si?
2572 if ($config->get_cfg_value("gosaSupportURI") != ""){
2573 $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2574 if (isset($res['XML']['HASH'])){
2575 $hash= $res['XML']['HASH'];
2576 } else {
2577 $hash= "";
2578 }
2580 if ($hash == "") {
2581 msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2582 return ("");
2583 }
2584 } else {
2585 $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
2586 @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2588 exec($tmp, $ar);
2589 flush();
2590 reset($ar);
2591 $hash= current($ar);
2593 if ($hash == "") {
2594 msg_dialog::display(_("Configuration error"), sprintf(_("Cannot generate samba hash: running '%s' failed, check the 'sambaHashHook'!"),$config->get_cfg_value('sambaHashHook')), ERROR_DIALOG);
2595 return ("");
2596 }
2597 }
2599 list($lm,$nt)= split (":", trim($hash));
2601 $attrs['sambaLMPassword']= $lm;
2602 $attrs['sambaNTPassword']= $nt;
2603 $attrs['sambaPwdLastSet']= date('U');
2604 $attrs['sambaBadPasswordCount']= "0";
2605 $attrs['sambaBadPasswordTime']= "0";
2606 return($attrs);
2607 }
2610 function getEntryCSN($dn)
2611 {
2612 global $config;
2613 if(empty($dn) || !is_object($config)){
2614 return("");
2615 }
2617 /* Get attribute that we should use as serial number */
2618 $attr= $config->get_cfg_value("modificationDetectionAttribute");
2619 if($attr != ""){
2620 $ldap = $config->get_ldap_link();
2621 $ldap->cat($dn,array($attr));
2622 $csn = $ldap->fetch();
2623 if(isset($csn[$attr][0])){
2624 return($csn[$attr][0]);
2625 }
2626 }
2627 return("");
2628 }
2631 /* Add a given objectClass to an attrs entry */
2632 function add_objectClass($classes, &$attrs)
2633 {
2634 if (is_array($classes)){
2635 $list= $classes;
2636 } else {
2637 $list= array($classes);
2638 }
2640 foreach ($list as $class){
2641 $attrs['objectClass'][]= $class;
2642 }
2643 }
2646 /* Removes a given objectClass from the attrs entry */
2647 function remove_objectClass($classes, &$attrs)
2648 {
2649 if (isset($attrs['objectClass'])){
2650 /* Array? */
2651 if (is_array($classes)){
2652 $list= $classes;
2653 } else {
2654 $list= array($classes);
2655 }
2657 $tmp= array();
2658 foreach ($attrs['objectClass'] as $oc) {
2659 foreach ($list as $class){
2660 if (strtolower($oc) != strtolower($class)){
2661 $tmp[]= $oc;
2662 }
2663 }
2664 }
2665 $attrs['objectClass']= $tmp;
2666 }
2667 }
2669 /*! \brief Initialize a file download with given content, name and data type.
2670 * @param data String The content to send.
2671 * @param name String The name of the file.
2672 * @param type String The content identifier, default value is "application/octet-stream";
2673 */
2674 function send_binary_content($data,$name,$type = "application/octet-stream")
2675 {
2676 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2677 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2678 header("Cache-Control: no-cache");
2679 header("Pragma: no-cache");
2680 header("Cache-Control: post-check=0, pre-check=0");
2681 header("Content-type: ".$type."");
2683 $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2685 /* Strip name if it is a complete path */
2686 if (preg_match ("/\//", $name)) {
2687 $name= basename($name);
2688 }
2690 /* force download dialog */
2691 if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2692 header('Content-Disposition: filename="'.$name.'"');
2693 } else {
2694 header('Content-Disposition: attachment; filename="'.$name.'"');
2695 }
2697 echo $data;
2698 exit();
2699 }
2702 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2703 {
2704 if(is_string($str)){
2705 return(htmlentities($str,$type,$charset));
2706 }elseif(is_array($str)){
2707 foreach($str as $name => $value){
2708 $str[$name] = reverse_html_entities($value,$type,$charset);
2709 }
2710 }
2711 return($str);
2712 }
2715 /*! \brief Encode special string characters so we can use the string in \
2716 HTML output, without breaking quotes.
2717 @param The String we want to encode.
2718 @return The encoded String
2719 */
2720 function xmlentities($str)
2721 {
2722 if(is_string($str)){
2724 static $asc2uni= array();
2725 if (!count($asc2uni)){
2726 for($i=128;$i<256;$i++){
2727 # $asc2uni[chr($i)] = "&#x".dechex($i).";";
2728 }
2729 }
2731 $str = str_replace("&", "&", $str);
2732 $str = str_replace("<", "<", $str);
2733 $str = str_replace(">", ">", $str);
2734 $str = str_replace("'", "'", $str);
2735 $str = str_replace("\"", """, $str);
2736 $str = str_replace("\r", "", $str);
2737 $str = strtr($str,$asc2uni);
2738 return $str;
2739 }elseif(is_array($str)){
2740 foreach($str as $name => $value){
2741 $str[$name] = xmlentities($value);
2742 }
2743 }
2744 return($str);
2745 }
2748 /*! \brief Updates all accessTo attributes from a given value to a new one.
2749 For example if a host is renamed.
2750 @param String $from The source accessTo name.
2751 @param String $to The destination accessTo name.
2752 */
2753 function update_accessTo($from,$to)
2754 {
2755 global $config;
2756 $ldap = $config->get_ldap_link();
2757 $ldap->cd($config->current['BASE']);
2758 $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2759 while($attrs = $ldap->fetch()){
2760 $new_attrs = array("accessTo" => array());
2761 $dn = $attrs['dn'];
2762 for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2763 $new_attrs['objectClass'][] = $attrs['objectClass'][$i];
2764 }
2765 for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2766 if($attrs['accessTo'][$i] == $from){
2767 if(!empty($to)){
2768 $new_attrs['accessTo'][] = $to;
2769 }
2770 }else{
2771 $new_attrs['accessTo'][] = $attrs['accessTo'][$i];
2772 }
2773 }
2774 $ldap->cd($dn);
2775 $ldap->modify($new_attrs);
2776 if (!$ldap->success()){
2777 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2778 }
2779 new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2780 }
2781 }
2784 function get_random_char () {
2785 $randno = rand (0, 63);
2786 if ($randno < 12) {
2787 return (chr ($randno + 46)); // Digits, '/' and '.'
2788 } else if ($randno < 38) {
2789 return (chr ($randno + 53)); // Uppercase
2790 } else {
2791 return (chr ($randno + 59)); // Lowercase
2792 }
2793 }
2796 function cred_encrypt($input, $password) {
2798 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2799 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2801 return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2803 }
2806 function cred_decrypt($input,$password) {
2807 $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2808 $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2810 return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2811 }
2814 function get_object_info()
2815 {
2816 return(session::get('objectinfo'));
2817 }
2820 function set_object_info($str = "")
2821 {
2822 session::set('objectinfo',$str);
2823 }
2826 function isIpInNet($ip, $net, $mask) {
2827 // Move to long ints
2828 $ip= ip2long($ip);
2829 $net= ip2long($net);
2830 $mask= ip2long($mask);
2832 // Mask given IP with mask. If it returns "net", we're in...
2833 $res= $ip & $mask;
2835 return ($res == $net);
2836 }
2839 function get_next_id($attrib, $dn)
2840 {
2841 global $config;
2843 switch ($config->get_cfg_value("idAllocationMethod", "traditional")){
2844 case "pool":
2845 return get_next_id_pool($attrib);
2846 case "traditional":
2847 return get_next_id_traditional($attrib, $dn);
2848 }
2850 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("unknown idAllocation method!"), ERROR_DIALOG);
2851 return null;
2852 }
2855 function get_next_id_pool($attrib) {
2856 global $config;
2858 /* Fill informational values */
2859 $min= $config->get_cfg_value("${attrib}PoolMin", 10000);
2860 $max= $config->get_cfg_value("${attrib}PoolMax", 40000);
2862 /* Sanity check */
2863 if ($min >= $max) {
2864 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." ".sprintf(_("%sPoolMin >= %sPoolMax!"), $attrib), ERROR_DIALOG);
2865 return null;
2866 }
2868 /* ID to skip */
2869 $ldap= $config->get_ldap_link();
2870 $id= null;
2872 /* Try to allocate the ID several times before failing */
2873 $tries= 3;
2874 while ($tries--) {
2876 /* Look for ID map entry */
2877 $ldap->cd ($config->current['BASE']);
2878 $ldap->search ("(&(objectClass=sambaUnixIdPool)($attrib=*))", array("$attrib"));
2880 /* If it does not exist, create one with these defaults */
2881 if ($ldap->count() == 0) {
2882 /* Fill informational values */
2883 $minUserId= $config->get_cfg_value("uidPoolMin", 10000);
2884 $minGroupId= $config->get_cfg_value("gidPoolMin", 10000);
2886 /* Add as default */
2887 $attrs= array("objectClass" => array("organizationalUnit", "sambaUnixIdPool"));
2888 $attrs["ou"]= "idmap";
2889 $attrs["uidNumber"]= $minUserId;
2890 $attrs["gidNumber"]= $minGroupId;
2891 $ldap->cd("ou=idmap,".$config->current['BASE']);
2892 $ldap->add($attrs);
2893 if ($ldap->error != "Success") {
2894 msg_dialog::display(_("Error"), _("Cannot create sambaUnixIdPool entry!"), ERROR_DIALOG);
2895 return null;
2896 }
2897 $tries++;
2898 continue;
2899 }
2900 /* Bail out if it's not unique */
2901 if ($ldap->count() != 1) {
2902 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("sambaUnixIdPool is not unique!"), ERROR_DIALOG);
2903 return null;
2904 }
2906 /* Store old attrib and generate new */
2907 $attrs= $ldap->fetch();
2908 $dn= $ldap->getDN();
2909 $oldAttr= $attrs[$attrib][0];
2910 $newAttr= $oldAttr + 1;
2912 /* Sanity check */
2913 if ($newAttr >= $max) {
2914 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("no ID available!"), ERROR_DIALOG);
2915 return null;
2916 }
2917 if ($newAttr < $min) {
2918 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("no ID available!"), ERROR_DIALOG);
2919 return null;
2920 }
2922 #FIXME: PHP is not able to do a modification of "del: .../add: ...", so this
2923 # is completely unsafe in the moment.
2924 #/* Remove old attr, add new attr */
2925 #$attrs= array($attrib => $oldAttr);
2926 #$ldap->rm($attrs, $dn);
2927 #if ($ldap->error != "Success") {
2928 # continue;
2929 #}
2930 $ldap->cd($dn);
2931 $ldap->modify(array($attrib => $newAttr));
2932 if ($ldap->error != "Success") {
2933 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." ".$ldap->get_error(), ERROR_DIALOG);
2934 return null;
2935 } else {
2936 return $oldAttr;
2937 }
2938 }
2940 /* Bail out if we had problems getting the next id */
2941 if (!$tries) {
2942 msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("maximum tries exceeded!"), ERROR_DIALOG);
2943 }
2945 return $id;
2946 }
2948 function get_next_id_traditional($attrib, $dn)
2949 {
2950 global $config;
2952 $ids= array();
2953 $ldap= $config->get_ldap_link();
2955 $ldap->cd ($config->current['BASE']);
2956 if (preg_match('/gidNumber/i', $attrib)){
2957 $oc= "posixGroup";
2958 } else {
2959 $oc= "posixAccount";
2960 }
2961 $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
2963 /* Get list of ids */
2964 while ($attrs= $ldap->fetch()){
2965 $ids[]= (int)$attrs["$attrib"][0];
2966 }
2968 /* Add the nobody id */
2969 $ids[]= 65534;
2971 /* get the ranges */
2972 $tmp = array('0'=> 1000);
2973 if (preg_match('/posixAccount/', $oc) && $config->get_cfg_value("uidNumberBase") != ""){
2974 $tmp= split('-',$config->get_cfg_value("uidNumberBase"));
2975 } elseif($config->get_cfg_value("gidNumberBase") != ""){
2976 $tmp= split('-',$config->get_cfg_value("gidNumberBase"));
2977 }
2979 /* Set hwm to max if not set - for backward compatibility */
2980 $lwm= $tmp[0];
2981 if (isset($tmp[1])){
2982 $hwm= $tmp[1];
2983 } else {
2984 $hwm= pow(2,32);
2985 }
2986 /* Find out next free id near to UID_BASE */
2987 if ($config->get_cfg_value("baseIdHook") == ""){
2988 $base= $lwm;
2989 } else {
2990 /* Call base hook */
2991 $base= get_base_from_hook($dn, $attrib);
2992 }
2993 for ($id= $base; $id++; $id < pow(2,32)){
2994 if (!in_array($id, $ids)){
2995 return ($id);
2996 }
2997 }
2999 /* Should not happen */
3000 if ($id == $hwm){
3001 msg_dialog::display(_("Error"), _("Cannot allocate a free ID!"), ERROR_DIALOG);
3002 exit;
3003 }
3004 }
3007 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3008 ?>