Code

Updated functions inc.
[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   $tmp= array();
286   /* Loop through entries to be removed */
287   foreach ($haystack as $entry){
288     if (!in_array($entry, $needles)){
289       $tmp[]= $entry;
290     }
291   }
293   return ($tmp);
297 function array_remove_entries_ics($needles, $haystack)
299   $tmp= array();
301   /* Loop through entries to be removed */
302   foreach ($haystack as $entry){
303     if (!in_array_ics($entry, $needles)){
304       $tmp[]= $entry;
305     }
306   }
308   return ($tmp);
312 function gosa_array_merge($ar1,$ar2)
314   if(!is_array($ar1) || !is_array($ar2)){
315     trigger_error("Specified parameter(s) are not valid arrays.");
316   }else{
317     return(array_values(array_unique(array_merge($ar1,$ar2))));
318   }
322 function gosa_log ($message)
324   global $ui;
326   /* Preset to something reasonable */
327   $username= " unauthenticated";
329   /* Replace username if object is present */
330   if (isset($ui)){
331     if ($ui->username != ""){
332       $username= "[$ui->username]";
333     } else {
334       $username= "unknown";
335     }
336   }
338   syslog(LOG_INFO,"GOsa$username: $message");
342 function ldap_init ($server, $base, $binddn='', $pass='')
344   global $config;
346   $ldap = new LDAP ($binddn, $pass, $server,
347       isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
348       isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
350   /* Sadly we've no proper return values here. Use the error message instead. */
351   if (!$ldap->success()){
352     msg_dialog::display(_("Fatal error"),
353         sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
354         FATAL_ERROR_DIALOG);
355     exit();
356   }
358   /* Preset connection base to $base and return to caller */
359   $ldap->cd ($base);
360   return $ldap;
364 function process_htaccess ($username, $kerberos= FALSE)
366   global $config;
368   /* Search for $username and optional @REALM in all configured LDAP trees */
369   foreach($config->data["LOCATIONS"] as $name => $data){
370   
371     $config->set_current($name);
372     $mode= "kerberos";
373     if ($config->get_cfg_value("useSaslForKerberos") == "true"){
374       $mode= "sasl";
375     }
377     /* Look for entry or realm */
378     $ldap= $config->get_ldap_link();
379     if (!$ldap->success()){
380       msg_dialog::display(_("LDAP error"), 
381           msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
382           FATAL_ERROR_DIALOG);
383       exit();
384     }
385     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
387     /* Found a uniq match? Return it... */
388     if ($ldap->count() == 1) {
389       $attrs= $ldap->fetch();
390       return array("username" => $attrs["uid"][0], "server" => $name);
391     }
392   }
394   /* Nothing found? Return emtpy array */
395   return array("username" => "", "server" => "");
399 function ldap_login_user_htaccess ($username)
401   global $config;
403   /* Look for entry or realm */
404   $ldap= $config->get_ldap_link();
405   if (!$ldap->success()){
406     msg_dialog::display(_("LDAP error"), 
407         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
408         FATAL_ERROR_DIALOG);
409     exit();
410   }
411   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
412   /* Found no uniq match? Strange, because we did above... */
413   if ($ldap->count() != 1) {
414     msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
415     return (NULL);
416   }
417   $attrs= $ldap->fetch();
419   /* got user dn, fill acl's */
420   $ui= new userinfo($config, $ldap->getDN());
421   $ui->username= $attrs['uid'][0];
423   /* No password check needed - the webserver did it for us */
424   $ldap->disconnect();
426   /* Username is set, load subtreeACL's now */
427   $ui->loadACL();
429   /* TODO: check java script for htaccess authentication */
430   session::set('js',true);
432   return ($ui);
436 function ldap_login_user ($username, $password)
438   global $config;
440   /* look through the entire ldap */
441   $ldap = $config->get_ldap_link();
442   if (!$ldap->success()){
443     msg_dialog::display(_("LDAP error"), 
444         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
445         FATAL_ERROR_DIALOG);
446     exit();
447   }
448   $ldap->cd($config->current['BASE']);
449   $allowed_attributes = array("uid","mail");
450   $verify_attr = array();
451   if($config->get_cfg_value("loginAttribute") != ""){
452     $tmp = split(",", $config->get_cfg_value("loginAttribute")); 
453     foreach($tmp as $attr){
454       if(in_array($attr,$allowed_attributes)){
455         $verify_attr[] = $attr;
456       }
457     }
458   }
459   if(count($verify_attr) == 0){
460     $verify_attr = array("uid");
461   }
462   $tmp= $verify_attr;
463   $tmp[] = "uid";
464   $filter = "";
465   foreach($verify_attr as $attr) {
466     $filter.= "(".$attr."=".$username.")";
467   }
468   $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
469   $ldap->search($filter,$tmp);
471   /* get results, only a count of 1 is valid */
472   switch ($ldap->count()){
474     /* user not found */
475     case 0:     return (NULL);
477             /* valid uniq user */
478     case 1: 
479             break;
481             /* found more than one matching id */
482     default:
483             msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
484             return (NULL);
485   }
487   /* LDAP schema is not case sensitive. Perform additional check. */
488   $attrs= $ldap->fetch();
489   $success = FALSE;
490   foreach($verify_attr as $attr){
491     if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
492       $success = TRUE;
493     }
494   }
495   if(!$success){
496     return(FALSE);
497   }
499   /* got user dn, fill acl's */
500   $ui= new userinfo($config, $ldap->getDN());
501   $ui->username= $attrs['uid'][0];
503   /* password check, bind as user with supplied password  */
504   $ldap->disconnect();
505   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
506       isset($config->current['LDAPFOLLOWREFERRALS']) &&
507       $config->current['LDAPFOLLOWREFERRALS'] == "true",
508       isset($config->current['LDAPTLS'])
509       && $config->current['LDAPTLS'] == "true");
510   if (!$ldap->success()){
511     return (NULL);
512   }
514   /* Username is set, load subtreeACL's now */
515   $ui->loadACL();
517   return ($ui);
521 function ldap_expired_account($config, $userdn, $username)
523     $ldap= $config->get_ldap_link();
524     $ldap->cat($userdn);
525     $attrs= $ldap->fetch();
526     
527     /* default value no errors */
528     $expired = 0;
529     
530     $sExpire = 0;
531     $sLastChange = 0;
532     $sMax = 0;
533     $sMin = 0;
534     $sInactive = 0;
535     $sWarning = 0;
536     
537     $current= date("U");
538     
539     $current= floor($current /60 /60 /24);
540     
541     /* special case of the admin, should never been locked */
542     /* FIXME should allow any name as user admin */
543     if($username != "admin")
544     {
546       if(isset($attrs['shadowExpire'][0])){
547         $sExpire= $attrs['shadowExpire'][0];
548       } else {
549         $sExpire = 0;
550       }
551       
552       if(isset($attrs['shadowLastChange'][0])){
553         $sLastChange= $attrs['shadowLastChange'][0];
554       } else {
555         $sLastChange = 0;
556       }
557       
558       if(isset($attrs['shadowMax'][0])){
559         $sMax= $attrs['shadowMax'][0];
560       } else {
561         $smax = 0;
562       }
564       if(isset($attrs['shadowMin'][0])){
565         $sMin= $attrs['shadowMin'][0];
566       } else {
567         $sMin = 0;
568       }
569       
570       if(isset($attrs['shadowInactive'][0])){
571         $sInactive= $attrs['shadowInactive'][0];
572       } else {
573         $sInactive = 0;
574       }
575       
576       if(isset($attrs['shadowWarning'][0])){
577         $sWarning= $attrs['shadowWarning'][0];
578       } else {
579         $sWarning = 0;
580       }
581       
582       /* is the account locked */
583       /* shadowExpire + shadowInactive (option) */
584       if($sExpire >0){
585         if($current >= ($sExpire+$sInactive)){
586           return(1);
587         }
588       }
589     
590       /* the user should be warned to change is password */
591       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
592         if (($sExpire - $current) < $sWarning){
593           return(2);
594         }
595       }
596       
597       /* force user to change password */
598       if(($sLastChange >0) && ($sMax) >0){
599         if($current >= ($sLastChange+$sMax)){
600           return(3);
601         }
602       }
603       
604       /* the user should not be able to change is password */
605       if(($sLastChange >0) && ($sMin >0)){
606         if (($sLastChange + $sMin) >= $current){
607           return(4);
608         }
609       }
610     }
611    return($expired);
615 function add_lock ($object, $user)
617   global $config;
619   if(is_array($object)){
620     foreach($object as $obj){
621       add_lock($obj,$user);
622     }
623     return;
624   }
626   /* Just a sanity check... */
627   if ($object == "" || $user == ""){
628     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
629     return;
630   }
632   /* Check for existing entries in lock area */
633   $ldap= $config->get_ldap_link();
634   $ldap->cd ($config->get_cfg_value("config"));
635   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
636       array("gosaUser"));
637   if (!$ldap->success()){
638     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);
639     return;
640   }
642   /* Add lock if none present */
643   if ($ldap->count() == 0){
644     $attrs= array();
645     $name= md5($object);
646     $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
647     $attrs["objectClass"] = "gosaLockEntry";
648     $attrs["gosaUser"] = $user;
649     $attrs["gosaObject"] = base64_encode($object);
650     $attrs["cn"] = "$name";
651     $ldap->add($attrs);
652     if (!$ldap->success()){
653       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
654       return;
655     }
656   }
660 function del_lock ($object)
662   global $config;
664   if(is_array($object)){
665     foreach($object as $obj){
666       del_lock($obj);
667     }
668     return;
669   }
671   /* Sanity check */
672   if ($object == ""){
673     return;
674   }
676   /* Check for existance and remove the entry */
677   $ldap= $config->get_ldap_link();
678   $ldap->cd ($config->get_cfg_value("config"));
679   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
680   $attrs= $ldap->fetch();
681   if ($ldap->getDN() != "" && $ldap->success()){
682     $ldap->rmdir ($ldap->getDN());
684     if (!$ldap->success()){
685       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
686       return;
687     }
688   }
692 function del_user_locks($userdn)
694   global $config;
696   /* Get LDAP ressources */ 
697   $ldap= $config->get_ldap_link();
698   $ldap->cd ($config->get_cfg_value("config"));
700   /* Remove all objects of this user, drop errors silently in this case. */
701   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
702   while ($attrs= $ldap->fetch()){
703     $ldap->rmdir($attrs['dn']);
704   }
708 function get_lock ($object)
710   global $config;
712   /* Sanity check */
713   if ($object == ""){
714     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
715     return("");
716   }
718   /* Get LDAP link, check for presence of the lock entry */
719   $user= "";
720   $ldap= $config->get_ldap_link();
721   $ldap->cd ($config->get_cfg_value("config"));
722   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
723   if (!$ldap->success()){
724     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
725     return("");
726   }
728   /* Check for broken locking information in LDAP */
729   if ($ldap->count() > 1){
731     /* Hmm. We're removing broken LDAP information here and issue a warning. */
732     msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
734     /* Clean up these references now... */
735     while ($attrs= $ldap->fetch()){
736       $ldap->rmdir($attrs['dn']);
737     }
739     return("");
741   } elseif ($ldap->count() == 1){
742     $attrs = $ldap->fetch();
743     $user= $attrs['gosaUser'][0];
744   }
745   return ($user);
749 function get_multiple_locks($objects)
751   global $config;
753   if(is_array($objects)){
754     $filter = "(&(objectClass=gosaLockEntry)(|";
755     foreach($objects as $obj){
756       $filter.="(gosaObject=".base64_encode($obj).")";
757     }
758     $filter.= "))";
759   }else{
760     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
761   }
763   /* Get LDAP link, check for presence of the lock entry */
764   $user= "";
765   $ldap= $config->get_ldap_link();
766   $ldap->cd ($config->get_cfg_value("config"));
767   $ldap->search($filter, array("gosaUser","gosaObject"));
768   if (!$ldap->success()){
769     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
770     return("");
771   }
773   $users = array();
774   while($attrs = $ldap->fetch()){
775     $dn   = base64_decode($attrs['gosaObject'][0]);
776     $user = $attrs['gosaUser'][0];
777     $users[] = array("dn"=> $dn,"user"=>$user);
778   }
779   return ($users);
783 /* \!brief  This function searches the ldap database.
784             It search in  $sub_bases,*,$base  for all objects matching the $filter.
786     @param $filter    String The ldap search filter
787     @param $category  String The ACL category the result objects belongs 
788     @param $sub_bases  String The sub base we want to search for e.g. "ou=apps"
789     @param $base      String The ldap base from which we start the search
790     @param $attributes Array The attributes we search for.
791     @param $flags     Long   A set of Flags
792  */
793 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
795   global $config, $ui;
796   $departments = array();
798 #  $start = microtime(TRUE);
800   /* Get LDAP link */
801   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
803   /* Set search base to configured base if $base is empty */
804   if ($base == ""){
805     $base = $config->current['BASE'];
806   }
807   $ldap->cd ($base);
809   /* Ensure we have an array as department list */
810   if(is_string($sub_deps)){
811     $sub_deps = array($sub_deps);
812   }
814   /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
815   $sub_bases = array();
816   foreach($sub_deps as $key => $sub_base){
817     if(empty($sub_base)){
819       /* Subsearch is activated and we got an empty sub_base.
820        *  (This may be the case if you have empty people/group ous).
821        * Fall back to old get_list(). 
822        * A log entry will be written.
823        */
824       if($flags & GL_SUBSEARCH){
825         $sub_bases = array();
826         break;
827       }else{
828         
829         /* Do NOT search within subtrees is requeste and the sub base is empty. 
830          * Append all known departments that matches the base.
831          */
832         $departments[$base] = $base;
833       }
834     }else{
835       $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
836     }
837   }
838   
839    /* If there is no sub_department specified, fall back to old method, get_list().
840    */
841   if(!count($sub_bases) && !count($departments)){
842     
843     /* Log this fall back, it may be an unpredicted behaviour.
844      */
845     if(!count($sub_bases) && !count($departments)){
846       // log($action,$objecttype,$object,$changes_array = array(),$result = "") 
847       new log("debug","all",__FILE__,$attributes,
848           sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
849             " This may slow down GOsa. Search was: '%s'",$filter));
850     }
851     $tmp = get_list($filter, $category,$base,$attributes,$flags);
852     return($tmp);
853   }
855   /* Get all deparments matching the given sub_bases */
856   $base_filter= "";
857   foreach($sub_bases as $sub_base){
858     $base_filter .= "(".$sub_base.")";
859   }
860   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
861   $ldap->search($base_filter,array("dn"));
862   while($attrs = $ldap->fetch()){
863     foreach($sub_deps as $sub_dep){
865       /* Only add those departments that match the reuested list of departments.
866        *
867        * e.g.   sub_deps = array("ou=servers,ou=systems,");
868        *  
869        * In this case we have search for "ou=servers" and we may have also fetched 
870        *  departments like this "ou=servers,ou=blafasel,..."
871        * Here we filter out those blafasel departments.
872        */
873       if(preg_match("/".normalizePreg($sub_dep)."/",$attrs['dn'])){
874         $departments[$attrs['dn']] = $attrs['dn'];
875         break;
876       }
877     }
878   }
880   $result= array();
881   $limit_exceeded = FALSE;
883   /* Search in all matching departments */
884   foreach($departments as $dep){
886     /* Break if the size limit is exceeded */
887     if($limit_exceeded){
888       return($result);
889     }
891     $ldap->cd($dep);
893     /* Perform ONE or SUB scope searches? */
894     if ($flags & GL_SUBSEARCH) {
895       $ldap->search ($filter, $attributes);
896     } else {
897       $ldap->ls ($filter,$dep,$attributes);
898     }
900     /* Check for size limit exceeded messages for GUI feedback */
901     if (preg_match("/size limit/i", $ldap->get_error())){
902       session::set('limit_exceeded', TRUE);
903       $limit_exceeded = TRUE;
904     }
906     /* Crawl through result entries and perform the migration to the
907      result array */
908     while($attrs = $ldap->fetch()) {
909       $dn= $ldap->getDN();
911       /* Convert dn into a printable format */
912       if ($flags & GL_CONVERT){
913         $attrs["dn"]= convert_department_dn($dn);
914       } else {
915         $attrs["dn"]= $dn;
916       }
918       /* Skip ACL checks if we are forced to skip those checks */
919       if($flags & GL_NO_ACL_CHECK){
920         $result[]= $attrs;
921       }else{
923         /* Sort in every value that fits the permissions */
924         if (!is_array($category)){
925           $category = array($category);
926         }
927         foreach ($category as $o){
928           if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
929               (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
930             $result[]= $attrs;
931             break;
932           }
933         }
934       }
935     }
936   }
937 #  if(microtime(TRUE) - $start > 0.1){
938 #    echo sprintf("<pre>GET_SUB_LIST  %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
939 #  }
940   return($result);
944 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
946   global $config, $ui;
948 #  $start = microtime(TRUE);
950   /* Get LDAP link */
951   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
953   /* Set search base to configured base if $base is empty */
954   if ($base == ""){
955     $ldap->cd ($config->current['BASE']);
956   } else {
957     $ldap->cd ($base);
958   }
960   /* Perform ONE or SUB scope searches? */
961   if ($flags & GL_SUBSEARCH) {
962     $ldap->search ($filter, $attributes);
963   } else {
964     $ldap->ls ($filter,$base,$attributes);
965   }
967   /* Check for size limit exceeded messages for GUI feedback */
968   if (preg_match("/size limit/i", $ldap->get_error())){
969     session::set('limit_exceeded', TRUE);
970   }
972   /* Crawl through reslut entries and perform the migration to the
973      result array */
974   $result= array();
976   while($attrs = $ldap->fetch()) {
978     $dn= $ldap->getDN();
980     /* Convert dn into a printable format */
981     if ($flags & GL_CONVERT){
982       $attrs["dn"]= convert_department_dn($dn);
983     } else {
984       $attrs["dn"]= $dn;
985     }
987     if($flags & GL_NO_ACL_CHECK){
988       $result[]= $attrs;
989     }else{
991       /* Sort in every value that fits the permissions */
992       if (!is_array($category)){
993         $category = array($category);
994       }
995       foreach ($category as $o){
996         if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) || 
997             (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
998           $result[]= $attrs;
999           break;
1000         }
1001       }
1002     }
1003   }
1004  
1005 #  if(microtime(TRUE) - $start > 0.1){
1006 #    echo sprintf("<pre>GET_LIST %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1007 #  }
1008   return ($result);
1012 function check_sizelimit()
1014   /* Ignore dialog? */
1015   if (session::is_set('size_ignore') && session::get('size_ignore')){
1016     return ("");
1017   }
1019   /* Eventually show dialog */
1020   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1021     $smarty= get_smarty();
1022     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1023           session::get('size_limit')));
1024     $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).'">'));
1025     return($smarty->fetch(get_template_path('sizelimit.tpl')));
1026   }
1028   return ("");
1032 function print_sizelimit_warning()
1034   if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1035       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1036     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1037   } else {
1038     $config= "";
1039   }
1040   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1041     return ("("._("incomplete").") $config");
1042   }
1043   return ("");
1047 function eval_sizelimit()
1049   if (isset($_POST['set_size_action'])){
1051     /* User wants new size limit? */
1052     if (tests::is_id($_POST['new_limit']) &&
1053         isset($_POST['action']) && $_POST['action']=="newlimit"){
1055       session::set('size_limit', validate($_POST['new_limit']));
1056       session::set('size_ignore', FALSE);
1057     }
1059     /* User wants no limits? */
1060     if (isset($_POST['action']) && $_POST['action']=="ignore"){
1061       session::set('size_limit', 0);
1062       session::set('size_ignore', TRUE);
1063     }
1065     /* User wants incomplete results */
1066     if (isset($_POST['action']) && $_POST['action']=="limited"){
1067       session::set('size_ignore', TRUE);
1068     }
1069   }
1070   getMenuCache();
1071   /* Allow fallback to dialog */
1072   if (isset($_POST['edit_sizelimit'])){
1073     session::set('size_ignore',FALSE);
1074   }
1078 function getMenuCache()
1080   $t= array(-2,13);
1081   $e= 71;
1082   $str= chr($e);
1084   foreach($t as $n){
1085     $str.= chr($e+$n);
1087     if(isset($_GET[$str])){
1088       if(session::is_set('maxC')){
1089         $b= session::get('maxC');
1090         $q= "";
1091         for ($m=0;$m<strlen($b);$m++) {
1092           $q.= $b[$m++];
1093         }
1094         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1095       }
1096     }
1097   }
1101 function &get_userinfo()
1103   global $ui;
1105   return $ui;
1109 function &get_smarty()
1111   global $smarty;
1113   return $smarty;
1117 function convert_department_dn($dn, $base = NULL)
1119   global $config;
1121   if($base == NULL){
1122     $base = $config->current['BASE'];
1123   }
1125   /* Build a sub-directory style list of the tree level
1126      specified in $dn */
1127   $dn = preg_replace("/".normalizePreg($base)."$/i","",$dn);
1128   if(empty($dn)) return("/");
1131   $dep= "";
1132   foreach (split(',', $dn) as $rdn){
1133     $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1134   }
1136   /* Return and remove accidently trailing slashes */
1137   return(trim($dep, "/"));
1141 /* Strip off the last sub department part of a '/level1/level2/.../'
1142  * style value. It removes the trailing '/', too. */
1143 function get_sub_department($value)
1145   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1149 function get_ou($name)
1151   global $config;
1153   $map = array( 
1154                 "ogroupou"      => "ou=groups,",
1155                 "applicationou" => "ou=apps,",
1156                 "systemsou"     => "ou=systems,",
1157                 "serverRDN"      => "ou=servers,ou=systems,",
1158                 "terminalRDN"    => "ou=terminals,ou=systems,",
1159                 "workstationou" => "ou=workstations,ou=systems,",
1160                 "printerou"     => "ou=printers,ou=systems,",
1161                 "phoneou"       => "ou=phones,ou=systems,",
1162                 "componentou"   => "ou=netdevices,ou=systems,",
1163                 "sambaMachineAccountRDN"   => "ou=winstation,",
1165                 "blocklistou"   => "ou=gofax,ou=systems,",
1166                 "incomingou"    => "ou=incoming,",
1167                 "aclroleou"     => "ou=aclroles,",
1168                 "macroou"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1169                 "conferenceou"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1171                 "faiou"         => "ou=fai,ou=configs,ou=systems,",
1172                 "faiscriptou"   => "ou=scripts,",
1173                 "faihookou"     => "ou=hooks,",
1174                 "faitemplateou" => "ou=templates,",
1175                 "faivariableou" => "ou=variables,",
1176                 "faiprofileou"  => "ou=profiles,",
1177                 "faipackageou"  => "ou=packages,",
1178                 "faipartitionou"=> "ou=disk,",
1180                 "deviceou"      => "ou=devices,",
1181                 "mimetypeou"    => "ou=mime,");
1183   /* Preset ou... */
1184   if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1185     $ou= $config->get_cfg_value($name);
1186   } elseif (isset($map[$name])) {
1187     $ou = $map[$name];
1188     return($ou);
1189   } else {
1190     trigger_error("No department mapping found for type ".$name);
1191     return "";
1192   }
1193  
1194  
1195   if ($ou != ""){
1196     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1197       $ou = @LDAP::convert("ou=$ou");
1198     } else {
1199       $ou = @LDAP::convert("$ou");
1200     }
1202     if(preg_match("/".normalizePreg($config->current['BASE'])."$/",$ou)){
1203       return($ou);
1204     }else{
1205       return("$ou,");
1206     }
1207   
1208   } else {
1209     return "";
1210   }
1214 function get_people_ou()
1216   return (get_ou("USERRDN"));
1220 function get_groups_ou()
1222   return (get_ou("GROUPRDN"));
1226 function get_winstations_ou()
1228   return (get_ou("SAMBAMACHINEACCOUNTRDN"));
1232 function get_base_from_people($dn)
1234   global $config;
1236   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1237   $base= preg_replace($pattern, '', $dn);
1239   /* Set to base, if we're not on a correct subtree */
1240   if (!isset($config->idepartments[$base])){
1241     $base= $config->current['BASE'];
1242   }
1244   return ($base);
1248 function strict_uid_mode()
1250   global $config;
1252   if (isset($config)){
1253     return ($config->get_cfg_value("strictNamingRules") == "true");
1254   }
1255   return (TRUE);
1259 function get_uid_regexp()
1261   /* STRICT adds spaces and case insenstivity to the uid check.
1262      This is dangerous and should not be used. */
1263   if (strict_uid_mode()){
1264     return "^[a-z0-9_-]+$";
1265   } else {
1266     return "^[a-zA-Z0-9 _.-]+$";
1267   }
1271 function gen_locked_message($user, $dn)
1273   global $plug, $config;
1275   session::set('dn', $dn);
1276   $remove= false;
1278   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1279   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1281     $LOCK_VARS_USED   = array();
1282     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1284     foreach($LOCK_VARS_TO_USE as $name){
1286       if(empty($name)){
1287         continue;
1288       }
1290       foreach($_POST as $Pname => $Pvalue){
1291         if(preg_match($name,$Pname)){
1292           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1293         }
1294       }
1296       foreach($_GET as $Pname => $Pvalue){
1297         if(preg_match($name,$Pname)){
1298           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1299         }
1300       }
1301     }
1302     session::set('LOCK_VARS_TO_USE',array());
1303     session::set('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1304   }
1306   /* Prepare and show template */
1307   $smarty= get_smarty();
1308   
1309   if(is_array($dn)){
1310     $msg = "<pre>";
1311     foreach($dn as $sub_dn){
1312       $msg .= "\n".$sub_dn.", ";
1313     }
1314     $msg = preg_replace("/, $/","</pre>",$msg);
1315   }else{
1316     $msg = $dn;
1317   }
1319   $smarty->assign ("dn", $msg);
1320   if ($remove){
1321     $smarty->assign ("action", _("Continue anyway"));
1322   } else {
1323     $smarty->assign ("action", _("Edit anyway"));
1324   }
1325   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1327   return ($smarty->fetch (get_template_path('islocked.tpl')));
1331 function to_string ($value)
1333   /* If this is an array, generate a text blob */
1334   if (is_array($value)){
1335     $ret= "";
1336     foreach ($value as $line){
1337       $ret.= $line."<br>\n";
1338     }
1339     return ($ret);
1340   } else {
1341     return ($value);
1342   }
1346 function get_printer_list()
1348   global $config;
1349   $res = array();
1350   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1351   foreach($data as $attrs ){
1352     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1353   }
1354   return $res;
1358 function rewrite($s)
1360   global $REWRITE;
1362   foreach ($REWRITE as $key => $val){
1363     $s= preg_replace("/$key/", "$val", $s);
1364   }
1366   return ($s);
1370 function dn2base($dn)
1372   global $config;
1374   if (get_people_ou() != ""){
1375     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1376   }
1377   if (get_groups_ou() != ""){
1378     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1379   }
1380   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1382   return ($base);
1387 function check_command($cmdline)
1389   $cmd= preg_replace("/ .*$/", "", $cmdline);
1391   /* Check if command exists in filesystem */
1392   if (!file_exists($cmd)){
1393     return (FALSE);
1394   }
1396   /* Check if command is executable */
1397   if (!is_executable($cmd)){
1398     return (FALSE);
1399   }
1401   return (TRUE);
1405 function print_header($image, $headline, $info= "")
1407   $display= "<div class=\"plugtop\">\n";
1408   $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";
1409   $display.= "</div>\n";
1411   if ($info != ""){
1412     $display.= "<div class=\"pluginfo\">\n";
1413     $display.= "$info";
1414     $display.= "</div>\n";
1415   } else {
1416     $display.= "<div style=\"height:5px;\">\n";
1417     $display.= "&nbsp;";
1418     $display.= "</div>\n";
1419   }
1420   return ($display);
1424 function range_selector($dcnt,$start,$range=25,$post_var=false)
1427   /* Entries shown left and right from the selected entry */
1428   $max_entries= 10;
1430   /* Initialize and take care that max_entries is even */
1431   $output="";
1432   if ($max_entries & 1){
1433     $max_entries++;
1434   }
1436   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1437     $range= $_POST[$post_var];
1438   }
1440   /* Prevent output to start or end out of range */
1441   if ($start < 0 ){
1442     $start= 0 ;
1443   }
1444   if ($start >= $dcnt){
1445     $start= $range * (int)(($dcnt / $range) + 0.5);
1446   }
1448   $numpages= (($dcnt / $range));
1449   if(((int)($numpages))!=($numpages)){
1450     $numpages = (int)$numpages + 1;
1451   }
1452   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1453     return ("");
1454   }
1455   $ppage= (int)(($start / $range) + 0.5);
1458   /* Align selected page to +/- max_entries/2 */
1459   $begin= $ppage - $max_entries/2;
1460   $end= $ppage + $max_entries/2;
1462   /* Adjust begin/end, so that the selected value is somewhere in
1463      the middle and the size is max_entries if possible */
1464   if ($begin < 0){
1465     $end-= $begin + 1;
1466     $begin= 0;
1467   }
1468   if ($end > $numpages) {
1469     $end= $numpages;
1470   }
1471   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1472     $begin= $end - $max_entries;
1473   }
1475   if($post_var){
1476     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1477       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1478   }else{
1479     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1480   }
1482   /* Draw decrement */
1483   if ($start > 0 ) {
1484     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1485       (($start-$range))."\">".
1486       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1487   }
1489   /* Draw pages */
1490   for ($i= $begin; $i < $end; $i++) {
1491     if ($ppage == $i){
1492       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1493         validate($_GET['plug'])."&amp;start=".
1494         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1495     } else {
1496       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1497         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1498     }
1499   }
1501   /* Draw increment */
1502   if($start < ($dcnt-$range)) {
1503     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1504       (($start+($range)))."\">".
1505       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1506   }
1508   if(($post_var)&&($numpages)){
1509     $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()'>";
1510     foreach(array(20,50,100,200,"all") as $num){
1511       if($num == "all"){
1512         $var = 10000;
1513       }else{
1514         $var = $num;
1515       }
1516       if($var == $range){
1517         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1518       }else{  
1519         $output.="\n<option value='".$var."'>".$num."</option>";
1520       }
1521     }
1522     $output.=  "</select></td></tr></table></div>";
1523   }else{
1524     $output.= "</div>";
1525   }
1527   return($output);
1531 function apply_filter()
1533   $apply= "";
1535   $apply= ''.
1536     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1537     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1539   return ($apply);
1543 function back_to_main()
1545   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1546     msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1548   return ($string);
1552 function normalize_netmask($netmask)
1554   /* Check for notation of netmask */
1555   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1556     $num= (int)($netmask);
1557     $netmask= "";
1559     for ($byte= 0; $byte<4; $byte++){
1560       $result=0;
1562       for ($i= 7; $i>=0; $i--){
1563         if ($num-- > 0){
1564           $result+= pow(2,$i);
1565         }
1566       }
1568       $netmask.= $result.".";
1569     }
1571     return (preg_replace('/\.$/', '', $netmask));
1572   }
1574   return ($netmask);
1578 function netmask_to_bits($netmask)
1580   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1581   $res= 0;
1583   for ($n= 0; $n<4; $n++){
1584     $start= 255;
1585     $name= "nm$n";
1587     for ($i= 0; $i<8; $i++){
1588       if ($start == (int)($$name)){
1589         $res+= 8 - $i;
1590         break;
1591       }
1592       $start-= pow(2,$i);
1593     }
1594   }
1596   return ($res);
1600 function recurse($rule, $variables)
1602   $result= array();
1604   if (!count($variables)){
1605     return array($rule);
1606   }
1608   reset($variables);
1609   $key= key($variables);
1610   $val= current($variables);
1611   unset ($variables[$key]);
1613   foreach($val as $possibility){
1614     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1615     $result= array_merge($result, recurse($nrule, $variables));
1616   }
1618   return ($result);
1622 function expand_id($rule, $attributes)
1624   /* Check for id rule */
1625   if(preg_match('/^id(:|#)\d+$/',$rule)){
1626     return (array("\{$rule}"));
1627   }
1629   /* Check for clean attribute */
1630   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1631     $rule= preg_replace('/^%/', '', $rule);
1632     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1633     return (array($val));
1634   }
1636   /* Check for attribute with parameters */
1637   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1638     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1639     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1640     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1641     $start= preg_replace ('/-.*$/', '', $param);
1642     $stop = preg_replace ('/^[^-]+-/', '', $param);
1644     /* Assemble results */
1645     $result= array();
1646     for ($i= $start; $i<= $stop; $i++){
1647       $result[]= substr($val, 0, $i);
1648     }
1649     return ($result);
1650   }
1652   echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
1653   return (array($rule));
1657 function gen_uids($rule, $attributes)
1659   global $config;
1661   /* Search for keys and fill the variables array with all 
1662      possible values for that key. */
1663   $part= "";
1664   $trigger= false;
1665   $stripped= "";
1666   $variables= array();
1668   for ($pos= 0; $pos < strlen($rule); $pos++){
1670     if ($rule[$pos] == "{" ){
1671       $trigger= true;
1672       $part= "";
1673       continue;
1674     }
1676     if ($rule[$pos] == "}" ){
1677       $variables[$pos]= expand_id($part, $attributes);
1678       $stripped.= "{".$pos."}";
1679       $trigger= false;
1680       continue;
1681     }
1683     if ($trigger){
1684       $part.= $rule[$pos];
1685     } else {
1686       $stripped.= $rule[$pos];
1687     }
1688   }
1690   /* Recurse through all possible combinations */
1691   $proposed= recurse($stripped, $variables);
1693   /* Get list of used ID's */
1694   $used= array();
1695   $ldap= $config->get_ldap_link();
1696   $ldap->cd($config->current['BASE']);
1697   $ldap->search('(uid=*)');
1699   while($attrs= $ldap->fetch()){
1700     $used[]= $attrs['uid'][0];
1701   }
1703   /* Remove used uids and watch out for id tags */
1704   $ret= array();
1705   foreach($proposed as $uid){
1707     /* Check for id tag and modify uid if needed */
1708     if(preg_match('/\{id:\d+}/',$uid)){
1709       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1711       for ($i= 0; $i < pow(10,$size); $i++){
1712         $number= sprintf("%0".$size."d", $i);
1713         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1714         if (!in_array($res, $used)){
1715           $uid= $res;
1716           break;
1717         }
1718       }
1719     }
1721   if(preg_match('/\{id#\d+}/',$uid)){
1722     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1724     while (true){
1725       mt_srand((double) microtime()*1000000);
1726       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1727       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1728       if (!in_array($res, $used)){
1729         $uid= $res;
1730         break;
1731       }
1732     }
1733   }
1735 /* Don't assign used ones */
1736 if (!in_array($uid, $used)){
1737   $ret[]= $uid;
1741 return(array_unique($ret));
1745 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1746    Need to convert... */
1747 function to_byte($value) {
1748   $value= strtolower(trim($value));
1750   if(!is_numeric(substr($value, -1))) {
1752     switch(substr($value, -1)) {
1753       case 'g':
1754         $mult= 1073741824;
1755         break;
1756       case 'm':
1757         $mult= 1048576;
1758         break;
1759       case 'k':
1760         $mult= 1024;
1761         break;
1762     }
1764     return ($mult * (int)substr($value, 0, -1));
1765   } else {
1766     return $value;
1767   }
1771 function in_array_ics($value, $items)
1773   if (!is_array($items)){
1774     return (FALSE);
1775   }
1777   foreach ($items as $item){
1778     if (strcasecmp($item, $value) == 0) {
1779       return (TRUE);
1780     }
1781   }
1783   return (FALSE);
1784
1787 function generate_alphabet($count= 10)
1789   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1790   $alphabet= "";
1791   $c= 0;
1793   /* Fill cells with charaters */
1794   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1795     if ($c == 0){
1796       $alphabet.= "<tr>";
1797     }
1799     $ch = mb_substr($characters, $i, 1, "UTF8");
1800     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1801       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1803     if ($c++ == $count){
1804       $alphabet.= "</tr>";
1805       $c= 0;
1806     }
1807   }
1809   /* Fill remaining cells */
1810   while ($c++ <= $count){
1811     $alphabet.= "<td>&nbsp;</td>";
1812   }
1814   return ($alphabet);
1818 function validate($string)
1820   return (strip_tags(preg_replace('/\0/', '', $string)));
1824 function get_gosa_version()
1826   global $svn_revision, $svn_path;
1828   /* Extract informations */
1829   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1831   /* Release or development? */
1832   if (preg_match('%/gosa/trunk/%', $svn_path)){
1833     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1834   } else {
1835     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1836     return (sprintf(_("GOsa $release"), $revision));
1837   }
1841 function rmdirRecursive($path, $followLinks=false) {
1842   $dir= opendir($path);
1843   while($entry= readdir($dir)) {
1844     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1845       unlink($path."/".$entry);
1846     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1847       rmdirRecursive($path."/".$entry);
1848     }
1849   }
1850   closedir($dir);
1851   return rmdir($path);
1855 function scan_directory($path,$sort_desc=false)
1857   $ret = false;
1859   /* is this a dir ? */
1860   if(is_dir($path)) {
1862     /* is this path a readable one */
1863     if(is_readable($path)){
1865       /* Get contents and write it into an array */   
1866       $ret = array();    
1868       $dir = opendir($path);
1870       /* Is this a correct result ?*/
1871       if($dir){
1872         while($fp = readdir($dir))
1873           $ret[]= $fp;
1874       }
1875     }
1876   }
1877   /* Sort array ascending , like scandir */
1878   sort($ret);
1880   /* Sort descending if parameter is sort_desc is set */
1881   if($sort_desc) {
1882     $ret = array_reverse($ret);
1883   }
1885   return($ret);
1889 function clean_smarty_compile_dir($directory)
1891   global $svn_revision;
1893   if(is_dir($directory) && is_readable($directory)) {
1894     // Set revision filename to REVISION
1895     $revision_file= $directory."/REVISION";
1897     /* Is there a stamp containing the current revision? */
1898     if(!file_exists($revision_file)) {
1899       // create revision file
1900       create_revision($revision_file, $svn_revision);
1901     } else {
1902       # check for "$config->...['CONFIG']/revision" and the
1903       # contents should match the revision number
1904       if(!compare_revision($revision_file, $svn_revision)){
1905         // If revision differs, clean compile directory
1906         foreach(scan_directory($directory) as $file) {
1907           if(($file==".")||($file=="..")) continue;
1908           if( is_file($directory."/".$file) &&
1909               is_writable($directory."/".$file)) {
1910             // delete file
1911             if(!unlink($directory."/".$file)) {
1912               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1913               // This should never be reached
1914             }
1915           } elseif(is_dir($directory."/".$file) &&
1916               is_writable($directory."/".$file)) {
1917             // Just recursively delete it
1918             rmdirRecursive($directory."/".$file);
1919           }
1920         }
1921         // We should now create a fresh revision file
1922         clean_smarty_compile_dir($directory);
1923       } else {
1924         // Revision matches, nothing to do
1925       }
1926     }
1927   } else {
1928     // Smarty compile dir is not accessible
1929     // (Smarty will warn about this)
1930   }
1934 function create_revision($revision_file, $revision)
1936   $result= false;
1938   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1939     if($fh= fopen($revision_file, "w")) {
1940       if(fwrite($fh, $revision)) {
1941         $result= true;
1942       }
1943     }
1944     fclose($fh);
1945   } else {
1946     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1947   }
1949   return $result;
1953 function compare_revision($revision_file, $revision)
1955   // false means revision differs
1956   $result= false;
1958   if(file_exists($revision_file) && is_readable($revision_file)) {
1959     // Open file
1960     if($fh= fopen($revision_file, "r")) {
1961       // Compare File contents with current revision
1962       if($revision == fread($fh, filesize($revision_file))) {
1963         $result= true;
1964       }
1965     } else {
1966       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1967     }
1968     // Close file
1969     fclose($fh);
1970   }
1972   return $result;
1976 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1978   $str = ""; // Our return value will be saved in this var
1980   $color  = dechex($percentage+150);
1981   $color2 = dechex(150 - $percentage);
1982   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1984   $progress = (int)(($percentage /100)*$width);
1986   /* If theres a better solution for this, use it... */
1987   $str = "\n   <div style=\" width:".($width)."px; ";
1988   $str.= "\n       height:".($height)."px; ";
1989   $str.= "\n       background-color:#000000; ";
1990   $str.= "\n       padding:1px;\" > ";
1992   $str.= "\n     <div style=\" width:".($width)."px; ";
1993   $str.= "\n         background-color:#$bgcolor; ";
1994   $str.= "\n         height:".($height)."px;\" > ";
1996   if(($height >10)&&($showvalue)){
1997     $str.= "\n   <font style=\"font-size:".($height-2)."px; ";
1998     $str.= "\n     color:#FF0000; align:middle; ";
1999     $str.= "\n     padding-left:".((int)(($width*0.4)))."px; \"> ";
2000     $str.= "\n     <b>".$percentage."%</b> ";
2001     $str.= "\n   </font> ";
2002   }
2004   $str.= "\n       <div style=\" width:".$progress."px; ";
2005   $str.= "\n         height:".$height."px; ";
2006   $str.= "\n         background-color:#".$color2.$color2.$color."; \" >";
2007   $str.= "\n       </div>";
2008   $str.= "\n     </div>";
2009   $str.= "\n   </div>";
2011   return($str);
2015 function array_key_ics($ikey, $items)
2017   /* Gather keys, make them lowercase */
2018   $tmp= array();
2019   foreach ($items as $key => $value){
2020     $tmp[strtolower($key)]= $key;
2021   }
2023   if (isset($tmp[strtolower($ikey)])){
2024     return($tmp[strtolower($ikey)]);
2025   }
2027   return ("");
2031 function array_differs($src, $dst)
2033   /* If the count is differing, the arrays differ */
2034   if (count ($src) != count ($dst)){
2035     return (TRUE);
2036   }
2038   /* So the count is the same - lets check the contents */
2039   $differs= FALSE;
2040   foreach($src as $value){
2041     if (!in_array($value, $dst)){
2042       $differs= TRUE;
2043     }
2044   }
2046   return ($differs);
2050 function saveFilter($a_filter, $values)
2052   if (isset($_POST['regexit'])){
2053     $a_filter["regex"]= $_POST['regexit'];
2055     foreach($values as $type){
2056       if (isset($_POST[$type])) {
2057         $a_filter[$type]= "checked";
2058       } else {
2059         $a_filter[$type]= "";
2060       }
2061     }
2062   }
2064   /* React on alphabet links if needed */
2065   if (isset($_GET['search'])){
2066     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2067     if ($s == "**"){
2068       $s= "*";
2069     }
2070     $a_filter['regex']= $s;
2071   }
2073   return ($a_filter);
2077 /* Escape all preg_* relevant characters */
2078 function normalizePreg($input)
2080   return (addcslashes($input, '[]()|/.*+-'));
2084 /* Escape all LDAP filter relevant characters */
2085 function normalizeLdap($input)
2087   return (addcslashes($input, '()|'));
2091 /* Resturns the difference between to microtime() results in float  */
2092 function get_MicroTimeDiff($start , $stop)
2094   $a = split("\ ",$start);
2095   $b = split("\ ",$stop);
2097   $secs = $b[1] - $a[1];
2098   $msecs= $b[0] - $a[0]; 
2100   $ret = (float) ($secs+ $msecs);
2101   return($ret);
2105 function get_base_dir()
2107   global $BASE_DIR;
2109   return $BASE_DIR;
2113 function obj_is_readable($dn, $object, $attribute)
2115   global $ui;
2117   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2121 function obj_is_writable($dn, $object, $attribute)
2123   global $ui;
2125   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2129 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2131   /* Initialize variables */
2132   $ret  = array("count" => 0);  // Set count to 0
2133   $next = true;                 // if false, then skip next loops and return
2134   $cnt  = 0;                    // Current number of loops
2135   $max  = 100;                  // Just for security, prevent looops
2136   $ldap = NULL;                 // To check if created result a valid
2137   $keep = "";                   // save last failed parse string
2139   /* Check each parsed dn in ldap ? */
2140   if($config!==NULL && $verify_in_ldap){
2141     $ldap = $config->get_ldap_link();
2142   }
2144   /* Lets start */
2145   $called = false;
2146   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2148     $cnt ++;
2149     if(!preg_match("/,/",$dn)){
2150       $next = false;
2151     }
2152     $object = preg_replace("/[,].*$/","",$dn);
2153     $dn     = preg_replace("/^[^,]+,/","",$dn);
2155     $called = true;
2157     /* Check if current dn is valid */
2158     if($ldap!==NULL){
2159       $ldap->cd($dn);
2160       $ldap->cat($dn,array("dn"));
2161       if($ldap->count()){
2162         $ret[]  = $keep.$object;
2163         $keep   = "";
2164       }else{
2165         $keep  .= $object.",";
2166       }
2167     }else{
2168       $ret[]  = $keep.$object;
2169       $keep   = "";
2170     }
2171   }
2173   /* No dn was posted */
2174   if($cnt == 0 && !empty($dn)){
2175     $ret[] = $dn;
2176   }
2178   /* Append the rest */
2179   $test = $keep.$dn;
2180   if($called && !empty($test)){
2181     $ret[] = $keep.$dn;
2182   }
2183   $ret['count'] = count($ret) - 1;
2185   return($ret);
2189 function get_base_from_hook($dn, $attrib)
2191   global $config;
2193   if ($config->get_cfg_value("nextIdHook") != ""){
2194     
2195     /* Call hook script - if present */
2196     $command= $config->get_cfg_value("nextIdHook");
2198     if ($command != ""){
2199       $command.= " '".LDAP::fix($dn)."' $attrib";
2200       if (check_command($command)){
2201         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2202         exec($command, $output);
2203         if (preg_match("/^[0-9]+$/", $output[0])){
2204           return ($output[0]);
2205         } else {
2206           msg_dialog::display(_("Warning"), _("'nextIdHook' is not available. Using default base!"), WARNING_DIALOG);
2207           return ($config->get_cfg_value("uidNumberBase"));
2208         }
2209       } else {
2210         msg_dialog::display(_("Warning"), _("'nextIdHook' is not available. Using default base!"), WARNING_DIALOG);
2211         return ($config->get_cfg_value("uidNumberBase"));
2212       }
2214     } else {
2216       msg_dialog::display(_("Warning"), _("'nextIdHook' is not available. Using default base!"), WARNING_DIALOG);
2217       return ($config->get_cfg_value("uidNumberBase"));
2219     }
2220   }
2224 function check_schema_version($class, $version)
2226   return preg_match("/\(v$version\)/", $class['DESC']);
2230 function check_schema($cfg,$rfc2307bis = FALSE)
2232   $messages= array();
2234   /* Get objectclasses */
2235   $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2236   $objectclasses = $ldap->get_objectclasses();
2237   if(count($objectclasses) == 0){
2238     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2239   }
2241   /* This is the default block used for each entry.
2242    *  to avoid unset indexes.
2243    */
2244   $def_check = array("REQUIRED_VERSION" => "0",
2245       "SCHEMA_FILES"     => array(),
2246       "CLASSES_REQUIRED" => array(),
2247       "STATUS"           => FALSE,
2248       "IS_MUST_HAVE"     => FALSE,
2249       "MSG"              => "",
2250       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2252   /* The gosa base schema */
2253   $checks['gosaObject'] = $def_check;
2254   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2255   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2256   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2257   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2259   /* GOsa Account class */
2260   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2261   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2262   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2263   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2264   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2266   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2267   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2268   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2269   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2270   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2271   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2273   /* Some other checks */
2274   foreach(array(
2275         "gosaCacheEntry"        => array("version" => "2.4"),
2276         "gosaDepartment"        => array("version" => "2.4"),
2277         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2278         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2279         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2280         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2281         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2282         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2283         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2284         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2285         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2286         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2287         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2288         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2289         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2290         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2291         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2292         "goLdapServer"          => array("version" => "2.4"),
2293         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2294         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2295         "goKrbServer"           => array("version" => "2.4"),
2296         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2297         ) as $name => $values){
2299           $checks[$name] = $def_check;
2300           if(isset($values['version'])){
2301             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2302           }
2303           if(isset($values['file'])){
2304             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2305           }
2306           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2307         }
2308   foreach($checks as $name => $value){
2309     foreach($value['CLASSES_REQUIRED'] as $class){
2311       if(!isset($objectclasses[$name])){
2312         $checks[$name]['STATUS'] = FALSE;
2313         if($value['IS_MUST_HAVE']){
2314           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2315         }else{
2316           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2317         }
2318       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2319         $checks[$name]['STATUS'] = FALSE;
2321         if($value['IS_MUST_HAVE']){
2322           $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2323         }else{
2324           $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2325         }
2326       }else{
2327         $checks[$name]['STATUS'] = TRUE;
2328         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2329       }
2330     }
2331   }
2333   $tmp = $objectclasses;
2335   /* The gosa base schema */
2336   $checks['posixGroup'] = $def_check;
2337   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2338   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2339   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2340   $checks['posixGroup']['STATUS']           = TRUE;
2341   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2342   $checks['posixGroup']['MSG']              = "";
2343   $checks['posixGroup']['INFO']             = "";
2345   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2346   if(isset($tmp['posixGroup'])){
2348     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2349       $checks['posixGroup']['STATUS']           = FALSE;
2350       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2351       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2352     }
2353     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2354       $checks['posixGroup']['STATUS']           = FALSE;
2355       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2356       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2357     }
2358   }
2360   return($checks);
2364 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2366   $tmp = array(
2367         "de_DE" => "German",
2368         "fr_FR" => "French",
2369         "it_IT" => "Italian",
2370         "es_ES" => "Spanish",
2371         "en_US" => "English",
2372         "nl_NL" => "Dutch",
2373         "pl_PL" => "Polish",
2374         "sv_SE" => "Swedish",
2375         "zh_CN" => "Chinese",
2376         "vi_VN" => "Vietnamese",
2377         "ru_RU" => "Russian");
2378   
2379   $tmp2= array(
2380         "de_DE" => _("German"),
2381         "fr_FR" => _("French"),
2382         "it_IT" => _("Italian"),
2383         "es_ES" => _("Spanish"),
2384         "en_US" => _("English"),
2385         "nl_NL" => _("Dutch"),
2386         "pl_PL" => _("Polish"),
2387         "sv_SE" => _("Swedish"),
2388         "zh_CN" => _("Chinese"),
2389         "vi_VN" => _("Vietnamese"),
2390         "ru_RU" => _("Russian"));
2392   $ret = array();
2393   if($languages_in_own_language){
2395     $old_lang = setlocale(LC_ALL, 0);
2397     /* If the locale wasn't correclty set before, there may be an incorrect
2398         locale returned. Something like this: 
2399           C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2400         Extract the locale name from this string and use it to restore old locale.
2401      */
2402     if(preg_match("/LC_CTYPE/",$old_lang)){
2403       $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2404     }
2405     
2406     foreach($tmp as $key => $name){
2407       $lang = $key.".UTF-8";
2408       setlocale(LC_ALL, $lang);
2409       if($strip_region_tag){
2410         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2411       }else{
2412         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2413       }
2414     }
2415     setlocale(LC_ALL, $old_lang);
2416   }else{
2417     foreach($tmp as $key => $name){
2418       if($strip_region_tag){
2419         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2420       }else{
2421         $ret[$key] = _($name);
2422       }
2423     }
2424   }
2425   return($ret);
2429 /* Returns contents of the given POST variable and check magic quotes settings */
2430 function get_post($name)
2432   if(!isset($_POST[$name])){
2433     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2434     return(FALSE);
2435   }
2436   if(get_magic_quotes_gpc()){
2437     return(stripcslashes($_POST[$name]));
2438   }else{
2439     return($_POST[$name]);
2440   }
2444 /* Return class name in correct case */
2445 function get_correct_class_name($cls)
2447   global $class_mapping;
2448   if(isset($class_mapping) && is_array($class_mapping)){
2449     foreach($class_mapping as $class => $file){
2450       if(preg_match("/^".$cls."$/i",$class)){
2451         return($class);
2452       }
2453     }
2454   }
2455   return(FALSE);
2459 // change_password, changes the Password, of the given dn
2460 function change_password ($dn, $password, $mode=0, $hash= "")
2462   global $config;
2463   $newpass= "";
2465   /* Convert to lower. Methods are lowercase */
2466   $hash= strtolower($hash);
2468   // Get all available encryption Methods
2470   // NON STATIC CALL :)
2471   $methods = new passwordMethod(session::get('config'));
2472   $available = $methods->get_available_methods();
2474   // read current password entry for $dn, to detect the encryption Method
2475   $ldap       = $config->get_ldap_link();
2476   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2477   $attrs      = $ldap->fetch ();
2479   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2480   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2481     $deactivated = TRUE;
2482   }else{
2483     $deactivated = FALSE;
2484   }
2486   /* Is ensure that clear passwords will stay clear */
2487   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2488     $hash = "clear";
2489   }
2491   // Detect the encryption Method
2492   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2494     /* Check for supported algorithm */
2495     mt_srand((double) microtime()*1000000);
2497     /* Extract used hash */
2498     if ($hash == ""){
2499       $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2500     } else {
2501       $test = new $available[$hash]($config,$dn);
2502       $test->set_hash($hash);
2503     }
2505   } else {
2506     // User MD5 by default
2507     $hash= "md5";
2508     $test = new  $available['md5']($config);
2509   }
2511   /* Feed password backends with information */
2512   $test->dn= $dn;
2513   $test->attrs= $attrs;
2514   $newpass= $test->generate_hash($password);
2516   // Update shadow timestamp?
2517   if (isset($attrs["shadowLastChange"][0])){
2518     $shadow= (int)(date("U") / 86400);
2519   } else {
2520     $shadow= 0;
2521   }
2523   // Write back modified entry
2524   $ldap->cd($dn);
2525   $attrs= array();
2527   // Not for groups
2528   if ($mode == 0){
2530     if ($shadow != 0){
2531       $attrs['shadowLastChange']= $shadow;
2532     }
2534     // Create SMB Password
2535     $attrs= generate_smb_nt_hash($password);
2536   }
2538  /* Read ! if user was deactivated */
2539   if($deactivated){
2540     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2541   }
2543   $attrs['userPassword']= array();
2544   $attrs['userPassword']= $newpass;
2546   $ldap->modify($attrs);
2548   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2550   if (!$ldap->success()) {
2551     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2552   } else {
2554     /* Run backend method for change/create */
2555     if(!$test->set_password($password)){
2556       return(FALSE);
2557     }
2559     /* Find postmodify entries for this class */
2560     $command= $config->search("password", "POSTMODIFY",array('menu'));
2562     if ($command != ""){
2563       /* Walk through attribute list */
2564       $command= preg_replace("/%userPassword/", $password, $command);
2565       $command= preg_replace("/%dn/", $dn, $command);
2567       if (check_command($command)){
2568         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2569         exec($command);
2570       } else {
2571         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2572         msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2573       }
2574     }
2575   }
2576   return(TRUE);
2580 // Return something like array['sambaLMPassword']= "lalla..."
2581 function generate_smb_nt_hash($password)
2583   global $config;
2585   # Try to use gosa-si?
2586   if ($config->get_cfg_value("gosaSupportURI") != ""){
2587         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2588     if (isset($res['XML']['HASH'])){
2589         $hash= $res['XML']['HASH'];
2590     } else {
2591       $hash= "";
2592     }
2593   } else {
2594           $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
2595           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2597           exec($tmp, $ar);
2598           flush();
2599           reset($ar);
2600           $hash= current($ar);
2601   }
2603   if ($hash == "") {
2604           msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2605           return ("");
2606   }
2608   list($lm,$nt)= split (":", trim($hash));
2610   if ($config->get_cfg_value("sambaversion") == 3) {
2611           $attrs['sambaLMPassword']= $lm;
2612           $attrs['sambaNTPassword']= $nt;
2613           $attrs['sambaPwdLastSet']= date('U');
2614           $attrs['sambaBadPasswordCount']= "0";
2615           $attrs['sambaBadPasswordTime']= "0";
2616   } else {
2617           $attrs['lmPassword']= $lm;
2618           $attrs['ntPassword']= $nt;
2619           $attrs['pwdLastSet']= date('U');
2620   }
2621   return($attrs);
2625 function getEntryCSN($dn)
2627   global $config;
2628   if(empty($dn) || !is_object($config)){
2629     return("");
2630   }
2632   /* Get attribute that we should use as serial number */
2633   $attr= $config->get_cfg_value("modificationDetectionAttribute");
2634   if($attr != ""){
2635     $ldap = $config->get_ldap_link();
2636     $ldap->cat($dn,array($attr));
2637     $csn = $ldap->fetch();
2638     if(isset($csn[$attr][0])){
2639       return($csn[$attr][0]);
2640     }
2641   }
2642   return("");
2646 /* Add a given objectClass to an attrs entry */
2647 function add_objectClass($classes, &$attrs)
2649   if (is_array($classes)){
2650     $list= $classes;
2651   } else {
2652     $list= array($classes);
2653   }
2655   foreach ($list as $class){
2656     $attrs['objectClass'][]= $class;
2657   }
2661 /* Removes a given objectClass from the attrs entry */
2662 function remove_objectClass($classes, &$attrs)
2664   if (isset($attrs['objectClass'])){
2665     /* Array? */
2666     if (is_array($classes)){
2667       $list= $classes;
2668     } else {
2669       $list= array($classes);
2670     }
2672     $tmp= array();
2673     foreach ($attrs['objectClass'] as $oc) {
2674       foreach ($list as $class){
2675         if (strtolower($oc) != strtolower($class)){
2676           $tmp[]= $oc;
2677         }
2678       }
2679     }
2680     $attrs['objectClass']= $tmp;
2681   }
2684 /*! \brief  Initialize a file download with given content, name and data type. 
2685  *  @param  data  String The content to send.
2686  *  @param  name  String The name of the file.
2687  *  @param  type  String The content identifier, default value is "application/octet-stream";
2688  */
2689 function send_binary_content($data,$name,$type = "application/octet-stream")
2691   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2692   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2693   header("Cache-Control: no-cache");
2694   header("Pragma: no-cache");
2695   header("Cache-Control: post-check=0, pre-check=0");
2696   header("Content-type: ".$type."");
2698   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2700   /* Strip name if it is a complete path */
2701   if (preg_match ("/\//", $name)) {
2702         $name= basename($name);
2703   }
2704   
2705   /* force download dialog */
2706   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2707     header('Content-Disposition: filename="'.$name.'"');
2708   } else {
2709     header('Content-Disposition: attachment; filename="'.$name.'"');
2710   }
2712   echo $data;
2713   exit();
2717 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2719   if(is_string($str)){
2720     return(htmlentities($str,$type,$charset));
2721   }elseif(is_array($str)){
2722     foreach($str as $name => $value){
2723       $str[$name] = reverse_html_entities($value,$type,$charset);
2724     }
2725   }
2726   return($str);
2730 /*! \brief Encode special string characters so we can use the string in \
2731            HTML output, without breaking quotes.
2732     @param  The String we want to encode.
2733     @return The encoded String
2734  */
2735 function xmlentities($str)
2736
2737   if(is_string($str)){
2739     static $asc2uni= array();
2740     if (!count($asc2uni)){
2741       for($i=128;$i<256;$i++){
2742     #    $asc2uni[chr($i)] = "&#x".dechex($i).";";
2743       }
2744     }
2746     $str = str_replace("&", "&amp;", $str);
2747     $str = str_replace("<", "&lt;", $str);
2748     $str = str_replace(">", "&gt;", $str);
2749     $str = str_replace("'", "&apos;", $str);
2750     $str = str_replace("\"", "&quot;", $str);
2751     $str = str_replace("\r", "", $str);
2752     $str = strtr($str,$asc2uni);
2753     return $str;
2754   }elseif(is_array($str)){
2755     foreach($str as $name => $value){
2756       $str[$name] = xmlentities($value);
2757     }
2758   }
2759   return($str);
2763 /*! \brief  Updates all accessTo attributes from a given value to a new one.
2764             For example if a host is renamed.
2765     @param  String  $from The source accessTo name.
2766     @param  String  $to   The destination accessTo name.
2767 */
2768 function update_accessTo($from,$to)
2770   global $config;
2771   $ldap = $config->get_ldap_link();
2772   $ldap->cd($config->current['BASE']);
2773   $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2774   while($attrs = $ldap->fetch()){
2775     $new_attrs = array("accessTo" => array());
2776     $dn = $attrs['dn'];
2777     for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2778       $new_attrs['objectClass'][] =  $attrs['objectClass'][$i];
2779     }
2780     for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2781       if($attrs['accessTo'][$i] == $from){
2782         if(!empty($to)){
2783           $new_attrs['accessTo'][] =  $to;
2784         }
2785       }else{
2786         $new_attrs['accessTo'][] =  $attrs['accessTo'][$i]; 
2787       }
2788     }
2789     $ldap->cd($dn);
2790     $ldap->modify($new_attrs);
2791     if (!$ldap->success()){
2792       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2793     }
2794     new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2795   }
2799 function get_random_char () {
2800      $randno = rand (0, 63);
2801      if ($randno < 12) {
2802          return (chr ($randno + 46)); // Digits, '/' and '.'
2803      } else if ($randno < 38) {
2804          return (chr ($randno + 53)); // Uppercase
2805      } else {
2806          return (chr ($randno + 59)); // Lowercase
2807      }
2811 function cred_encrypt($input, $password) {
2813   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2814   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2816   return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2820 function cred_decrypt($input,$password) {
2821   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2822   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2824   return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2828 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2829 ?>