Code

Added allocation algorithms
[gosa.git] / gosa-core / include / functions.inc
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     }
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)
140   global $class_mapping;
141   return(isset($class_mapping[$name]));
145 /* Check if plugin is avaliable */
146 function plugin_available($plugin)
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         }
158 /* Create seed with microseconds */
159 function make_seed() {
160   list($usec, $sec) = explode(' ', microtime());
161   return (float) $sec + ((float) $usec * 100000);
165 /* Debug level action */
166 function DEBUG($level, $line, $function, $file, $data, $info="")
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   }
186 function get_browser_language()
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   }
205  
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'));
220 /* Rewrite ui object to another dn */
221 function change_ui_dn($dn, $newdn)
223   $ui= session::global_get('ui');
224   if ($ui->dn == $dn){
225     $ui->dn= $newdn;
226     session::global_set('ui',$ui);
227   }
231 /* Return theme path for specified file */
232 function get_template_path($filename= '', $plugin= FALSE, $path= "")
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   }
284 function array_remove_entries($needles, $haystack)
286   return (array_merge(array_diff($haystack, $needles)));
290 function array_remove_entries_ics($needles, $haystack)
292   // strcasecmp will work, because we only compare ASCII values here
293   return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
297 function gosa_array_merge($ar1,$ar2)
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   }
307 function gosa_log ($message)
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");
327 function ldap_init ($server, $base, $binddn='', $pass='')
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;
349 function process_htaccess ($username, $kerberos= FALSE)
351   global $config;
353   /* Search for $username and optional @REALM in all configured LDAP trees */
354   foreach($config->data["LOCATIONS"] as $name => $data){
355   
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" => "");
384 function ldap_login_user_htaccess ($username)
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);
427 function ldap_login_user ($username, $password)
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);
518 function ldap_expired_account($config, $userdn, $username)
520     $ldap= $config->get_ldap_link();
521     $ldap->cat($userdn);
522     $attrs= $ldap->fetch();
523     
524     /* default value no errors */
525     $expired = 0;
526     
527     $sExpire = 0;
528     $sLastChange = 0;
529     $sMax = 0;
530     $sMin = 0;
531     $sInactive = 0;
532     $sWarning = 0;
533     
534     $current= date("U");
535     
536     $current= floor($current /60 /60 /24);
537     
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       }
548       
549       if(isset($attrs['shadowLastChange'][0])){
550         $sLastChange= $attrs['shadowLastChange'][0];
551       } else {
552         $sLastChange = 0;
553       }
554       
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       }
566       
567       if(isset($attrs['shadowInactive'][0])){
568         $sInactive= $attrs['shadowInactive'][0];
569       } else {
570         $sInactive = 0;
571       }
572       
573       if(isset($attrs['shadowWarning'][0])){
574         $sWarning= $attrs['shadowWarning'][0];
575       } else {
576         $sWarning = 0;
577       }
578       
579       /* is the account locked */
580       /* shadowExpire + shadowInactive (option) */
581       if($sExpire >0){
582         if($current >= ($sExpire+$sInactive)){
583           return(1);
584         }
585       }
586     
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       }
593       
594       /* force user to change password */
595       if(($sLastChange >0) && ($sMax) >0){
596         if($current >= ($sLastChange+$sMax)){
597           return(3);
598         }
599       }
600       
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);
612 function add_lock($object, $user)
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   }
673 function del_lock ($object)
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   }
716 function del_user_locks($userdn)
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   }
732 function get_lock ($object)
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);
776 function get_multiple_locks($objects)
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);
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)
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{
855         
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   }
865   
866    /* If there is no sub_department specified, fall back to old method, get_list().
867    */
868   if(!count($sub_bases) && !count($departments)){
869     
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);
971 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
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   }
1031  
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);
1039 function check_sizelimit()
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 ("");
1059 function print_sizelimit_warning()
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 ("");
1074 function eval_sizelimit()
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   }
1105 function getMenuCache()
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   }
1128 function &get_userinfo()
1130   global $ui;
1132   return $ui;
1136 function &get_smarty()
1138   global $smarty;
1140   return $smarty;
1144 function convert_department_dn($dn, $base = NULL)
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, "/"));
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)
1172   return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1176 function get_ou($name)
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   }
1223  
1224  
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     }
1237   
1238   } else {
1239     return "";
1240   }
1244 function get_people_ou()
1246   return (get_ou("userRDN"));
1250 function get_groups_ou()
1252   return (get_ou("groupRDN"));
1256 function get_winstations_ou()
1258   return (get_ou("sambaMachineAccountRDN"));
1262 function get_base_from_people($dn)
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);
1278 function strict_uid_mode()
1280   global $config;
1282   if (isset($config)){
1283     return ($config->get_cfg_value("strictNamingRules") == "true");
1284   }
1285   return (TRUE);
1289 function get_uid_regexp()
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   }
1301 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
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')));
1371 function to_string ($value)
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   }
1386 function get_printer_list()
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;
1398 function rewrite($s)
1400   global $REWRITE;
1402   foreach ($REWRITE as $key => $val){
1403     $s= str_replace("$key", "$val", $s);
1404   }
1406   return ($s);
1410 function dn2base($dn)
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);
1427 function check_command($cmdline)
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);
1445 function print_header($image, $headline, $info= "")
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=\"*\">&nbsp;$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.= "&nbsp;";
1458     $display.= "</div>\n";
1459   }
1460   return ($display);
1464 function range_selector($dcnt,$start,$range=25,$post_var=false)
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'])."&amp;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'])."&amp;start=".
1534         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1535     } else {
1536       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1537         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1538     }
1539   }
1541   /* Draw increment */
1542   if($start < ($dcnt-$range)) {
1543     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;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;'>&nbsp;"._("Entries per page")."&nbsp;<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);
1571 function apply_filter()
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);
1583 function back_to_main()
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);
1592 function normalize_netmask($netmask)
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);
1618 function netmask_to_bits($netmask)
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);
1640 function recurse($rule, $variables)
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);
1662 function expand_id($rule, $attributes)
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));
1697 function gen_uids($rule, $attributes)
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); $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       }
1760     }
1762     if(preg_match('/\{id#\d+}/',$uid)){
1763       $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1765       while (true){
1766         mt_srand((double) microtime()*1000000);
1767         $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1768         $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1769         $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
1770         if($ldap->count() == 0){
1771           $uid= $res;
1772           break;
1773         }
1774       }
1775     }
1777     /* Don't assign used ones */
1778     $ldap->search("(uid=".preg_replace('/[{}]/', '', $uid).")",array('dn'));
1779     if($ldap->count() == 0){
1780       /* Add uid, but remove {} first. These are invalid anyway. */
1781       $ret[]= preg_replace('/[{}]/', '', $uid);
1782     }
1783   }
1785   return(array_unique($ret));
1789 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1790    Need to convert... */
1791 function to_byte($value) {
1792   $value= strtolower(trim($value));
1794   if(!is_numeric(substr($value, -1))) {
1796     switch(substr($value, -1)) {
1797       case 'g':
1798         $mult= 1073741824;
1799         break;
1800       case 'm':
1801         $mult= 1048576;
1802         break;
1803       case 'k':
1804         $mult= 1024;
1805         break;
1806     }
1808     return ($mult * (int)substr($value, 0, -1));
1809   } else {
1810     return $value;
1811   }
1815 function in_array_ics($value, $items)
1817         return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
1821 function generate_alphabet($count= 10)
1823   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1824   $alphabet= "";
1825   $c= 0;
1827   /* Fill cells with charaters */
1828   for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
1829     if ($c == 0){
1830       $alphabet.= "<tr>";
1831     }
1833     $ch = mb_substr($characters, $i, 1, "UTF8");
1834     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1835       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1837     if ($c++ == $count){
1838       $alphabet.= "</tr>";
1839       $c= 0;
1840     }
1841   }
1843   /* Fill remaining cells */
1844   while ($c++ <= $count){
1845     $alphabet.= "<td>&nbsp;</td>";
1846   }
1848   return ($alphabet);
1852 function validate($string)
1854   return (strip_tags(str_replace('\0', '', $string)));
1858 function get_gosa_version()
1860   global $svn_revision, $svn_path;
1862   /* Extract informations */
1863   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1865   /* Release or development? */
1866   if (preg_match('%/gosa/trunk/%', $svn_path)){
1867     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1868   } else {
1869     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1870     return (sprintf(_("GOsa $release"), $revision));
1871   }
1875 function rmdirRecursive($path, $followLinks=false) {
1876   $dir= opendir($path);
1877   while($entry= readdir($dir)) {
1878     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1879       unlink($path."/".$entry);
1880     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1881       rmdirRecursive($path."/".$entry);
1882     }
1883   }
1884   closedir($dir);
1885   return rmdir($path);
1889 function scan_directory($path,$sort_desc=false)
1891   $ret = false;
1893   /* is this a dir ? */
1894   if(is_dir($path)) {
1896     /* is this path a readable one */
1897     if(is_readable($path)){
1899       /* Get contents and write it into an array */   
1900       $ret = array();    
1902       $dir = opendir($path);
1904       /* Is this a correct result ?*/
1905       if($dir){
1906         while($fp = readdir($dir))
1907           $ret[]= $fp;
1908       }
1909     }
1910   }
1911   /* Sort array ascending , like scandir */
1912   sort($ret);
1914   /* Sort descending if parameter is sort_desc is set */
1915   if($sort_desc) {
1916     $ret = array_reverse($ret);
1917   }
1919   return($ret);
1923 function clean_smarty_compile_dir($directory)
1925   global $svn_revision;
1927   if(is_dir($directory) && is_readable($directory)) {
1928     // Set revision filename to REVISION
1929     $revision_file= $directory."/REVISION";
1931     /* Is there a stamp containing the current revision? */
1932     if(!file_exists($revision_file)) {
1933       // create revision file
1934       create_revision($revision_file, $svn_revision);
1935     } else {
1936       # check for "$config->...['CONFIG']/revision" and the
1937       # contents should match the revision number
1938       if(!compare_revision($revision_file, $svn_revision)){
1939         // If revision differs, clean compile directory
1940         foreach(scan_directory($directory) as $file) {
1941           if(($file==".")||($file=="..")) continue;
1942           if( is_file($directory."/".$file) &&
1943               is_writable($directory."/".$file)) {
1944             // delete file
1945             if(!unlink($directory."/".$file)) {
1946               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1947               // This should never be reached
1948             }
1949           } elseif(is_dir($directory."/".$file) &&
1950               is_writable($directory."/".$file)) {
1951             // Just recursively delete it
1952             rmdirRecursive($directory."/".$file);
1953           }
1954         }
1955         // We should now create a fresh revision file
1956         clean_smarty_compile_dir($directory);
1957       } else {
1958         // Revision matches, nothing to do
1959       }
1960     }
1961   } else {
1962     // Smarty compile dir is not accessible
1963     // (Smarty will warn about this)
1964   }
1968 function create_revision($revision_file, $revision)
1970   $result= false;
1972   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1973     if($fh= fopen($revision_file, "w")) {
1974       if(fwrite($fh, $revision)) {
1975         $result= true;
1976       }
1977     }
1978     fclose($fh);
1979   } else {
1980     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1981   }
1983   return $result;
1987 function compare_revision($revision_file, $revision)
1989   // false means revision differs
1990   $result= false;
1992   if(file_exists($revision_file) && is_readable($revision_file)) {
1993     // Open file
1994     if($fh= fopen($revision_file, "r")) {
1995       // Compare File contents with current revision
1996       if($revision == fread($fh, filesize($revision_file))) {
1997         $result= true;
1998       }
1999     } else {
2000       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2001     }
2002     // Close file
2003     fclose($fh);
2004   }
2006   return $result;
2010 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2012   return("<img src='progress.php?x=$width&amp;y=$height&amp;p=$percentage'>");
2016 function array_key_ics($ikey, $items)
2018   $tmp= array_change_key_case($items, CASE_LOWER);
2019   $ikey= strtolower($ikey);
2020   if (isset($tmp[$ikey])){
2021     return($tmp[$ikey]);
2022   }
2024   return ('');
2028 function array_differs($src, $dst)
2030   /* If the count is differing, the arrays differ */
2031   if (count ($src) != count ($dst)){
2032     return (TRUE);
2033   }
2035   return (count(array_diff($src, $dst)) != 0);
2039 function saveFilter($a_filter, $values)
2041   if (isset($_POST['regexit'])){
2042     $a_filter["regex"]= $_POST['regexit'];
2044     foreach($values as $type){
2045       if (isset($_POST[$type])) {
2046         $a_filter[$type]= "checked";
2047       } else {
2048         $a_filter[$type]= "";
2049       }
2050     }
2051   }
2053   /* React on alphabet links if needed */
2054   if (isset($_GET['search'])){
2055     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2056     if ($s == "**"){
2057       $s= "*";
2058     }
2059     $a_filter['regex']= $s;
2060   }
2062   return ($a_filter);
2066 /* Escape all LDAP filter relevant characters */
2067 function normalizeLdap($input)
2069   return (addcslashes($input, '()|'));
2073 /* Resturns the difference between to microtime() results in float  */
2074 function get_MicroTimeDiff($start , $stop)
2076   $a = split("\ ",$start);
2077   $b = split("\ ",$stop);
2079   $secs = $b[1] - $a[1];
2080   $msecs= $b[0] - $a[0]; 
2082   $ret = (float) ($secs+ $msecs);
2083   return($ret);
2087 function get_base_dir()
2089   global $BASE_DIR;
2091   return $BASE_DIR;
2095 function obj_is_readable($dn, $object, $attribute)
2097   global $ui;
2099   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2103 function obj_is_writable($dn, $object, $attribute)
2105   global $ui;
2107   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2111 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2113   /* Initialize variables */
2114   $ret  = array("count" => 0);  // Set count to 0
2115   $next = true;                 // if false, then skip next loops and return
2116   $cnt  = 0;                    // Current number of loops
2117   $max  = 100;                  // Just for security, prevent looops
2118   $ldap = NULL;                 // To check if created result a valid
2119   $keep = "";                   // save last failed parse string
2121   /* Check each parsed dn in ldap ? */
2122   if($config!==NULL && $verify_in_ldap){
2123     $ldap = $config->get_ldap_link();
2124   }
2126   /* Lets start */
2127   $called = false;
2128   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2130     $cnt ++;
2131     if(!preg_match("/,/",$dn)){
2132       $next = false;
2133     }
2134     $object = preg_replace("/[,].*$/","",$dn);
2135     $dn     = preg_replace("/^[^,]+,/","",$dn);
2137     $called = true;
2139     /* Check if current dn is valid */
2140     if($ldap!==NULL){
2141       $ldap->cd($dn);
2142       $ldap->cat($dn,array("dn"));
2143       if($ldap->count()){
2144         $ret[]  = $keep.$object;
2145         $keep   = "";
2146       }else{
2147         $keep  .= $object.",";
2148       }
2149     }else{
2150       $ret[]  = $keep.$object;
2151       $keep   = "";
2152     }
2153   }
2155   /* No dn was posted */
2156   if($cnt == 0 && !empty($dn)){
2157     $ret[] = $dn;
2158   }
2160   /* Append the rest */
2161   $test = $keep.$dn;
2162   if($called && !empty($test)){
2163     $ret[] = $keep.$dn;
2164   }
2165   $ret['count'] = count($ret) - 1;
2167   return($ret);
2171 function get_base_from_hook($dn, $attrib)
2173   global $config;
2175   if ($config->get_cfg_value("baseIdHook") != ""){
2176     
2177     /* Call hook script - if present */
2178     $command= $config->get_cfg_value("baseIdHook");
2180     if ($command != ""){
2181       $command.= " '".LDAP::fix($dn)."' $attrib";
2182       if (check_command($command)){
2183         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2184         exec($command, $output);
2185         if (preg_match("/^[0-9]+$/", $output[0])){
2186           return ($output[0]);
2187         } else {
2188           msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2189           return ($config->get_cfg_value("uidNumberBase"));
2190         }
2191       } else {
2192         msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2193         return ($config->get_cfg_value("uidNumberBase"));
2194       }
2196     } else {
2198       msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2199       return ($config->get_cfg_value("uidNumberBase"));
2201     }
2202   }
2206 function check_schema_version($class, $version)
2208   return preg_match("/\(v$version\)/", $class['DESC']);
2212 function check_schema($cfg,$rfc2307bis = FALSE)
2214   $messages= array();
2216   /* Get objectclasses */
2217   $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2218   $objectclasses = $ldap->get_objectclasses();
2219   if(count($objectclasses) == 0){
2220     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2221   }
2223   /* This is the default block used for each entry.
2224    *  to avoid unset indexes.
2225    */
2226   $def_check = array("REQUIRED_VERSION" => "0",
2227       "SCHEMA_FILES"     => array(),
2228       "CLASSES_REQUIRED" => array(),
2229       "STATUS"           => FALSE,
2230       "IS_MUST_HAVE"     => FALSE,
2231       "MSG"              => "",
2232       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2234   /* The gosa base schema */
2235   $checks['gosaObject'] = $def_check;
2236   $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2237   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa-samba3.schema","gosa-samba2.schema");
2238   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2239   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2241   /* GOsa Account class */
2242   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.6";
2243   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa-samba3.schema","gosa-samba2.schema");
2244   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2245   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2246   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2248   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2249   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2250   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa-samba3.schema","gosa-samba2.schema");
2251   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2252   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2253   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2255   /* Some other checks */
2256   foreach(array(
2257         "gosaCacheEntry"        => array("version" => "2.6.1", "class" => "gosaAccount"),
2258         "gosaDepartment"        => array("version" => "2.6.1", "class" => "gosaAccount"),
2259         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2260         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2261         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2262         "gosaUserTemplate"      => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2263         "gosaMailAccount"       => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa-samba3.schema"),
2264         "gosaProxyAccount"      => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa-samba3.schema"),
2265         "gosaApplication"       => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2266         "gosaApplicationGroup"  => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2267         "GOhard"                => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2268         "gotoTerminal"          => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2269         "goServer"              => array("version" => "2.6.1", "class" => "server","file" => "goserver.schema"),
2270         "goTerminalServer"      => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2271         "goShareServer"         => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2272         "goNtpServer"           => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2273         "goSyslogServer"        => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2274         "goLdapServer"          => array("version" => "2.6.1", "class" => "goServer"),
2275         "goCupsServer"          => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2276         "goImapServer"          => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa-samba3.schema"),
2277         "goKrbServer"           => array("version" => "2.6.1", "class" => "goServer"),
2278         "goFaxServer"           => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2279         ) as $name => $values){
2281           $checks[$name] = $def_check;
2282           if(isset($values['version'])){
2283             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2284           }
2285           if(isset($values['file'])){
2286             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2287           }
2288           if (isset($values['class'])) {
2289             $checks[$name]["CLASSES_REQUIRED"] = is_array($values['class'])?$values['class']:array($values['class']);
2290           }
2291         }
2292   foreach($checks as $name => $value){
2293     foreach($value['CLASSES_REQUIRED'] as $class){
2295       if(!isset($objectclasses[$name])){
2296         if($value['IS_MUST_HAVE']){
2297           $checks[$name]['STATUS'] = FALSE;
2298           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2299         } else {
2300           $checks[$name]['STATUS'] = TRUE;
2301           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2302         }
2303       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2304         $checks[$name]['STATUS'] = FALSE;
2306         $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2307       }else{
2308         $checks[$name]['STATUS'] = TRUE;
2309         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2310       }
2311     }
2312   }
2314   $tmp = $objectclasses;
2316   /* The gosa base schema */
2317   $checks['posixGroup'] = $def_check;
2318   $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2319   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa-samba3.schema","gosa-samba2.schema");
2320   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2321   $checks['posixGroup']['STATUS']           = TRUE;
2322   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2323   $checks['posixGroup']['MSG']              = "";
2324   $checks['posixGroup']['INFO']             = "";
2326   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2327   if(isset($tmp['posixGroup'])){
2329     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2330       $checks['posixGroup']['STATUS']           = FALSE;
2331       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2332       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2333     }
2334     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2335       $checks['posixGroup']['STATUS']           = FALSE;
2336       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2337       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2338     }
2339   }
2341   return($checks);
2345 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2347   $tmp = array(
2348         "de_DE" => "German",
2349         "fr_FR" => "French",
2350         "it_IT" => "Italian",
2351         "es_ES" => "Spanish",
2352         "en_US" => "English",
2353         "nl_NL" => "Dutch",
2354         "pl_PL" => "Polish",
2355         #"sv_SE" => "Swedish",
2356         "zh_CN" => "Chinese",
2357         "vi_VN" => "Vietnamese",
2358         "ru_RU" => "Russian");
2359   
2360   $tmp2= array(
2361         "de_DE" => _("German"),
2362         "fr_FR" => _("French"),
2363         "it_IT" => _("Italian"),
2364         "es_ES" => _("Spanish"),
2365         "en_US" => _("English"),
2366         "nl_NL" => _("Dutch"),
2367         "pl_PL" => _("Polish"),
2368         #"sv_SE" => _("Swedish"),
2369         "zh_CN" => _("Chinese"),
2370         "vi_VN" => _("Vietnamese"),
2371         "ru_RU" => _("Russian"));
2373   $ret = array();
2374   if($languages_in_own_language){
2376     $old_lang = setlocale(LC_ALL, 0);
2378     /* If the locale wasn't correclty set before, there may be an incorrect
2379         locale returned. Something like this: 
2380           C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2381         Extract the locale name from this string and use it to restore old locale.
2382      */
2383     if(preg_match("/LC_CTYPE/",$old_lang)){
2384       $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2385     }
2386     
2387     foreach($tmp as $key => $name){
2388       $lang = $key.".UTF-8";
2389       setlocale(LC_ALL, $lang);
2390       if($strip_region_tag){
2391         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2392       }else{
2393         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2394       }
2395     }
2396     setlocale(LC_ALL, $old_lang);
2397   }else{
2398     foreach($tmp as $key => $name){
2399       if($strip_region_tag){
2400         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2401       }else{
2402         $ret[$key] = _($name);
2403       }
2404     }
2405   }
2406   return($ret);
2410 /* Returns contents of the given POST variable and check magic quotes settings */
2411 function get_post($name)
2413   if(!isset($_POST[$name])){
2414     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2415     return(FALSE);
2416   }
2417   if(get_magic_quotes_gpc()){
2418     return(stripcslashes($_POST[$name]));
2419   }else{
2420     return($_POST[$name]);
2421   }
2425 /* Return class name in correct case */
2426 function get_correct_class_name($cls)
2428   global $class_mapping;
2429   if(isset($class_mapping) && is_array($class_mapping)){
2430     foreach($class_mapping as $class => $file){
2431       if(preg_match("/^".$cls."$/i",$class)){
2432         return($class);
2433       }
2434     }
2435   }
2436   return(FALSE);
2440 // change_password, changes the Password, of the given dn
2441 function change_password ($dn, $password, $mode=0, $hash= "")
2443   global $config;
2444   $newpass= "";
2446   /* Convert to lower. Methods are lowercase */
2447   $hash= strtolower($hash);
2449   // Get all available encryption Methods
2451   // NON STATIC CALL :)
2452   $methods = new passwordMethod(session::get('config'));
2453   $available = $methods->get_available_methods();
2455   // read current password entry for $dn, to detect the encryption Method
2456   $ldap       = $config->get_ldap_link();
2457   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2458   $attrs      = $ldap->fetch ();
2460   /* Is ensure that clear passwords will stay clear */
2461   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2462     $hash = "clear";
2463   }
2465   // Detect the encryption Method
2466   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2468     /* Check for supported algorithm */
2469     mt_srand((double) microtime()*1000000);
2471     /* Extract used hash */
2472     if ($hash == ""){
2473       $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2474     } else {
2475       $test = new $available[$hash]($config,$dn);
2476       $test->set_hash($hash);
2477     }
2479   } else {
2480     // User MD5 by default
2481     $hash= "md5";
2482     $test = new  $available['md5']($config);
2483   }
2485   if($test instanceOf passwordMethod){
2487     $deactivated = $test->is_locked($config,$dn);
2489     /* Feed password backends with information */
2490     $test->dn= $dn;
2491     $test->attrs= $attrs;
2492     $newpass= $test->generate_hash($password);
2494     // Update shadow timestamp?
2495     if (isset($attrs["shadowLastChange"][0])){
2496       $shadow= (int)(date("U") / 86400);
2497     } else {
2498       $shadow= 0;
2499     }
2501     // Write back modified entry
2502     $ldap->cd($dn);
2503     $attrs= array();
2505     // Not for groups
2506     if ($mode == 0){
2508       if ($shadow != 0){
2509         $attrs['shadowLastChange']= $shadow;
2510       }
2512       // Create SMB Password
2513       $attrs= generate_smb_nt_hash($password);
2514     }
2516     $attrs['userPassword']= array();
2517     $attrs['userPassword']= $newpass;
2519     $ldap->modify($attrs);
2521     /* Read ! if user was deactivated */
2522     if($deactivated){
2523       $test->lock_account($config,$dn);
2524     }
2526     new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2528     if (!$ldap->success()) {
2529       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2530     } else {
2532       /* Run backend method for change/create */
2533       if(!$test->set_password($password)){
2534         return(FALSE);
2535       }
2537       /* Find postmodify entries for this class */
2538       $command= $config->search("password", "POSTMODIFY",array('menu'));
2540       if ($command != ""){
2541         /* Walk through attribute list */
2542         $command= preg_replace("/%userPassword/", $password, $command);
2543         $command= preg_replace("/%dn/", $dn, $command);
2545         if (check_command($command)){
2546           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2547           exec($command);
2548         } else {
2549           $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2550           msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2551         }
2552       }
2553     }
2554     return(TRUE);
2555   }
2559 // Return something like array['sambaLMPassword']= "lalla..."
2560 function generate_smb_nt_hash($password)
2562   global $config;
2564   # Try to use gosa-si?
2565   if ($config->get_cfg_value("gosaSupportURI") != ""){
2566         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2567     if (isset($res['XML']['HASH'])){
2568         $hash= $res['XML']['HASH'];
2569     } else {
2570       $hash= "";
2571     }
2573     if ($hash == "") {
2574       msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2575       return ("");
2576     }
2577   } else {
2578           $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
2579           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2581           exec($tmp, $ar);
2582           flush();
2583           reset($ar);
2584           $hash= current($ar);
2586     if ($hash == "") {
2587       msg_dialog::display(_("Configuration error"), sprintf(_("Cannot generate samba hash: running '%s' failed, check the 'sambaHashHook'!"),$config->get_cfg_value('sambaHashHook')), ERROR_DIALOG);
2588       return ("");
2589     }
2590   }
2592   list($lm,$nt)= split (":", trim($hash));
2594   $attrs['sambaLMPassword']= $lm;
2595   $attrs['sambaNTPassword']= $nt;
2596   $attrs['sambaPwdLastSet']= date('U');
2597   $attrs['sambaBadPasswordCount']= "0";
2598   $attrs['sambaBadPasswordTime']= "0";
2599   return($attrs);
2603 function getEntryCSN($dn)
2605   global $config;
2606   if(empty($dn) || !is_object($config)){
2607     return("");
2608   }
2610   /* Get attribute that we should use as serial number */
2611   $attr= $config->get_cfg_value("modificationDetectionAttribute");
2612   if($attr != ""){
2613     $ldap = $config->get_ldap_link();
2614     $ldap->cat($dn,array($attr));
2615     $csn = $ldap->fetch();
2616     if(isset($csn[$attr][0])){
2617       return($csn[$attr][0]);
2618     }
2619   }
2620   return("");
2624 /* Add a given objectClass to an attrs entry */
2625 function add_objectClass($classes, &$attrs)
2627   if (is_array($classes)){
2628     $list= $classes;
2629   } else {
2630     $list= array($classes);
2631   }
2633   foreach ($list as $class){
2634     $attrs['objectClass'][]= $class;
2635   }
2639 /* Removes a given objectClass from the attrs entry */
2640 function remove_objectClass($classes, &$attrs)
2642   if (isset($attrs['objectClass'])){
2643     /* Array? */
2644     if (is_array($classes)){
2645       $list= $classes;
2646     } else {
2647       $list= array($classes);
2648     }
2650     $tmp= array();
2651     foreach ($attrs['objectClass'] as $oc) {
2652       foreach ($list as $class){
2653         if (strtolower($oc) != strtolower($class)){
2654           $tmp[]= $oc;
2655         }
2656       }
2657     }
2658     $attrs['objectClass']= $tmp;
2659   }
2662 /*! \brief  Initialize a file download with given content, name and data type. 
2663  *  @param  data  String The content to send.
2664  *  @param  name  String The name of the file.
2665  *  @param  type  String The content identifier, default value is "application/octet-stream";
2666  */
2667 function send_binary_content($data,$name,$type = "application/octet-stream")
2669   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2670   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2671   header("Cache-Control: no-cache");
2672   header("Pragma: no-cache");
2673   header("Cache-Control: post-check=0, pre-check=0");
2674   header("Content-type: ".$type."");
2676   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2678   /* Strip name if it is a complete path */
2679   if (preg_match ("/\//", $name)) {
2680         $name= basename($name);
2681   }
2682   
2683   /* force download dialog */
2684   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2685     header('Content-Disposition: filename="'.$name.'"');
2686   } else {
2687     header('Content-Disposition: attachment; filename="'.$name.'"');
2688   }
2690   echo $data;
2691   exit();
2695 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2697   if(is_string($str)){
2698     return(htmlentities($str,$type,$charset));
2699   }elseif(is_array($str)){
2700     foreach($str as $name => $value){
2701       $str[$name] = reverse_html_entities($value,$type,$charset);
2702     }
2703   }
2704   return($str);
2708 /*! \brief Encode special string characters so we can use the string in \
2709            HTML output, without breaking quotes.
2710     @param  The String we want to encode.
2711     @return The encoded String
2712  */
2713 function xmlentities($str)
2714
2715   if(is_string($str)){
2717     static $asc2uni= array();
2718     if (!count($asc2uni)){
2719       for($i=128;$i<256;$i++){
2720     #    $asc2uni[chr($i)] = "&#x".dechex($i).";";
2721       }
2722     }
2724     $str = str_replace("&", "&amp;", $str);
2725     $str = str_replace("<", "&lt;", $str);
2726     $str = str_replace(">", "&gt;", $str);
2727     $str = str_replace("'", "&apos;", $str);
2728     $str = str_replace("\"", "&quot;", $str);
2729     $str = str_replace("\r", "", $str);
2730     $str = strtr($str,$asc2uni);
2731     return $str;
2732   }elseif(is_array($str)){
2733     foreach($str as $name => $value){
2734       $str[$name] = xmlentities($value);
2735     }
2736   }
2737   return($str);
2741 /*! \brief  Updates all accessTo attributes from a given value to a new one.
2742             For example if a host is renamed.
2743     @param  String  $from The source accessTo name.
2744     @param  String  $to   The destination accessTo name.
2745 */
2746 function update_accessTo($from,$to)
2748   global $config;
2749   $ldap = $config->get_ldap_link();
2750   $ldap->cd($config->current['BASE']);
2751   $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2752   while($attrs = $ldap->fetch()){
2753     $new_attrs = array("accessTo" => array());
2754     $dn = $attrs['dn'];
2755     for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2756       $new_attrs['objectClass'][] =  $attrs['objectClass'][$i];
2757     }
2758     for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2759       if($attrs['accessTo'][$i] == $from){
2760         if(!empty($to)){
2761           $new_attrs['accessTo'][] =  $to;
2762         }
2763       }else{
2764         $new_attrs['accessTo'][] =  $attrs['accessTo'][$i]; 
2765       }
2766     }
2767     $ldap->cd($dn);
2768     $ldap->modify($new_attrs);
2769     if (!$ldap->success()){
2770       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2771     }
2772     new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2773   }
2777 function get_random_char () {
2778      $randno = rand (0, 63);
2779      if ($randno < 12) {
2780          return (chr ($randno + 46)); // Digits, '/' and '.'
2781      } else if ($randno < 38) {
2782          return (chr ($randno + 53)); // Uppercase
2783      } else {
2784          return (chr ($randno + 59)); // Lowercase
2785      }
2789 function cred_encrypt($input, $password) {
2791   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2792   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2794   return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2799 function cred_decrypt($input,$password) {
2800   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2801   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2803   return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2807 function get_object_info()
2809   return(session::get('objectinfo'));
2813 function set_object_info($str = "")
2815   session::set('objectinfo',$str);
2819 function isIpInNet($ip, $net, $mask) {
2820    // Move to long ints
2821    $ip= ip2long($ip);
2822    $net= ip2long($net);
2823    $mask= ip2long($mask);
2825    // Mask given IP with mask. If it returns "net", we're in...
2826    $res= $ip & $mask;
2828    return ($res == $net);
2832 function get_next_id($attrib, $dn)
2834   global $config;
2836   switch ($config->get_cfg_value("idAllocationMethod", "traditional")){
2837     case "pool":
2838       return get_next_id_pool($attrib);
2839     case "traditional":
2840       return get_next_id_traditional($attrib, $dn);
2841   }
2843   msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("unknown idAllocation method!"), ERROR_DIALOG);
2844   return null;
2848 function get_next_id_pool($attrib) {
2849   global $config;
2851   /* Fill informational values */
2852   $min= $config->get_cfg_value("${attrib}PoolMin", 10000);
2853   $max= $config->get_cfg_value("${attrib}PoolMax", 40000);
2855   /* Sanity check */
2856   if ($min >= $max) {
2857     msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." ".sprintf(_("%sPoolMin >= %sPoolMax!"), $attrib), ERROR_DIALOG);
2858     return null;
2859   }
2861   /* ID to skip */
2862   $ldap= $config->get_ldap_link();
2863   $id= null;
2865   /* Try to allocate the ID several times before failing */
2866   $tries= 3;
2867   while ($tries--) {
2869     /* Look for ID map entry */
2870     $ldap->cd ($config->current['BASE']);
2871     $ldap->search ("(&(objectClass=sambaUnixIdPool)($attrib=*))", array("$attrib"));
2873     /* If it does not exist, create one with these defaults */
2874     if ($ldap->count() == 0) {
2875       /* Fill informational values */
2876       $minUserId= $config->get_cfg_value("uidPoolMin", 10000);
2877       $minGroupId= $config->get_cfg_value("gidPoolMin", 10000);
2879       /* Add as default */
2880       $attrs= array("objectClass" => array("organizationalUnit", "sambaUnixIdPool"));
2881       $attrs["ou"]= "idmap";
2882       $attrs["uidNumber"]= $minUserId;
2883       $attrs["gidNumber"]= $minGroupId;
2884       $ldap->cd("ou=idmap,".$config->current['BASE']);
2885       $ldap->add($attrs);
2886       if ($ldap->error != "Success") {
2887         msg_dialog::display(_("Error"), _("Cannot create sambaUnixIdPool entry!"), ERROR_DIALOG);
2888         return null;
2889       }
2890       $tries++;
2891       continue;
2892     }
2893     /* Bail out if it's not unique */
2894     if ($ldap->count() != 1) {
2895       msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("sambaUnixIdPool is not unique!"), ERROR_DIALOG);
2896       return null;
2897     }
2899     /* Store old attrib and generate new */
2900     $attrs= $ldap->fetch();
2901     $dn= $ldap->getDN();
2902     $oldAttr= $attrs[$attrib][0];
2903     $newAttr= $oldAttr + 1;
2905     /* Sanity check */
2906     if ($newAttr >= $max) {
2907       msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("no ID available!"), ERROR_DIALOG);
2908       return null;
2909     }
2910     if ($newAttr < $min) {
2911       msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("no ID available!"), ERROR_DIALOG);
2912       return null;
2913     }
2915     #FIXME: PHP is not able to do a modification of "del: .../add: ...", so this
2916     #       is completely unsafe in the moment.
2917     #/* Remove old attr, add new attr */
2918     #$attrs= array($attrib => $oldAttr);
2919     #$ldap->rm($attrs, $dn);
2920     #if ($ldap->error != "Success") {
2921     #  continue;
2922     #}
2923     $ldap->cd($dn);
2924     $ldap->modify(array($attrib => $newAttr));
2925     if ($ldap->error != "Success") {
2926       msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." ".$ldap->get_error(), ERROR_DIALOG);
2927       return null;
2928     } else {
2929       return $newAttr;
2930     }
2931   }
2933   /* Bail out if we had problems getting the next id */
2934   if (!$tries) {
2935     msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("maximum tries exceeded!"), ERROR_DIALOG);
2936   }
2938   return $id;
2941 function get_next_id_traditional($attrib, $dn)
2943   global $config;
2945   $ids= array();
2946   $ldap= $config->get_ldap_link();
2948   $ldap->cd ($config->current['BASE']);
2949   if (preg_match('/gidNumber/i', $attrib)){
2950     $oc= "posixGroup";
2951   } else {
2952     $oc= "posixAccount";
2953   }
2954   $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
2956   /* Get list of ids */
2957   while ($attrs= $ldap->fetch()){
2958     $ids[]= (int)$attrs["$attrib"][0];
2959   }
2961   /* Add the nobody id */
2962   $ids[]= 65534;
2964   /* get the ranges */
2965   $tmp = array('0'=> 1000);
2966   if (preg_match('/posixAccount/', $oc) && $config->get_cfg_value("uidNumberBase") != ""){
2967     $tmp= split('-',$config->get_cfg_value("uidNumberBase"));
2968   } elseif($config->get_cfg_value("gidNumberBase") != ""){
2969     $tmp= split('-',$config->get_cfg_value("gidNumberBase"));
2970   }
2972   /* Set hwm to max if not set - for backward compatibility */
2973   $lwm= $tmp[0];
2974   if (isset($tmp[1])){
2975     $hwm= $tmp[1];
2976   } else {
2977     $hwm= pow(2,32);
2978   }
2979   /* Find out next free id near to UID_BASE */
2980   if ($config->get_cfg_value("baseIdHook") == ""){
2981     $base= $lwm;
2982   } else {
2983     /* Call base hook */
2984     $base= get_base_from_hook($dn, $attrib);
2985   }
2986   for ($id= $base; $id++; $id < pow(2,32)){
2987     if (!in_array($id, $ids)){
2988       return ($id);
2989     }
2990   }
2992   /* Should not happen */
2993   if ($id == $hwm){
2994     msg_dialog::display(_("Error"), _("Cannot allocate a free ID!"), ERROR_DIALOG);
2995     exit;
2996   }
3000 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
3001 ?>