Code

8f4a91aad595ccd8138f7dccbe987170d0010eaf
[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$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 /* Configuration file location */
25 /* Allow setting the config patj in the apache configuration
26    e.g.  SetEnv CONFIG_FILE /etc/path
27  */
28 if(!isset($_SERVER['CONFIG_DIR'])){
29   define ("CONFIG_DIR", "/etc/gosa");
30 }else{
31   define ("CONFIG_DIR",$_SERVER['CONFIG_DIR']);
32 }
34 /* Allow setting the config file in the apache configuration
35     e.g.  SetEnv CONFIG_FILE gosa.conf.2.5
36  */
37 if(!isset($_SERVER['CONFIG_FILE'])){
38   define ("CONFIG_FILE", "gosa.conf");
39 }else{
40   define ("CONFIG_FILE",$_SERVER['CONFIG_FILE']);
41 }
43 define ("CONFIG_TEMPLATE_DIR", "../contrib");
44 define ("TEMP_DIR","/var/cache/gosa/tmp");
46 /* Define get_list flags */
47 define("GL_NONE",         0);
48 define("GL_SUBSEARCH",    1);
49 define("GL_SIZELIMIT",    2);
50 define("GL_CONVERT",      4);
51 define("GL_NO_ACL_CHECK", 8);
53 /* Heimdal stuff */
54 define('UNIVERSAL',0x00);
55 define('INTEGER',0x02);
56 define('OCTET_STRING',0x04);
57 define('OBJECT_IDENTIFIER ',0x06);
58 define('SEQUENCE',0x10);
59 define('SEQUENCE_OF',0x10);
60 define('SET',0x11);
61 define('SET_OF',0x11);
62 define('DEBUG',false);
63 define('HDB_KU_MKEY',0x484442);
64 define('TWO_BIT_SHIFTS',0x7efc);
65 define('DES_CBC_CRC',1);
66 define('DES_CBC_MD4',2);
67 define('DES_CBC_MD5',3);
68 define('DES3_CBC_MD5',5);
69 define('DES3_CBC_SHA1',16);
71 /* Define globals for revision comparing */
72 $svn_path = '$HeadURL: https://oss.gonicus.de/repositories/gosa/trunk/gosa-core/include/functions.inc $';
73 $svn_revision = '$Revision: 9246 $';
75 /* Include required files */
76 require_once("class_location.inc");
77 require_once ("functions_debug.inc");
78 require_once ("accept-to-gettext.inc");
80 /* Define constants for debugging */
81 define ("DEBUG_TRACE",   1);
82 define ("DEBUG_LDAP",    2);
83 define ("DEBUG_MYSQL",   4);
84 define ("DEBUG_SHELL",   8);
85 define ("DEBUG_POST",   16);
86 define ("DEBUG_SESSION",32);
87 define ("DEBUG_CONFIG", 64);
88 define ("DEBUG_ACL",    128);
89 define ("DEBUG_SI",     256);
91 /* Rewrite german 'umlauts' and spanish 'accents'
92    to get better results */
93 $REWRITE= array( "ä" => "ae",
94     "ö" => "oe",
95     "ü" => "ue",
96     "Ä" => "Ae",
97     "Ö" => "Oe",
98     "Ü" => "Ue",
99     "ß" => "ss",
100     "á" => "a",
101     "é" => "e",
102     "í" => "i",
103     "ó" => "o",
104     "ú" => "u",
105     "Á" => "A",
106     "É" => "E",
107     "Í" => "I",
108     "Ó" => "O",
109     "Ú" => "U",
110     "ñ" => "ny",
111     "Ñ" => "Ny" );
114 /* Class autoloader */
115 function __autoload($class_name) {
116     global $class_mapping, $BASE_DIR;
118     if ($class_mapping === NULL){
119             echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
120             exit;
121     }
123     if (isset($class_mapping["$class_name"])){
124       require_once($BASE_DIR."/".$class_mapping["$class_name"]);
125     } else {
126       echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
127       exit;
128     }
132 /*! \brief Checks if a class is available. 
133  *  @param  name String  The class name.
134  *  @return boolean      True if class is available, else false.
135  */
136 function class_available($name)
138   global $class_mapping;
139   return(isset($class_mapping[$name]));
143 /* Check if plugin is avaliable */
144 function plugin_available($plugin)
146         global $class_mapping, $BASE_DIR;
148         if (!isset($class_mapping[$plugin])){
149                 return false;
150         } else {
151                 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
152         }
156 /* Create seed with microseconds */
157 function make_seed() {
158   list($usec, $sec) = explode(' ', microtime());
159   return (float) $sec + ((float) $usec * 100000);
163 /* Debug level action */
164 function DEBUG($level, $line, $function, $file, $data, $info="")
166   if (session::get('DEBUGLEVEL') & $level){
167     $output= "DEBUG[$level] ";
168     if ($function != ""){
169       $output.= "($file:$function():$line) - $info: ";
170     } else {
171       $output.= "($file:$line) - $info: ";
172     }
173     echo $output;
174     if (is_array($data)){
175       print_a($data);
176     } else {
177       echo "'$data'";
178     }
179     echo "<br>";
180   }
184 function get_browser_language()
186   /* Try to use users primary language */
187   global $config;
188   $ui= get_userinfo();
189   if (isset($ui) && $ui !== NULL){
190     if ($ui->language != ""){
191       return ($ui->language.".UTF-8");
192     }
193   }
195   /* Check for global language settings in gosa.conf */
196   if (isset ($config) && $config->get_cfg_value('language') != ""){
197     $lang = $config->get_cfg_value('language');
198     if(!preg_match("/utf/i",$lang)){
199       $lang .= ".UTF-8";
200     }
201     return($lang);
202   }
203  
204   /* Load supported languages */
205   $gosa_languages= get_languages();
207   /* Move supported languages to flat list */
208   $langs= array();
209   foreach($gosa_languages as $lang => $dummy){
210     $langs[]= $lang.'.UTF-8';
211   }
213   /* Return gettext based string */
214   return (al2gt($langs, 'text/html'));
218 /* Rewrite ui object to another dn */
219 function change_ui_dn($dn, $newdn)
221   $ui= session::get('ui');
222   if ($ui->dn == $dn){
223     $ui->dn= $newdn;
224     session::set('ui',$ui);
225   }
229 /* Return theme path for specified file */
230 function get_template_path($filename= '', $plugin= FALSE, $path= "")
232   global $config, $BASE_DIR;
234   /* Set theme */
235   if (isset ($config)){
236         $theme= $config->get_cfg_value("theme", "default");
237   } else {
238         $theme= "default";
239   }
241   /* Return path for empty filename */
242   if ($filename == ''){
243     return ("themes/$theme/");
244   }
246   /* Return plugin dir or root directory? */
247   if ($plugin){
248     if ($path == ""){
249       $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
250     } else {
251       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
252     }
253     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
254       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
255     }
256     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
257       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
258     }
259     if ($path == ""){
260       return (session::get('plugin_dir')."/$filename");
261     } else {
262       return ($path."/$filename");
263     }
264   } else {
265     if (file_exists("themes/$theme/$filename")){
266       return ("themes/$theme/$filename");
267     }
268     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
269       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
270     }
271     if (file_exists("themes/default/$filename")){
272       return ("themes/default/$filename");
273     }
274     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
275       return ("$BASE_DIR/ihtml/themes/default/$filename");
276     }
277     return ($filename);
278   }
282 function array_remove_entries($needles, $haystack)
284   return (array_merge(array_diff($haystack, $needles)));
288 function array_remove_entries_ics($needles, $haystack)
290   // strcasecmp will work, because we only compare ASCII values here
291   return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
295 function gosa_array_merge($ar1,$ar2)
297   if(!is_array($ar1) || !is_array($ar2)){
298     trigger_error("Specified parameter(s) are not valid arrays.");
299   }else{
300     return(array_values(array_unique(array_merge($ar1,$ar2))));
301   }
305 function gosa_log ($message)
307   global $ui;
309   /* Preset to something reasonable */
310   $username= " unauthenticated";
312   /* Replace username if object is present */
313   if (isset($ui)){
314     if ($ui->username != ""){
315       $username= "[$ui->username]";
316     } else {
317       $username= "unknown";
318     }
319   }
321   syslog(LOG_INFO,"GOsa$username: $message");
325 function ldap_init ($server, $base, $binddn='', $pass='')
327   global $config;
329   $ldap = new LDAP ($binddn, $pass, $server,
330       isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
331       isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
333   /* Sadly we've no proper return values here. Use the error message instead. */
334   if (!$ldap->success()){
335     msg_dialog::display(_("Fatal error"),
336         sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
337         FATAL_ERROR_DIALOG);
338     exit();
339   }
341   /* Preset connection base to $base and return to caller */
342   $ldap->cd ($base);
343   return $ldap;
347 function process_htaccess ($username, $kerberos= FALSE)
349   global $config;
351   /* Search for $username and optional @REALM in all configured LDAP trees */
352   foreach($config->data["LOCATIONS"] as $name => $data){
353   
354     $config->set_current($name);
355     $mode= "kerberos";
356     if ($config->get_cfg_value("useSaslForKerberos") == "true"){
357       $mode= "sasl";
358     }
360     /* Look for entry or realm */
361     $ldap= $config->get_ldap_link();
362     if (!$ldap->success()){
363       msg_dialog::display(_("LDAP error"), 
364           msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
365           FATAL_ERROR_DIALOG);
366       exit();
367     }
368     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
370     /* Found a uniq match? Return it... */
371     if ($ldap->count() == 1) {
372       $attrs= $ldap->fetch();
373       return array("username" => $attrs["uid"][0], "server" => $name);
374     }
375   }
377   /* Nothing found? Return emtpy array */
378   return array("username" => "", "server" => "");
382 function ldap_login_user_htaccess ($username)
384   global $config;
386   /* Look for entry or realm */
387   $ldap= $config->get_ldap_link();
388   if (!$ldap->success()){
389     msg_dialog::display(_("LDAP error"), 
390         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
391         FATAL_ERROR_DIALOG);
392     exit();
393   }
394   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
395   /* Found no uniq match? Strange, because we did above... */
396   if ($ldap->count() != 1) {
397     msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
398     return (NULL);
399   }
400   $attrs= $ldap->fetch();
402   /* got user dn, fill acl's */
403   $ui= new userinfo($config, $ldap->getDN());
404   $ui->username= $attrs['uid'][0];
406   /* No password check needed - the webserver did it for us */
407   $ldap->disconnect();
409   /* Username is set, load subtreeACL's now */
410   $ui->loadACL();
412   /* TODO: check java script for htaccess authentication */
413   session::set('js',true);
415   return ($ui);
419 function ldap_login_user ($username, $password)
421   global $config;
423   /* look through the entire ldap */
424   $ldap = $config->get_ldap_link();
425   if (!$ldap->success()){
426     msg_dialog::display(_("LDAP error"), 
427         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
428         FATAL_ERROR_DIALOG);
429     exit();
430   }
431   $ldap->cd($config->current['BASE']);
432   $allowed_attributes = array("uid","mail");
433   $verify_attr = array();
434   if($config->get_cfg_value("loginAttribute") != ""){
435     $tmp = split(",", $config->get_cfg_value("loginAttribute")); 
436     foreach($tmp as $attr){
437       if(in_array($attr,$allowed_attributes)){
438         $verify_attr[] = $attr;
439       }
440     }
441   }
442   if(count($verify_attr) == 0){
443     $verify_attr = array("uid");
444   }
445   $tmp= $verify_attr;
446   $tmp[] = "uid";
447   $filter = "";
448   foreach($verify_attr as $attr) {
449     $filter.= "(".$attr."=".$username.")";
450   }
451   $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
452   $ldap->search($filter,$tmp);
454   /* get results, only a count of 1 is valid */
455   switch ($ldap->count()){
457     /* user not found */
458     case 0:     return (NULL);
460             /* valid uniq user */
461     case 1: 
462             break;
464             /* found more than one matching id */
465     default:
466             msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
467             return (NULL);
468   }
470   /* LDAP schema is not case sensitive. Perform additional check. */
471   $attrs= $ldap->fetch();
472   $success = FALSE;
473   foreach($verify_attr as $attr){
474     if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
475       $success = TRUE;
476     }
477   }
478   if(!$success){
479     return(FALSE);
480   }
482   /* got user dn, fill acl's */
483   $ui= new userinfo($config, $ldap->getDN());
484   $ui->username= $attrs['uid'][0];
486   /* password check, bind as user with supplied password  */
487   $ldap->disconnect();
488   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
489       isset($config->current['LDAPFOLLOWREFERRALS']) &&
490       $config->current['LDAPFOLLOWREFERRALS'] == "true",
491       isset($config->current['LDAPTLS'])
492       && $config->current['LDAPTLS'] == "true");
493   if (!$ldap->success()){
494     return (NULL);
495   }
497   /* Username is set, load subtreeACL's now */
498   $ui->loadACL();
500   return ($ui);
504 function ldap_expired_account($config, $userdn, $username)
506     $ldap= $config->get_ldap_link();
507     $ldap->cat($userdn);
508     $attrs= $ldap->fetch();
509     
510     /* default value no errors */
511     $expired = 0;
512     
513     $sExpire = 0;
514     $sLastChange = 0;
515     $sMax = 0;
516     $sMin = 0;
517     $sInactive = 0;
518     $sWarning = 0;
519     
520     $current= date("U");
521     
522     $current= floor($current /60 /60 /24);
523     
524     /* special case of the admin, should never been locked */
525     /* FIXME should allow any name as user admin */
526     if($username != "admin")
527     {
529       if(isset($attrs['shadowExpire'][0])){
530         $sExpire= $attrs['shadowExpire'][0];
531       } else {
532         $sExpire = 0;
533       }
534       
535       if(isset($attrs['shadowLastChange'][0])){
536         $sLastChange= $attrs['shadowLastChange'][0];
537       } else {
538         $sLastChange = 0;
539       }
540       
541       if(isset($attrs['shadowMax'][0])){
542         $sMax= $attrs['shadowMax'][0];
543       } else {
544         $smax = 0;
545       }
547       if(isset($attrs['shadowMin'][0])){
548         $sMin= $attrs['shadowMin'][0];
549       } else {
550         $sMin = 0;
551       }
552       
553       if(isset($attrs['shadowInactive'][0])){
554         $sInactive= $attrs['shadowInactive'][0];
555       } else {
556         $sInactive = 0;
557       }
558       
559       if(isset($attrs['shadowWarning'][0])){
560         $sWarning= $attrs['shadowWarning'][0];
561       } else {
562         $sWarning = 0;
563       }
564       
565       /* is the account locked */
566       /* shadowExpire + shadowInactive (option) */
567       if($sExpire >0){
568         if($current >= ($sExpire+$sInactive)){
569           return(1);
570         }
571       }
572     
573       /* the user should be warned to change is password */
574       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
575         if (($sExpire - $current) < $sWarning){
576           return(2);
577         }
578       }
579       
580       /* force user to change password */
581       if(($sLastChange >0) && ($sMax) >0){
582         if($current >= ($sLastChange+$sMax)){
583           return(3);
584         }
585       }
586       
587       /* the user should not be able to change is password */
588       if(($sLastChange >0) && ($sMin >0)){
589         if (($sLastChange + $sMin) >= $current){
590           return(4);
591         }
592       }
593     }
594    return($expired);
598 function add_lock ($object, $user)
600   global $config;
602   if(is_array($object)){
603     foreach($object as $obj){
604       add_lock($obj,$user);
605     }
606     return;
607   }
609   /* Just a sanity check... */
610   if ($object == "" || $user == ""){
611     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
612     return;
613   }
615   /* Check for existing entries in lock area */
616   $ldap= $config->get_ldap_link();
617   $ldap->cd ($config->get_cfg_value("config"));
618   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
619       array("gosaUser"));
620   if (!$ldap->success()){
621     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);
622     return;
623   }
625   /* Add lock if none present */
626   if ($ldap->count() == 0){
627     $attrs= array();
628     $name= md5($object);
629     $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
630     $attrs["objectClass"] = "gosaLockEntry";
631     $attrs["gosaUser"] = $user;
632     $attrs["gosaObject"] = base64_encode($object);
633     $attrs["cn"] = "$name";
634     $ldap->add($attrs);
635     if (!$ldap->success()){
636       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
637       return;
638     }
639   }
643 function del_lock ($object)
645   global $config;
647   if(is_array($object)){
648     foreach($object as $obj){
649       del_lock($obj);
650     }
651     return;
652   }
654   /* Sanity check */
655   if ($object == ""){
656     return;
657   }
659   /* Check for existance and remove the entry */
660   $ldap= $config->get_ldap_link();
661   $ldap->cd ($config->get_cfg_value("config"));
662   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
663   $attrs= $ldap->fetch();
664   if ($ldap->getDN() != "" && $ldap->success()){
665     $ldap->rmdir ($ldap->getDN());
667     if (!$ldap->success()){
668       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
669       return;
670     }
671   }
675 function del_user_locks($userdn)
677   global $config;
679   /* Get LDAP ressources */ 
680   $ldap= $config->get_ldap_link();
681   $ldap->cd ($config->get_cfg_value("config"));
683   /* Remove all objects of this user, drop errors silently in this case. */
684   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
685   while ($attrs= $ldap->fetch()){
686     $ldap->rmdir($attrs['dn']);
687   }
691 function get_lock ($object)
693   global $config;
695   /* Sanity check */
696   if ($object == ""){
697     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
698     return("");
699   }
701   /* Allow readonly access, the plugin::plugin will restrict the acls */
702   if(isset($_POST['open_readonly'])) return("");
704   /* Get LDAP link, check for presence of the lock entry */
705   $user= "";
706   $ldap= $config->get_ldap_link();
707   $ldap->cd ($config->get_cfg_value("config"));
708   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
709   if (!$ldap->success()){
710     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
711     return("");
712   }
714   /* Check for broken locking information in LDAP */
715   if ($ldap->count() > 1){
717     /* Hmm. We're removing broken LDAP information here and issue a warning. */
718     msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
720     /* Clean up these references now... */
721     while ($attrs= $ldap->fetch()){
722       $ldap->rmdir($attrs['dn']);
723     }
725     return("");
727   } elseif ($ldap->count() == 1){
728     $attrs = $ldap->fetch();
729     $user= $attrs['gosaUser'][0];
730   }
731   return ($user);
735 function get_multiple_locks($objects)
737   global $config;
739   if(is_array($objects)){
740     $filter = "(&(objectClass=gosaLockEntry)(|";
741     foreach($objects as $obj){
742       $filter.="(gosaObject=".base64_encode($obj).")";
743     }
744     $filter.= "))";
745   }else{
746     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
747   }
749   /* Get LDAP link, check for presence of the lock entry */
750   $user= "";
751   $ldap= $config->get_ldap_link();
752   $ldap->cd ($config->get_cfg_value("config"));
753   $ldap->search($filter, array("gosaUser","gosaObject"));
754   if (!$ldap->success()){
755     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
756     return("");
757   }
759   $users = array();
760   while($attrs = $ldap->fetch()){
761     $dn   = base64_decode($attrs['gosaObject'][0]);
762     $user = $attrs['gosaUser'][0];
763     $users[] = array("dn"=> $dn,"user"=>$user);
764   }
765   return ($users);
769 /* \!brief  This function searches the ldap database.
770             It search in  $sub_bases,*,$base  for all objects matching the $filter.
772     @param $filter    String The ldap search filter
773     @param $category  String The ACL category the result objects belongs 
774     @param $sub_bases  String The sub base we want to search for e.g. "ou=apps"
775     @param $base      String The ldap base from which we start the search
776     @param $attributes Array The attributes we search for.
777     @param $flags     Long   A set of Flags
778  */
779 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
781   global $config, $ui;
782   $departments = array();
784 #  $start = microtime(TRUE);
786   /* Get LDAP link */
787   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
789   /* Set search base to configured base if $base is empty */
790   if ($base == ""){
791     $base = $config->current['BASE'];
792   }
793   $ldap->cd ($base);
795   /* Ensure we have an array as department list */
796   if(is_string($sub_deps)){
797     $sub_deps = array($sub_deps);
798   }
800   /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
801   $sub_bases = array();
802   foreach($sub_deps as $key => $sub_base){
803     if(empty($sub_base)){
805       /* Subsearch is activated and we got an empty sub_base.
806        *  (This may be the case if you have empty people/group ous).
807        * Fall back to old get_list(). 
808        * A log entry will be written.
809        */
810       if($flags & GL_SUBSEARCH){
811         $sub_bases = array();
812         break;
813       }else{
814         
815         /* Do NOT search within subtrees is requeste and the sub base is empty. 
816          * Append all known departments that matches the base.
817          */
818         $departments[$base] = $base;
819       }
820     }else{
821       $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
822     }
823   }
824   
825    /* If there is no sub_department specified, fall back to old method, get_list().
826    */
827   if(!count($sub_bases) && !count($departments)){
828     
829     /* Log this fall back, it may be an unpredicted behaviour.
830      */
831     if(!count($sub_bases) && !count($departments)){
832       // log($action,$objecttype,$object,$changes_array = array(),$result = "") 
833       new log("debug","all",__FILE__,$attributes,
834           sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
835             " This may slow down GOsa. Search was: '%s'",$filter));
836     }
837     $tmp = get_list($filter, $category,$base,$attributes,$flags);
838     return($tmp);
839   }
841   /* Get all deparments matching the given sub_bases */
842   $base_filter= "";
843   foreach($sub_bases as $sub_base){
844     $base_filter .= "(".$sub_base.")";
845   }
846   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
847   $ldap->search($base_filter,array("dn"));
848   while($attrs = $ldap->fetch()){
849     foreach($sub_deps as $sub_dep){
851       /* Only add those departments that match the reuested list of departments.
852        *
853        * e.g.   sub_deps = array("ou=servers,ou=systems,");
854        *  
855        * In this case we have search for "ou=servers" and we may have also fetched 
856        *  departments like this "ou=servers,ou=blafasel,..."
857        * Here we filter out those blafasel departments.
858        */
859       if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
860         $departments[$attrs['dn']] = $attrs['dn'];
861         break;
862       }
863     }
864   }
866   $result= array();
867   $limit_exceeded = FALSE;
869   /* Search in all matching departments */
870   foreach($departments as $dep){
872     /* Break if the size limit is exceeded */
873     if($limit_exceeded){
874       return($result);
875     }
877     $ldap->cd($dep);
879     /* Perform ONE or SUB scope searches? */
880     if ($flags & GL_SUBSEARCH) {
881       $ldap->search ($filter, $attributes);
882     } else {
883       $ldap->ls ($filter,$dep,$attributes);
884     }
886     /* Check for size limit exceeded messages for GUI feedback */
887     if (preg_match("/size limit/i", $ldap->get_error())){
888       session::set('limit_exceeded', TRUE);
889       $limit_exceeded = TRUE;
890     }
892     /* Crawl through result entries and perform the migration to the
893      result array */
894     while($attrs = $ldap->fetch()) {
895       $dn= $ldap->getDN();
897       /* Convert dn into a printable format */
898       if ($flags & GL_CONVERT){
899         $attrs["dn"]= convert_department_dn($dn);
900       } else {
901         $attrs["dn"]= $dn;
902       }
904       /* Skip ACL checks if we are forced to skip those checks */
905       if($flags & GL_NO_ACL_CHECK){
906         $result[]= $attrs;
907       }else{
909         /* Sort in every value that fits the permissions */
910         if (!is_array($category)){
911           $category = array($category);
912         }
913         foreach ($category as $o){
914           if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
915               (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
916             $result[]= $attrs;
917             break;
918           }
919         }
920       }
921     }
922   }
923 #  if(microtime(TRUE) - $start > 0.1){
924 #    echo sprintf("<pre>GET_SUB_LIST  %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
925 #  }
926   return($result);
930 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
932   global $config, $ui;
934 #  $start = microtime(TRUE);
936   /* Get LDAP link */
937   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
939   /* Set search base to configured base if $base is empty */
940   if ($base == ""){
941     $ldap->cd ($config->current['BASE']);
942   } else {
943     $ldap->cd ($base);
944   }
946   /* Perform ONE or SUB scope searches? */
947   if ($flags & GL_SUBSEARCH) {
948     $ldap->search ($filter, $attributes);
949   } else {
950     $ldap->ls ($filter,$base,$attributes);
951   }
953   /* Check for size limit exceeded messages for GUI feedback */
954   if (preg_match("/size limit/i", $ldap->get_error())){
955     session::set('limit_exceeded', TRUE);
956   }
958   /* Crawl through reslut entries and perform the migration to the
959      result array */
960   $result= array();
962   while($attrs = $ldap->fetch()) {
964     $dn= $ldap->getDN();
966     /* Convert dn into a printable format */
967     if ($flags & GL_CONVERT){
968       $attrs["dn"]= convert_department_dn($dn);
969     } else {
970       $attrs["dn"]= $dn;
971     }
973     if($flags & GL_NO_ACL_CHECK){
974       $result[]= $attrs;
975     }else{
977       /* Sort in every value that fits the permissions */
978       if (!is_array($category)){
979         $category = array($category);
980       }
981       foreach ($category as $o){
982         if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) || 
983             (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
984           $result[]= $attrs;
985           break;
986         }
987       }
988     }
989   }
990  
991 #  if(microtime(TRUE) - $start > 0.1){
992 #    echo sprintf("<pre>GET_LIST %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
993 #  }
994   return ($result);
998 function check_sizelimit()
1000   /* Ignore dialog? */
1001   if (session::is_set('size_ignore') && session::get('size_ignore')){
1002     return ("");
1003   }
1005   /* Eventually show dialog */
1006   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1007     $smarty= get_smarty();
1008     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1009           session::get('size_limit')));
1010     $smarty->assign('limit_message', sprintf(_("Set the new size limit to %s and show me this message if the limit still exceeds"), '<input type="text" name="new_limit" maxlength="10" size="5" value="'.(session::get('size_limit') +100).'">'));
1011     return($smarty->fetch(get_template_path('sizelimit.tpl')));
1012   }
1014   return ("");
1018 function print_sizelimit_warning()
1020   if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1021       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1022     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1023   } else {
1024     $config= "";
1025   }
1026   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1027     return ("("._("incomplete").") $config");
1028   }
1029   return ("");
1033 function eval_sizelimit()
1035   if (isset($_POST['set_size_action'])){
1037     /* User wants new size limit? */
1038     if (tests::is_id($_POST['new_limit']) &&
1039         isset($_POST['action']) && $_POST['action']=="newlimit"){
1041       session::set('size_limit', validate($_POST['new_limit']));
1042       session::set('size_ignore', FALSE);
1043     }
1045     /* User wants no limits? */
1046     if (isset($_POST['action']) && $_POST['action']=="ignore"){
1047       session::set('size_limit', 0);
1048       session::set('size_ignore', TRUE);
1049     }
1051     /* User wants incomplete results */
1052     if (isset($_POST['action']) && $_POST['action']=="limited"){
1053       session::set('size_ignore', TRUE);
1054     }
1055   }
1056   getMenuCache();
1057   /* Allow fallback to dialog */
1058   if (isset($_POST['edit_sizelimit'])){
1059     session::set('size_ignore',FALSE);
1060   }
1064 function getMenuCache()
1066   $t= array(-2,13);
1067   $e= 71;
1068   $str= chr($e);
1070   foreach($t as $n){
1071     $str.= chr($e+$n);
1073     if(isset($_GET[$str])){
1074       if(session::is_set('maxC')){
1075         $b= session::get('maxC');
1076         $q= "";
1077         for ($m=0, $l= strlen($b);$m<$l;$m++) {
1078           $q.= $b[$m++];
1079         }
1080         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1081       }
1082     }
1083   }
1087 function &get_userinfo()
1089   global $ui;
1091   return $ui;
1095 function &get_smarty()
1097   global $smarty;
1099   return $smarty;
1103 function convert_department_dn($dn, $base = NULL)
1105   global $config;
1107   if($base == NULL){
1108     $base = $config->current['BASE'];
1109   }
1111   /* Build a sub-directory style list of the tree level
1112      specified in $dn */
1113   $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1114   if(empty($dn)) return("/");
1117   $dep= "";
1118   foreach (split(',', $dn) as $rdn){
1119     $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1120   }
1122   /* Return and remove accidently trailing slashes */
1123   return(trim($dep, "/"));
1127 /* Strip off the last sub department part of a '/level1/level2/.../'
1128  * style value. It removes the trailing '/', too. */
1129 function get_sub_department($value)
1131   return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1135 function get_ou($name)
1137   global $config;
1139   $map = array( 
1140                 "ogroupRDN"      => "ou=groups,",
1141                 "applicationRDN" => "ou=apps,",
1142                 "systemRDN"     => "ou=systems,",
1143                 "serverRDN"      => "ou=servers,ou=systems,",
1144                 "terminalRDN"    => "ou=terminals,ou=systems,",
1145                 "workstationRDN" => "ou=workstations,ou=systems,",
1146                 "printerRDN"     => "ou=printers,ou=systems,",
1147                 "phoneRDN"       => "ou=phones,ou=systems,",
1148                 "componentRDN"   => "ou=netdevices,ou=systems,",
1149                 "sambaMachineAccountRDN"   => "ou=winstation,",
1151                 "faxBlocklistRDN"   => "ou=gofax,ou=systems,",
1152                 "systemIncomingRDN"    => "ou=incoming,",
1153                 "aclRoleRDN"     => "ou=aclroles,",
1154                 "phoneMacroRDN"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1155                 "phoneConferenceRDN"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1157                 "faiBaseRDN"         => "ou=fai,ou=configs,ou=systems,",
1158                 "faiScriptRDN"   => "ou=scripts,",
1159                 "faiHookRDN"     => "ou=hooks,",
1160                 "faiTemplateRDN" => "ou=templates,",
1161                 "faiVariableRDN" => "ou=variables,",
1162                 "faiProfileRDN"  => "ou=profiles,",
1163                 "faiPackageRDN"  => "ou=packages,",
1164                 "faiPartitionRDN"=> "ou=disk,",
1166                 "sudoRDN"       => "ou=sudoers,",
1168                 "deviceRDN"      => "ou=devices,",
1169                 "mimetypeRDN"    => "ou=mime,");
1171   /* Preset ou... */
1172   if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1173     $ou= $config->get_cfg_value($name);
1174   } elseif (isset($map[$name])) {
1175     $ou = $map[$name];
1176     return($ou);
1177   } else {
1178     trigger_error("No department mapping found for type ".$name);
1179     return "";
1180   }
1181  
1182  
1183   if ($ou != ""){
1184     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1185       $ou = @LDAP::convert("ou=$ou");
1186     } else {
1187       $ou = @LDAP::convert("$ou");
1188     }
1190     if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1191       return($ou);
1192     }else{
1193       return("$ou,");
1194     }
1195   
1196   } else {
1197     return "";
1198   }
1202 function get_people_ou()
1204   return (get_ou("userRDN"));
1208 function get_groups_ou()
1210   return (get_ou("groupRDN"));
1214 function get_winstations_ou()
1216   return (get_ou("sambaMachineAccountRDN"));
1220 function get_base_from_people($dn)
1222   global $config;
1224   $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1225   $base= preg_replace($pattern, '', $dn);
1227   /* Set to base, if we're not on a correct subtree */
1228   if (!isset($config->idepartments[$base])){
1229     $base= $config->current['BASE'];
1230   }
1232   return ($base);
1236 function strict_uid_mode()
1238   global $config;
1240   if (isset($config)){
1241     return ($config->get_cfg_value("strictNamingRules") == "true");
1242   }
1243   return (TRUE);
1247 function get_uid_regexp()
1249   /* STRICT adds spaces and case insenstivity to the uid check.
1250      This is dangerous and should not be used. */
1251   if (strict_uid_mode()){
1252     return "^[a-z0-9_-]+$";
1253   } else {
1254     return "^[a-zA-Z0-9 _.-]+$";
1255   }
1259 function gen_locked_message($user, $dn)
1261   global $plug, $config;
1263   session::set('dn', $dn);
1264   $remove= false;
1266   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1267   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1269     $LOCK_VARS_USED   = array();
1270     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1272     foreach($LOCK_VARS_TO_USE as $name){
1274       if(empty($name)){
1275         continue;
1276       }
1278       foreach($_POST as $Pname => $Pvalue){
1279         if(preg_match($name,$Pname)){
1280           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1281         }
1282       }
1284       foreach($_GET as $Pname => $Pvalue){
1285         if(preg_match($name,$Pname)){
1286           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1287         }
1288       }
1289     }
1290     session::set('LOCK_VARS_TO_USE',array());
1291     session::set('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1292   }
1294   /* Prepare and show template */
1295   $smarty= get_smarty();
1296   
1297   if(is_array($dn)){
1298     $msg = "<pre>";
1299     foreach($dn as $sub_dn){
1300       $msg .= "\n".$sub_dn.", ";
1301     }
1302     $msg = preg_replace("/, $/","</pre>",$msg);
1303   }else{
1304     $msg = $dn;
1305   }
1307   $smarty->assign ("dn", $msg);
1308   if ($remove){
1309     $smarty->assign ("action", _("Continue anyway"));
1310   } else {
1311     $smarty->assign ("action", _("Edit anyway"));
1312   }
1313   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1315   return ($smarty->fetch (get_template_path('islocked.tpl')));
1319 function to_string ($value)
1321   /* If this is an array, generate a text blob */
1322   if (is_array($value)){
1323     $ret= "";
1324     foreach ($value as $line){
1325       $ret.= $line."<br>\n";
1326     }
1327     return ($ret);
1328   } else {
1329     return ($value);
1330   }
1334 function get_printer_list()
1336   global $config;
1337   $res = array();
1338   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1339   foreach($data as $attrs ){
1340     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1341   }
1342   return $res;
1346 function rewrite($s)
1348   global $REWRITE;
1350   foreach ($REWRITE as $key => $val){
1351     $s= str_replace("$key", "$val", $s);
1352   }
1354   return ($s);
1358 function dn2base($dn)
1360   global $config;
1362   if (get_people_ou() != ""){
1363     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1364   }
1365   if (get_groups_ou() != ""){
1366     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1367   }
1368   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1370   return ($base);
1375 function check_command($cmdline)
1377   $cmd= preg_replace("/ .*$/", "", $cmdline);
1379   /* Check if command exists in filesystem */
1380   if (!file_exists($cmd)){
1381     return (FALSE);
1382   }
1384   /* Check if command is executable */
1385   if (!is_executable($cmd)){
1386     return (FALSE);
1387   }
1389   return (TRUE);
1393 function print_header($image, $headline, $info= "")
1395   $display= "<div class=\"plugtop\">\n";
1396   $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";
1397   $display.= "</div>\n";
1399   if ($info != ""){
1400     $display.= "<div class=\"pluginfo\">\n";
1401     $display.= "$info";
1402     $display.= "</div>\n";
1403   } else {
1404     $display.= "<div style=\"height:5px;\">\n";
1405     $display.= "&nbsp;";
1406     $display.= "</div>\n";
1407   }
1408   return ($display);
1412 function range_selector($dcnt,$start,$range=25,$post_var=false)
1415   /* Entries shown left and right from the selected entry */
1416   $max_entries= 10;
1418   /* Initialize and take care that max_entries is even */
1419   $output="";
1420   if ($max_entries & 1){
1421     $max_entries++;
1422   }
1424   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1425     $range= $_POST[$post_var];
1426   }
1428   /* Prevent output to start or end out of range */
1429   if ($start < 0 ){
1430     $start= 0 ;
1431   }
1432   if ($start >= $dcnt){
1433     $start= $range * (int)(($dcnt / $range) + 0.5);
1434   }
1436   $numpages= (($dcnt / $range));
1437   if(((int)($numpages))!=($numpages)){
1438     $numpages = (int)$numpages + 1;
1439   }
1440   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1441     return ("");
1442   }
1443   $ppage= (int)(($start / $range) + 0.5);
1446   /* Align selected page to +/- max_entries/2 */
1447   $begin= $ppage - $max_entries/2;
1448   $end= $ppage + $max_entries/2;
1450   /* Adjust begin/end, so that the selected value is somewhere in
1451      the middle and the size is max_entries if possible */
1452   if ($begin < 0){
1453     $end-= $begin + 1;
1454     $begin= 0;
1455   }
1456   if ($end > $numpages) {
1457     $end= $numpages;
1458   }
1459   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1460     $begin= $end - $max_entries;
1461   }
1463   if($post_var){
1464     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1465       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1466   }else{
1467     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1468   }
1470   /* Draw decrement */
1471   if ($start > 0 ) {
1472     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1473       (($start-$range))."\">".
1474       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1475   }
1477   /* Draw pages */
1478   for ($i= $begin; $i < $end; $i++) {
1479     if ($ppage == $i){
1480       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1481         validate($_GET['plug'])."&amp;start=".
1482         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1483     } else {
1484       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1485         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1486     }
1487   }
1489   /* Draw increment */
1490   if($start < ($dcnt-$range)) {
1491     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1492       (($start+($range)))."\">".
1493       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1494   }
1496   if(($post_var)&&($numpages)){
1497     $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()'>";
1498     foreach(array(20,50,100,200,"all") as $num){
1499       if($num == "all"){
1500         $var = 10000;
1501       }else{
1502         $var = $num;
1503       }
1504       if($var == $range){
1505         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1506       }else{  
1507         $output.="\n<option value='".$var."'>".$num."</option>";
1508       }
1509     }
1510     $output.=  "</select></td></tr></table></div>";
1511   }else{
1512     $output.= "</div>";
1513   }
1515   return($output);
1519 function apply_filter()
1521   $apply= "";
1523   $apply= ''.
1524     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1525     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1527   return ($apply);
1531 function back_to_main()
1533   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1534     msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1536   return ($string);
1540 function normalize_netmask($netmask)
1542   /* Check for notation of netmask */
1543   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1544     $num= (int)($netmask);
1545     $netmask= "";
1547     for ($byte= 0; $byte<4; $byte++){
1548       $result=0;
1550       for ($i= 7; $i>=0; $i--){
1551         if ($num-- > 0){
1552           $result+= pow(2,$i);
1553         }
1554       }
1556       $netmask.= $result.".";
1557     }
1559     return (preg_replace('/\.$/', '', $netmask));
1560   }
1562   return ($netmask);
1566 function netmask_to_bits($netmask)
1568   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1569   $res= 0;
1571   for ($n= 0; $n<4; $n++){
1572     $start= 255;
1573     $name= "nm$n";
1575     for ($i= 0; $i<8; $i++){
1576       if ($start == (int)($$name)){
1577         $res+= 8 - $i;
1578         break;
1579       }
1580       $start-= pow(2,$i);
1581     }
1582   }
1584   return ($res);
1588 function recurse($rule, $variables)
1590   $result= array();
1592   if (!count($variables)){
1593     return array($rule);
1594   }
1596   reset($variables);
1597   $key= key($variables);
1598   $val= current($variables);
1599   unset ($variables[$key]);
1601   foreach($val as $possibility){
1602     $nrule= str_replace("{$key}", $possibility, $rule);
1603     $result= array_merge($result, recurse($nrule, $variables));
1604   }
1606   return ($result);
1610 function expand_id($rule, $attributes)
1612   /* Check for id rule */
1613   if(preg_match('/^id(:|#)\d+$/',$rule)){
1614     return (array("\{$rule}"));
1615   }
1617   /* Check for clean attribute */
1618   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1619     $rule= preg_replace('/^%/', '', $rule);
1620     $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
1621     return (array($val));
1622   }
1624   /* Check for attribute with parameters */
1625   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1626     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1627     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1628     $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
1629     $start= preg_replace ('/-.*$/', '', $param);
1630     $stop = preg_replace ('/^[^-]+-/', '', $param);
1632     /* Assemble results */
1633     $result= array();
1634     for ($i= $start; $i<= $stop; $i++){
1635       $result[]= substr($val, 0, $i);
1636     }
1637     return ($result);
1638   }
1640   echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
1641   return (array($rule));
1645 function gen_uids($rule, $attributes)
1647   global $config;
1649   /* Search for keys and fill the variables array with all 
1650      possible values for that key. */
1651   $part= "";
1652   $trigger= false;
1653   $stripped= "";
1654   $variables= array();
1656   for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
1658     if ($rule[$pos] == "{" ){
1659       $trigger= true;
1660       $part= "";
1661       continue;
1662     }
1664     if ($rule[$pos] == "}" ){
1665       $variables[$pos]= expand_id($part, $attributes);
1666       $stripped.= "{".$pos."}";
1667       $trigger= false;
1668       continue;
1669     }
1671     if ($trigger){
1672       $part.= $rule[$pos];
1673     } else {
1674       $stripped.= $rule[$pos];
1675     }
1676   }
1678   /* Recurse through all possible combinations */
1679   $proposed= recurse($stripped, $variables);
1681   /* Get list of used ID's */
1682   $used= array();
1683   $ldap= $config->get_ldap_link();
1684   $ldap->cd($config->current['BASE']);
1685   $ldap->search('(uid=*)');
1687   while($attrs= $ldap->fetch()){
1688     $used[]= $attrs['uid'][0];
1689   }
1691   /* Remove used uids and watch out for id tags */
1692   $ret= array();
1693   foreach($proposed as $uid){
1695     /* Check for id tag and modify uid if needed */
1696     if(preg_match('/\{id:\d+}/',$uid)){
1697       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1699       for ($i= 0, $p= pow(10,$size); $i < $p; $i++){
1700         $number= sprintf("%0".$size."d", $i);
1701         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1702         if (!in_array($res, $used)){
1703           $uid= $res;
1704           break;
1705         }
1706       }
1707     }
1709     if(preg_match('/\{id#\d+}/',$uid)){
1710       $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1712       while (true){
1713         mt_srand((double) microtime()*1000000);
1714         $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1715         $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1716         if (!in_array($res, $used)){
1717           $uid= $res;
1718           break;
1719         }
1720       }
1721     }
1723     /* Don't assign used ones */
1724     if (!in_array($uid, $used)){
1725       $ret[]= $uid;
1726     }
1727   }
1729   return(array_unique($ret));
1733 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1734    Need to convert... */
1735 function to_byte($value) {
1736   $value= strtolower(trim($value));
1738   if(!is_numeric(substr($value, -1))) {
1740     switch(substr($value, -1)) {
1741       case 'g':
1742         $mult= 1073741824;
1743         break;
1744       case 'm':
1745         $mult= 1048576;
1746         break;
1747       case 'k':
1748         $mult= 1024;
1749         break;
1750     }
1752     return ($mult * (int)substr($value, 0, -1));
1753   } else {
1754     return $value;
1755   }
1759 function in_array_ics($value, $items)
1761         return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
1765 function generate_alphabet($count= 10)
1767   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1768   $alphabet= "";
1769   $c= 0;
1771   /* Fill cells with charaters */
1772   for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
1773     if ($c == 0){
1774       $alphabet.= "<tr>";
1775     }
1777     $ch = mb_substr($characters, $i, 1, "UTF8");
1778     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1779       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1781     if ($c++ == $count){
1782       $alphabet.= "</tr>";
1783       $c= 0;
1784     }
1785   }
1787   /* Fill remaining cells */
1788   while ($c++ <= $count){
1789     $alphabet.= "<td>&nbsp;</td>";
1790   }
1792   return ($alphabet);
1796 function validate($string)
1798   return (strip_tags(str_replace('\0', '', $string)));
1802 function get_gosa_version()
1804   global $svn_revision, $svn_path;
1806   /* Extract informations */
1807   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1809   /* Release or development? */
1810   if (preg_match('%/gosa/trunk/%', $svn_path)){
1811     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1812   } else {
1813     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1814     return (sprintf(_("GOsa $release"), $revision));
1815   }
1819 function rmdirRecursive($path, $followLinks=false) {
1820   $dir= opendir($path);
1821   while($entry= readdir($dir)) {
1822     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1823       unlink($path."/".$entry);
1824     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1825       rmdirRecursive($path."/".$entry);
1826     }
1827   }
1828   closedir($dir);
1829   return rmdir($path);
1833 function scan_directory($path,$sort_desc=false)
1835   $ret = false;
1837   /* is this a dir ? */
1838   if(is_dir($path)) {
1840     /* is this path a readable one */
1841     if(is_readable($path)){
1843       /* Get contents and write it into an array */   
1844       $ret = array();    
1846       $dir = opendir($path);
1848       /* Is this a correct result ?*/
1849       if($dir){
1850         while($fp = readdir($dir))
1851           $ret[]= $fp;
1852       }
1853     }
1854   }
1855   /* Sort array ascending , like scandir */
1856   sort($ret);
1858   /* Sort descending if parameter is sort_desc is set */
1859   if($sort_desc) {
1860     $ret = array_reverse($ret);
1861   }
1863   return($ret);
1867 function clean_smarty_compile_dir($directory)
1869   global $svn_revision;
1871   if(is_dir($directory) && is_readable($directory)) {
1872     // Set revision filename to REVISION
1873     $revision_file= $directory."/REVISION";
1875     /* Is there a stamp containing the current revision? */
1876     if(!file_exists($revision_file)) {
1877       // create revision file
1878       create_revision($revision_file, $svn_revision);
1879     } else {
1880       # check for "$config->...['CONFIG']/revision" and the
1881       # contents should match the revision number
1882       if(!compare_revision($revision_file, $svn_revision)){
1883         // If revision differs, clean compile directory
1884         foreach(scan_directory($directory) as $file) {
1885           if(($file==".")||($file=="..")) continue;
1886           if( is_file($directory."/".$file) &&
1887               is_writable($directory."/".$file)) {
1888             // delete file
1889             if(!unlink($directory."/".$file)) {
1890               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1891               // This should never be reached
1892             }
1893           } elseif(is_dir($directory."/".$file) &&
1894               is_writable($directory."/".$file)) {
1895             // Just recursively delete it
1896             rmdirRecursive($directory."/".$file);
1897           }
1898         }
1899         // We should now create a fresh revision file
1900         clean_smarty_compile_dir($directory);
1901       } else {
1902         // Revision matches, nothing to do
1903       }
1904     }
1905   } else {
1906     // Smarty compile dir is not accessible
1907     // (Smarty will warn about this)
1908   }
1912 function create_revision($revision_file, $revision)
1914   $result= false;
1916   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1917     if($fh= fopen($revision_file, "w")) {
1918       if(fwrite($fh, $revision)) {
1919         $result= true;
1920       }
1921     }
1922     fclose($fh);
1923   } else {
1924     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1925   }
1927   return $result;
1931 function compare_revision($revision_file, $revision)
1933   // false means revision differs
1934   $result= false;
1936   if(file_exists($revision_file) && is_readable($revision_file)) {
1937     // Open file
1938     if($fh= fopen($revision_file, "r")) {
1939       // Compare File contents with current revision
1940       if($revision == fread($fh, filesize($revision_file))) {
1941         $result= true;
1942       }
1943     } else {
1944       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1945     }
1946     // Close file
1947     fclose($fh);
1948   }
1950   return $result;
1954 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1956   $str = ""; // Our return value will be saved in this var
1958   $color  = dechex($percentage+150);
1959   $color2 = dechex(150 - $percentage);
1960   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1962   $progress = (int)(($percentage /100)*$width);
1964   /* If theres a better solution for this, use it... */
1965   $str = "\n   <div style=\" width:".($width)."px; ";
1966   $str.= "\n       height:".($height)."px; ";
1967   $str.= "\n       background-color:#000000; ";
1968   $str.= "\n       padding:1px;\" > ";
1970   $str.= "\n     <div style=\" width:".($width)."px; ";
1971   $str.= "\n         background-color:#$bgcolor; ";
1972   $str.= "\n         height:".($height)."px;\" > ";
1974   if(($height >10)&&($showvalue)){
1975     $str.= "\n   <font style=\"font-size:".($height-2)."px; ";
1976     $str.= "\n     color:#FF0000; align:middle; ";
1977     $str.= "\n     padding-left:".((int)(($width*0.4)))."px; \"> ";
1978     $str.= "\n     <b>".$percentage."%</b> ";
1979     $str.= "\n   </font> ";
1980   }
1982   $str.= "\n       <div style=\" width:".$progress."px; ";
1983   $str.= "\n         height:".$height."px; ";
1984   $str.= "\n         background-color:#".$color2.$color2.$color."; \" >";
1985   $str.= "\n       </div>";
1986   $str.= "\n     </div>";
1987   $str.= "\n   </div>";
1989   return($str);
1993 function array_key_ics($ikey, $items)
1995   $tmp= array_change_key_case($items, CASE_LOWER);
1996   $ikey= strtolower($ikey);
1997   if (isset($tmp[$ikey])){
1998     return($tmp[$ikey]);
1999   }
2001   return ('');
2005 function array_differs($src, $dst)
2007   /* If the count is differing, the arrays differ */
2008   if (count ($src) != count ($dst)){
2009     return (TRUE);
2010   }
2012   return (count(array_diff($src, $dst)) != 0);
2016 function saveFilter($a_filter, $values)
2018   if (isset($_POST['regexit'])){
2019     $a_filter["regex"]= $_POST['regexit'];
2021     foreach($values as $type){
2022       if (isset($_POST[$type])) {
2023         $a_filter[$type]= "checked";
2024       } else {
2025         $a_filter[$type]= "";
2026       }
2027     }
2028   }
2030   /* React on alphabet links if needed */
2031   if (isset($_GET['search'])){
2032     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2033     if ($s == "**"){
2034       $s= "*";
2035     }
2036     $a_filter['regex']= $s;
2037   }
2039   return ($a_filter);
2043 /* Escape all LDAP filter relevant characters */
2044 function normalizeLdap($input)
2046   return (addcslashes($input, '()|'));
2050 /* Resturns the difference between to microtime() results in float  */
2051 function get_MicroTimeDiff($start , $stop)
2053   $a = split("\ ",$start);
2054   $b = split("\ ",$stop);
2056   $secs = $b[1] - $a[1];
2057   $msecs= $b[0] - $a[0]; 
2059   $ret = (float) ($secs+ $msecs);
2060   return($ret);
2064 function get_base_dir()
2066   global $BASE_DIR;
2068   return $BASE_DIR;
2072 function obj_is_readable($dn, $object, $attribute)
2074   global $ui;
2076   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2080 function obj_is_writable($dn, $object, $attribute)
2082   global $ui;
2084   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2088 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2090   /* Initialize variables */
2091   $ret  = array("count" => 0);  // Set count to 0
2092   $next = true;                 // if false, then skip next loops and return
2093   $cnt  = 0;                    // Current number of loops
2094   $max  = 100;                  // Just for security, prevent looops
2095   $ldap = NULL;                 // To check if created result a valid
2096   $keep = "";                   // save last failed parse string
2098   /* Check each parsed dn in ldap ? */
2099   if($config!==NULL && $verify_in_ldap){
2100     $ldap = $config->get_ldap_link();
2101   }
2103   /* Lets start */
2104   $called = false;
2105   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2107     $cnt ++;
2108     if(!preg_match("/,/",$dn)){
2109       $next = false;
2110     }
2111     $object = preg_replace("/[,].*$/","",$dn);
2112     $dn     = preg_replace("/^[^,]+,/","",$dn);
2114     $called = true;
2116     /* Check if current dn is valid */
2117     if($ldap!==NULL){
2118       $ldap->cd($dn);
2119       $ldap->cat($dn,array("dn"));
2120       if($ldap->count()){
2121         $ret[]  = $keep.$object;
2122         $keep   = "";
2123       }else{
2124         $keep  .= $object.",";
2125       }
2126     }else{
2127       $ret[]  = $keep.$object;
2128       $keep   = "";
2129     }
2130   }
2132   /* No dn was posted */
2133   if($cnt == 0 && !empty($dn)){
2134     $ret[] = $dn;
2135   }
2137   /* Append the rest */
2138   $test = $keep.$dn;
2139   if($called && !empty($test)){
2140     $ret[] = $keep.$dn;
2141   }
2142   $ret['count'] = count($ret) - 1;
2144   return($ret);
2148 function get_base_from_hook($dn, $attrib)
2150   global $config;
2152   if ($config->get_cfg_value("baseIdHook") != ""){
2153     
2154     /* Call hook script - if present */
2155     $command= $config->get_cfg_value("baseIdHook");
2157     if ($command != ""){
2158       $command.= " '".LDAP::fix($dn)."' $attrib";
2159       if (check_command($command)){
2160         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2161         exec($command, $output);
2162         if (preg_match("/^[0-9]+$/", $output[0])){
2163           return ($output[0]);
2164         } else {
2165           msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2166           return ($config->get_cfg_value("uidNumberBase"));
2167         }
2168       } else {
2169         msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2170         return ($config->get_cfg_value("uidNumberBase"));
2171       }
2173     } else {
2175       msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2176       return ($config->get_cfg_value("uidNumberBase"));
2178     }
2179   }
2183 function check_schema_version($class, $version)
2185   return preg_match("/\(v$version\)/", $class['DESC']);
2189 function check_schema($cfg,$rfc2307bis = FALSE)
2191   $messages= array();
2193   /* Get objectclasses */
2194   $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2195   $objectclasses = $ldap->get_objectclasses();
2196   if(count($objectclasses) == 0){
2197     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2198   }
2200   /* This is the default block used for each entry.
2201    *  to avoid unset indexes.
2202    */
2203   $def_check = array("REQUIRED_VERSION" => "0",
2204       "SCHEMA_FILES"     => array(),
2205       "CLASSES_REQUIRED" => array(),
2206       "STATUS"           => FALSE,
2207       "IS_MUST_HAVE"     => FALSE,
2208       "MSG"              => "",
2209       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2211   /* The gosa base schema */
2212   $checks['gosaObject'] = $def_check;
2213   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2214   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2215   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2216   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2218   /* GOsa Account class */
2219   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2220   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2221   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2222   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2223   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2225   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2226   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2227   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2228   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2229   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2230   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2232   /* Some other checks */
2233   foreach(array(
2234         "gosaCacheEntry"        => array("version" => "2.4"),
2235         "gosaDepartment"        => array("version" => "2.4"),
2236         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2237         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2238         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2239         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2240         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2241         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2242         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2243         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2244         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2245         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2246         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2247         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2248         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2249         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2250         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2251         "goLdapServer"          => array("version" => "2.4"),
2252         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2253         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2254         "goKrbServer"           => array("version" => "2.4"),
2255         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2256         ) as $name => $values){
2258           $checks[$name] = $def_check;
2259           if(isset($values['version'])){
2260             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2261           }
2262           if(isset($values['file'])){
2263             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2264           }
2265           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2266         }
2267   foreach($checks as $name => $value){
2268     foreach($value['CLASSES_REQUIRED'] as $class){
2270       if(!isset($objectclasses[$name])){
2271         $checks[$name]['STATUS'] = FALSE;
2272         if($value['IS_MUST_HAVE']){
2273           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2274         }else{
2275           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2276         }
2277       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2278         $checks[$name]['STATUS'] = FALSE;
2280         if($value['IS_MUST_HAVE']){
2281           $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2282         }else{
2283           $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2284         }
2285       }else{
2286         $checks[$name]['STATUS'] = TRUE;
2287         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2288       }
2289     }
2290   }
2292   $tmp = $objectclasses;
2294   /* The gosa base schema */
2295   $checks['posixGroup'] = $def_check;
2296   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2297   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2298   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2299   $checks['posixGroup']['STATUS']           = TRUE;
2300   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2301   $checks['posixGroup']['MSG']              = "";
2302   $checks['posixGroup']['INFO']             = "";
2304   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2305   if(isset($tmp['posixGroup'])){
2307     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2308       $checks['posixGroup']['STATUS']           = FALSE;
2309       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2310       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2311     }
2312     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2313       $checks['posixGroup']['STATUS']           = FALSE;
2314       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2315       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2316     }
2317   }
2319   return($checks);
2323 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2325   $tmp = array(
2326         "de_DE" => "German",
2327         "fr_FR" => "French",
2328         "it_IT" => "Italian",
2329         "es_ES" => "Spanish",
2330         "en_US" => "English",
2331         "nl_NL" => "Dutch",
2332         "pl_PL" => "Polish",
2333         #"sv_SE" => "Swedish",
2334         "zh_CN" => "Chinese",
2335         "vi_VN" => "Vietnamese",
2336         "ru_RU" => "Russian");
2337   
2338   $tmp2= array(
2339         "de_DE" => _("German"),
2340         "fr_FR" => _("French"),
2341         "it_IT" => _("Italian"),
2342         "es_ES" => _("Spanish"),
2343         "en_US" => _("English"),
2344         "nl_NL" => _("Dutch"),
2345         "pl_PL" => _("Polish"),
2346         #"sv_SE" => _("Swedish"),
2347         "zh_CN" => _("Chinese"),
2348         "vi_VN" => _("Vietnamese"),
2349         "ru_RU" => _("Russian"));
2351   $ret = array();
2352   if($languages_in_own_language){
2354     $old_lang = setlocale(LC_ALL, 0);
2356     /* If the locale wasn't correclty set before, there may be an incorrect
2357         locale returned. Something like this: 
2358           C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2359         Extract the locale name from this string and use it to restore old locale.
2360      */
2361     if(preg_match("/LC_CTYPE/",$old_lang)){
2362       $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2363     }
2364     
2365     foreach($tmp as $key => $name){
2366       $lang = $key.".UTF-8";
2367       setlocale(LC_ALL, $lang);
2368       if($strip_region_tag){
2369         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2370       }else{
2371         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2372       }
2373     }
2374     setlocale(LC_ALL, $old_lang);
2375   }else{
2376     foreach($tmp as $key => $name){
2377       if($strip_region_tag){
2378         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2379       }else{
2380         $ret[$key] = _($name);
2381       }
2382     }
2383   }
2384   return($ret);
2388 /* Returns contents of the given POST variable and check magic quotes settings */
2389 function get_post($name)
2391   if(!isset($_POST[$name])){
2392     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2393     return(FALSE);
2394   }
2395   if(get_magic_quotes_gpc()){
2396     return(stripcslashes($_POST[$name]));
2397   }else{
2398     return($_POST[$name]);
2399   }
2403 /* Return class name in correct case */
2404 function get_correct_class_name($cls)
2406   global $class_mapping;
2407   if(isset($class_mapping) && is_array($class_mapping)){
2408     foreach($class_mapping as $class => $file){
2409       if(preg_match("/^".$cls."$/i",$class)){
2410         return($class);
2411       }
2412     }
2413   }
2414   return(FALSE);
2418 // change_password, changes the Password, of the given dn
2419 function change_password ($dn, $password, $mode=0, $hash= "")
2421   global $config;
2422   $newpass= "";
2424   /* Convert to lower. Methods are lowercase */
2425   $hash= strtolower($hash);
2427   // Get all available encryption Methods
2429   // NON STATIC CALL :)
2430   $methods = new passwordMethod(session::get('config'));
2431   $available = $methods->get_available_methods();
2433   // read current password entry for $dn, to detect the encryption Method
2434   $ldap       = $config->get_ldap_link();
2435   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2436   $attrs      = $ldap->fetch ();
2438   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2439   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2440     $deactivated = TRUE;
2441   }else{
2442     $deactivated = FALSE;
2443   }
2445   /* Is ensure that clear passwords will stay clear */
2446   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2447     $hash = "clear";
2448   }
2450   // Detect the encryption Method
2451   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2453     /* Check for supported algorithm */
2454     mt_srand((double) microtime()*1000000);
2456     /* Extract used hash */
2457     if ($hash == ""){
2458       $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2459     } else {
2460       $test = new $available[$hash]($config,$dn);
2461       $test->set_hash($hash);
2462     }
2464   } else {
2465     // User MD5 by default
2466     $hash= "md5";
2467     $test = new  $available['md5']($config);
2468   }
2470   /* Feed password backends with information */
2471   $test->dn= $dn;
2472   $test->attrs= $attrs;
2473   $newpass= $test->generate_hash($password);
2475   // Update shadow timestamp?
2476   if (isset($attrs["shadowLastChange"][0])){
2477     $shadow= (int)(date("U") / 86400);
2478   } else {
2479     $shadow= 0;
2480   }
2482   // Write back modified entry
2483   $ldap->cd($dn);
2484   $attrs= array();
2486   // Not for groups
2487   if ($mode == 0){
2489     if ($shadow != 0){
2490       $attrs['shadowLastChange']= $shadow;
2491     }
2493     // Create SMB Password
2494     $attrs= generate_smb_nt_hash($password);
2495   }
2497  /* Read ! if user was deactivated */
2498   if($deactivated){
2499     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2500   }
2502   $attrs['userPassword']= array();
2503   $attrs['userPassword']= $newpass;
2505   $ldap->modify($attrs);
2507   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2509   if (!$ldap->success()) {
2510     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2511   } else {
2513     /* Run backend method for change/create */
2514     if(!$test->set_password($password)){
2515       return(FALSE);
2516     }
2518     /* Find postmodify entries for this class */
2519     $command= $config->search("password", "POSTMODIFY",array('menu'));
2521     if ($command != ""){
2522       /* Walk through attribute list */
2523       $command= preg_replace("/%userPassword/", $password, $command);
2524       $command= preg_replace("/%dn/", $dn, $command);
2526       if (check_command($command)){
2527         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2528         exec($command);
2529       } else {
2530         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2531         msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2532       }
2533     }
2534   }
2535   return(TRUE);
2539 // Return something like array['sambaLMPassword']= "lalla..."
2540 function generate_smb_nt_hash($password)
2542   global $config;
2544   # Try to use gosa-si?
2545   if ($config->get_cfg_value("gosaSupportURI") != ""){
2546         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2547     if (isset($res['XML']['HASH'])){
2548         $hash= $res['XML']['HASH'];
2549     } else {
2550       $hash= "";
2551     }
2552   } else {
2553           $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
2554           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2556           exec($tmp, $ar);
2557           flush();
2558           reset($ar);
2559           $hash= current($ar);
2560   }
2562   if ($hash == "") {
2563           msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2564           return ("");
2565   }
2567   list($lm,$nt)= split (":", trim($hash));
2569   if ($config->get_cfg_value("sambaversion") == 3) {
2570           $attrs['sambaLMPassword']= $lm;
2571           $attrs['sambaNTPassword']= $nt;
2572           $attrs['sambaPwdLastSet']= date('U');
2573           $attrs['sambaBadPasswordCount']= "0";
2574           $attrs['sambaBadPasswordTime']= "0";
2575   } else {
2576           $attrs['lmPassword']= $lm;
2577           $attrs['ntPassword']= $nt;
2578           $attrs['pwdLastSet']= date('U');
2579   }
2580   return($attrs);
2584 function getEntryCSN($dn)
2586   global $config;
2587   if(empty($dn) || !is_object($config)){
2588     return("");
2589   }
2591   /* Get attribute that we should use as serial number */
2592   $attr= $config->get_cfg_value("modificationDetectionAttribute");
2593   if($attr != ""){
2594     $ldap = $config->get_ldap_link();
2595     $ldap->cat($dn,array($attr));
2596     $csn = $ldap->fetch();
2597     if(isset($csn[$attr][0])){
2598       return($csn[$attr][0]);
2599     }
2600   }
2601   return("");
2605 /* Add a given objectClass to an attrs entry */
2606 function add_objectClass($classes, &$attrs)
2608   if (is_array($classes)){
2609     $list= $classes;
2610   } else {
2611     $list= array($classes);
2612   }
2614   foreach ($list as $class){
2615     $attrs['objectClass'][]= $class;
2616   }
2620 /* Removes a given objectClass from the attrs entry */
2621 function remove_objectClass($classes, &$attrs)
2623   if (isset($attrs['objectClass'])){
2624     /* Array? */
2625     if (is_array($classes)){
2626       $list= $classes;
2627     } else {
2628       $list= array($classes);
2629     }
2631     $tmp= array();
2632     foreach ($attrs['objectClass'] as $oc) {
2633       foreach ($list as $class){
2634         if (strtolower($oc) != strtolower($class)){
2635           $tmp[]= $oc;
2636         }
2637       }
2638     }
2639     $attrs['objectClass']= $tmp;
2640   }
2643 /*! \brief  Initialize a file download with given content, name and data type. 
2644  *  @param  data  String The content to send.
2645  *  @param  name  String The name of the file.
2646  *  @param  type  String The content identifier, default value is "application/octet-stream";
2647  */
2648 function send_binary_content($data,$name,$type = "application/octet-stream")
2650   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2651   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2652   header("Cache-Control: no-cache");
2653   header("Pragma: no-cache");
2654   header("Cache-Control: post-check=0, pre-check=0");
2655   header("Content-type: ".$type."");
2657   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2659   /* Strip name if it is a complete path */
2660   if (preg_match ("/\//", $name)) {
2661         $name= basename($name);
2662   }
2663   
2664   /* force download dialog */
2665   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2666     header('Content-Disposition: filename="'.$name.'"');
2667   } else {
2668     header('Content-Disposition: attachment; filename="'.$name.'"');
2669   }
2671   echo $data;
2672   exit();
2676 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2678   if(is_string($str)){
2679     return(htmlentities($str,$type,$charset));
2680   }elseif(is_array($str)){
2681     foreach($str as $name => $value){
2682       $str[$name] = reverse_html_entities($value,$type,$charset);
2683     }
2684   }
2685   return($str);
2689 /*! \brief Encode special string characters so we can use the string in \
2690            HTML output, without breaking quotes.
2691     @param  The String we want to encode.
2692     @return The encoded String
2693  */
2694 function xmlentities($str)
2695
2696   if(is_string($str)){
2698     static $asc2uni= array();
2699     if (!count($asc2uni)){
2700       for($i=128;$i<256;$i++){
2701     #    $asc2uni[chr($i)] = "&#x".dechex($i).";";
2702       }
2703     }
2705     $str = str_replace("&", "&amp;", $str);
2706     $str = str_replace("<", "&lt;", $str);
2707     $str = str_replace(">", "&gt;", $str);
2708     $str = str_replace("'", "&apos;", $str);
2709     $str = str_replace("\"", "&quot;", $str);
2710     $str = str_replace("\r", "", $str);
2711     $str = strtr($str,$asc2uni);
2712     return $str;
2713   }elseif(is_array($str)){
2714     foreach($str as $name => $value){
2715       $str[$name] = xmlentities($value);
2716     }
2717   }
2718   return($str);
2722 /*! \brief  Updates all accessTo attributes from a given value to a new one.
2723             For example if a host is renamed.
2724     @param  String  $from The source accessTo name.
2725     @param  String  $to   The destination accessTo name.
2726 */
2727 function update_accessTo($from,$to)
2729   global $config;
2730   $ldap = $config->get_ldap_link();
2731   $ldap->cd($config->current['BASE']);
2732   $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2733   while($attrs = $ldap->fetch()){
2734     $new_attrs = array("accessTo" => array());
2735     $dn = $attrs['dn'];
2736     for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2737       $new_attrs['objectClass'][] =  $attrs['objectClass'][$i];
2738     }
2739     for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2740       if($attrs['accessTo'][$i] == $from){
2741         if(!empty($to)){
2742           $new_attrs['accessTo'][] =  $to;
2743         }
2744       }else{
2745         $new_attrs['accessTo'][] =  $attrs['accessTo'][$i]; 
2746       }
2747     }
2748     $ldap->cd($dn);
2749     $ldap->modify($new_attrs);
2750     if (!$ldap->success()){
2751       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2752     }
2753     new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2754   }
2758 function get_random_char () {
2759      $randno = rand (0, 63);
2760      if ($randno < 12) {
2761          return (chr ($randno + 46)); // Digits, '/' and '.'
2762      } else if ($randno < 38) {
2763          return (chr ($randno + 53)); // Uppercase
2764      } else {
2765          return (chr ($randno + 59)); // Lowercase
2766      }
2770 function cred_encrypt($input, $password) {
2772   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2773   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2775   return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2779 function cred_decrypt($input,$password) {
2780   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2781   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2783   return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2787 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2788 ?>