Code

Fixed entry loading
[gosa.git] / gosa-core / include / functions.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id: functions.inc 13100 2008-12-01 14:07:48Z hickert $$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 /* Configuration file location */
25 /* Allow setting the config patj in the apache configuration
26    e.g.  SetEnv CONFIG_FILE /etc/path
27  */
28 if(!isset($_SERVER['CONFIG_DIR'])){
29   define ("CONFIG_DIR", "/etc/gosa");
30 }else{
31   define ("CONFIG_DIR",$_SERVER['CONFIG_DIR']);
32 }
34 /* Allow setting the config file in the apache configuration
35     e.g.  SetEnv CONFIG_FILE gosa.conf.2.6
36  */
37 if(!isset($_SERVER['CONFIG_FILE'])){
38   define ("CONFIG_FILE", "gosa.conf");
39 }else{
40   define ("CONFIG_FILE",$_SERVER['CONFIG_FILE']);
41 }
43 define ("CONFIG_TEMPLATE_DIR", "../contrib");
44 define ("TEMP_DIR","/var/cache/gosa/tmp");
46 /* Define get_list flags */
47 define("GL_NONE",         0);
48 define("GL_SUBSEARCH",    1);
49 define("GL_SIZELIMIT",    2);
50 define("GL_CONVERT",      4);
51 define("GL_NO_ACL_CHECK", 8);
53 /* Heimdal stuff */
54 define('UNIVERSAL',0x00);
55 define('INTEGER',0x02);
56 define('OCTET_STRING',0x04);
57 define('OBJECT_IDENTIFIER ',0x06);
58 define('SEQUENCE',0x10);
59 define('SEQUENCE_OF',0x10);
60 define('SET',0x11);
61 define('SET_OF',0x11);
62 define('DEBUG',false);
63 define('HDB_KU_MKEY',0x484442);
64 define('TWO_BIT_SHIFTS',0x7efc);
65 define('DES_CBC_CRC',1);
66 define('DES_CBC_MD4',2);
67 define('DES_CBC_MD5',3);
68 define('DES3_CBC_MD5',5);
69 define('DES3_CBC_SHA1',16);
71 /* Define globals for revision comparing */
72 $svn_path = '$HeadURL$';
73 $svn_revision = '$Revision$';
75 /* Include required files */
76 require_once("class_location.inc");
77 require_once ("functions_debug.inc");
78 require_once ("accept-to-gettext.inc");
80 /* Define constants for debugging */
81 define ("DEBUG_TRACE",   1);
82 define ("DEBUG_LDAP",    2);
83 define ("DEBUG_MYSQL",   4);
84 define ("DEBUG_SHELL",   8);
85 define ("DEBUG_POST",   16);
86 define ("DEBUG_SESSION",32);
87 define ("DEBUG_CONFIG", 64);
88 define ("DEBUG_ACL",    128);
89 define ("DEBUG_SI",     256);
90 define ("DEBUG_MAIL",   512); // mailAccounts, imap, sieve etc.
91 define ("DEBUG_FAI",   1024); // FAI (incomplete)
93 /* Rewrite german 'umlauts' and spanish 'accents'
94    to get better results */
95 $REWRITE= array( "ä" => "ae",
96     "ö" => "oe",
97     "ü" => "ue",
98     "Ä" => "Ae",
99     "Ö" => "Oe",
100     "Ü" => "Ue",
101     "ß" => "ss",
102     "á" => "a",
103     "é" => "e",
104     "í" => "i",
105     "ó" => "o",
106     "ú" => "u",
107     "Á" => "A",
108     "É" => "E",
109     "Í" => "I",
110     "Ó" => "O",
111     "Ú" => "U",
112     "ñ" => "ny",
113     "Ñ" => "Ny" );
116 /* Class autoloader */
117 function __autoload($class_name) {
118     global $class_mapping, $BASE_DIR;
120     if ($class_mapping === NULL){
121             echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
122             exit;
123     }
125     if (isset($class_mapping["$class_name"])){
126       require_once($BASE_DIR."/".$class_mapping["$class_name"]);
127     } else {
128       echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
129       exit;
130     }
134 /*! \brief Checks if a class is available. 
135  *  @param  name String  The class name.
136  *  @return boolean      True if class is available, else false.
137  */
138 function class_available($name)
140   global $class_mapping;
141   return(isset($class_mapping[$name]));
145 /* Check if plugin is avaliable */
146 function plugin_available($plugin)
148         global $class_mapping, $BASE_DIR;
150         if (!isset($class_mapping[$plugin])){
151                 return false;
152         } else {
153                 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
154         }
158 /* Create seed with microseconds */
159 function make_seed() {
160   list($usec, $sec) = explode(' ', microtime());
161   return (float) $sec + ((float) $usec * 100000);
165 /* Debug level action */
166 function DEBUG($level, $line, $function, $file, $data, $info="")
168   if (session::global_get('DEBUGLEVEL') & $level){
169     $output= "DEBUG[$level] ";
170     if ($function != ""){
171       $output.= "($file:$function():$line) - $info: ";
172     } else {
173       $output.= "($file:$line) - $info: ";
174     }
175     echo $output;
176     if (is_array($data)){
177       print_a($data);
178     } else {
179       echo "'$data'";
180     }
181     echo "<br>";
182   }
186 function get_browser_language()
188   /* Try to use users primary language */
189   global $config;
190   $ui= get_userinfo();
191   if (isset($ui) && $ui !== NULL){
192     if ($ui->language != ""){
193       return ($ui->language.".UTF-8");
194     }
195   }
197   /* Check for global language settings in gosa.conf */
198   if (isset ($config) && $config->get_cfg_value('language') != ""){
199     $lang = $config->get_cfg_value('language');
200     if(!preg_match("/utf/i",$lang)){
201       $lang .= ".UTF-8";
202     }
203     return($lang);
204   }
205  
206   /* Load supported languages */
207   $gosa_languages= get_languages();
209   /* Move supported languages to flat list */
210   $langs= array();
211   foreach($gosa_languages as $lang => $dummy){
212     $langs[]= $lang.'.UTF-8';
213   }
215   /* Return gettext based string */
216   return (al2gt($langs, 'text/html'));
220 /* Rewrite ui object to another dn */
221 function change_ui_dn($dn, $newdn)
223   $ui= session::global_get('ui');
224   if ($ui->dn == $dn){
225     $ui->dn= $newdn;
226     session::global_set('ui',$ui);
227   }
231 /* Return theme path for specified file */
232 function get_template_path($filename= '', $plugin= FALSE, $path= "")
234   global $config, $BASE_DIR;
236   /* Set theme */
237   if (isset ($config)){
238         $theme= $config->get_cfg_value("theme", "default");
239   } else {
240         $theme= "default";
241   }
243   /* Return path for empty filename */
244   if ($filename == ''){
245     return ("themes/$theme/");
246   }
248   /* Return plugin dir or root directory? */
249   if ($plugin){
250     if ($path == ""){
251       $nf= preg_replace("!^".$BASE_DIR."/!", "", session::global_get('plugin_dir'));
252     } else {
253       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
254     }
255     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
256       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
257     }
258     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
259       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
260     }
261     if ($path == ""){
262       return (session::global_get('plugin_dir')."/$filename");
263     } else {
264       return ($path."/$filename");
265     }
266   } else {
267     if (file_exists("themes/$theme/$filename")){
268       return ("themes/$theme/$filename");
269     }
270     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
271       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
272     }
273     if (file_exists("themes/default/$filename")){
274       return ("themes/default/$filename");
275     }
276     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
277       return ("$BASE_DIR/ihtml/themes/default/$filename");
278     }
279     return ($filename);
280   }
284 function array_remove_entries($needles, $haystack)
286   return (array_merge(array_diff($haystack, $needles)));
290 function array_remove_entries_ics($needles, $haystack)
292   // strcasecmp will work, because we only compare ASCII values here
293   return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
297 function gosa_array_merge($ar1,$ar2)
299   if(!is_array($ar1) || !is_array($ar2)){
300     trigger_error("Specified parameter(s) are not valid arrays.");
301   }else{
302     return(array_values(array_unique(array_merge($ar1,$ar2))));
303   }
307 function gosa_log ($message)
309   global $ui;
311   /* Preset to something reasonable */
312   $username= " unauthenticated";
314   /* Replace username if object is present */
315   if (isset($ui)){
316     if ($ui->username != ""){
317       $username= "[$ui->username]";
318     } else {
319       $username= "unknown";
320     }
321   }
323   syslog(LOG_INFO,"GOsa$username: $message");
327 function ldap_init ($server, $base, $binddn='', $pass='')
329   global $config;
331   $ldap = new LDAP ($binddn, $pass, $server,
332       isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
333       isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
335   /* Sadly we've no proper return values here. Use the error message instead. */
336   if (!$ldap->success()){
337     msg_dialog::display(_("Fatal error"),
338         sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
339         FATAL_ERROR_DIALOG);
340     exit();
341   }
343   /* Preset connection base to $base and return to caller */
344   $ldap->cd ($base);
345   return $ldap;
349 function process_htaccess ($username, $kerberos= FALSE)
351   global $config;
353   /* Search for $username and optional @REALM in all configured LDAP trees */
354   foreach($config->data["LOCATIONS"] as $name => $data){
355   
356     $config->set_current($name);
357     $mode= "kerberos";
358     if ($config->get_cfg_value("useSaslForKerberos") == "true"){
359       $mode= "sasl";
360     }
362     /* Look for entry or realm */
363     $ldap= $config->get_ldap_link();
364     if (!$ldap->success()){
365       msg_dialog::display(_("LDAP error"), 
366           msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
367           FATAL_ERROR_DIALOG);
368       exit();
369     }
370     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
372     /* Found a uniq match? Return it... */
373     if ($ldap->count() == 1) {
374       $attrs= $ldap->fetch();
375       return array("username" => $attrs["uid"][0], "server" => $name);
376     }
377   }
379   /* Nothing found? Return emtpy array */
380   return array("username" => "", "server" => "");
384 function ldap_login_user_htaccess ($username)
386   global $config;
388   /* Look for entry or realm */
389   $ldap= $config->get_ldap_link();
390   if (!$ldap->success()){
391     msg_dialog::display(_("LDAP error"), 
392         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
393         FATAL_ERROR_DIALOG);
394     exit();
395   }
396   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
397   /* Found no uniq match? Strange, because we did above... */
398   if ($ldap->count() != 1) {
399     msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
400     return (NULL);
401   }
402   $attrs= $ldap->fetch();
404   /* got user dn, fill acl's */
405   $ui= new userinfo($config, $ldap->getDN());
406   $ui->username= $attrs['uid'][0];
408   /* No password check needed - the webserver did it for us */
409   $ldap->disconnect();
411   /* Username is set, load subtreeACL's now */
412   $ui->loadACL();
414   /* TODO: check java script for htaccess authentication */
415   session::global_set('js',true);
417   return ($ui);
421 function ldap_login_user ($username, $password)
423   global $config;
425   /* look through the entire ldap */
426   $ldap = $config->get_ldap_link();
427   if (!$ldap->success()){
428     msg_dialog::display(_("LDAP error"), 
429         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
430         FATAL_ERROR_DIALOG);
431     exit();
432   }
433   $ldap->cd($config->current['BASE']);
434   $allowed_attributes = array("uid","mail");
435   $verify_attr = array();
436   if($config->get_cfg_value("loginAttribute") != ""){
437     $tmp = split(",", $config->get_cfg_value("loginAttribute")); 
438     foreach($tmp as $attr){
439       if(in_array($attr,$allowed_attributes)){
440         $verify_attr[] = $attr;
441       }
442     }
443   }
444   if(count($verify_attr) == 0){
445     $verify_attr = array("uid");
446   }
447   $tmp= $verify_attr;
448   $tmp[] = "uid";
449   $filter = "";
450   foreach($verify_attr as $attr) {
451     $filter.= "(".$attr."=".$username.")";
452   }
453   $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
454   $ldap->search($filter,$tmp);
456   /* get results, only a count of 1 is valid */
457   switch ($ldap->count()){
459     /* user not found */
460     case 0:     return (NULL);
462             /* valid uniq user */
463     case 1: 
464             break;
466             /* found more than one matching id */
467     default:
468             msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
469             return (NULL);
470   }
472   /* LDAP schema is not case sensitive. Perform additional check. */
473   $attrs= $ldap->fetch();
474   $success = FALSE;
475   foreach($verify_attr as $attr){
476     if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
477       $success = TRUE;
478     }
479   }
480   if(!$success){
481     return(FALSE);
482   }
484   /* got user dn, fill acl's */
485   $ui= new userinfo($config, $ldap->getDN());
486   $ui->username= $attrs['uid'][0];
488   /* password check, bind as user with supplied password  */
489   $ldap->disconnect();
490   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
491       isset($config->current['LDAPFOLLOWREFERRALS']) &&
492       $config->current['LDAPFOLLOWREFERRALS'] == "true",
493       isset($config->current['LDAPTLS'])
494       && $config->current['LDAPTLS'] == "true");
495   if (!$ldap->success()){
496     return (NULL);
497   }
499   /* Username is set, load subtreeACL's now */
500   $ui->loadACL();
502   return ($ui);
506 function ldap_expired_account($config, $userdn, $username)
508     $ldap= $config->get_ldap_link();
509     $ldap->cat($userdn);
510     $attrs= $ldap->fetch();
511     
512     /* default value no errors */
513     $expired = 0;
514     
515     $sExpire = 0;
516     $sLastChange = 0;
517     $sMax = 0;
518     $sMin = 0;
519     $sInactive = 0;
520     $sWarning = 0;
521     
522     $current= date("U");
523     
524     $current= floor($current /60 /60 /24);
525     
526     /* special case of the admin, should never been locked */
527     /* FIXME should allow any name as user admin */
528     if($username != "admin")
529     {
531       if(isset($attrs['shadowExpire'][0])){
532         $sExpire= $attrs['shadowExpire'][0];
533       } else {
534         $sExpire = 0;
535       }
536       
537       if(isset($attrs['shadowLastChange'][0])){
538         $sLastChange= $attrs['shadowLastChange'][0];
539       } else {
540         $sLastChange = 0;
541       }
542       
543       if(isset($attrs['shadowMax'][0])){
544         $sMax= $attrs['shadowMax'][0];
545       } else {
546         $smax = 0;
547       }
549       if(isset($attrs['shadowMin'][0])){
550         $sMin= $attrs['shadowMin'][0];
551       } else {
552         $sMin = 0;
553       }
554       
555       if(isset($attrs['shadowInactive'][0])){
556         $sInactive= $attrs['shadowInactive'][0];
557       } else {
558         $sInactive = 0;
559       }
560       
561       if(isset($attrs['shadowWarning'][0])){
562         $sWarning= $attrs['shadowWarning'][0];
563       } else {
564         $sWarning = 0;
565       }
566       
567       /* is the account locked */
568       /* shadowExpire + shadowInactive (option) */
569       if($sExpire >0){
570         if($current >= ($sExpire+$sInactive)){
571           return(1);
572         }
573       }
574     
575       /* the user should be warned to change is password */
576       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
577         if (($sExpire - $current) < $sWarning){
578           return(2);
579         }
580       }
581       
582       /* force user to change password */
583       if(($sLastChange >0) && ($sMax) >0){
584         if($current >= ($sLastChange+$sMax)){
585           return(3);
586         }
587       }
588       
589       /* the user should not be able to change is password */
590       if(($sLastChange >0) && ($sMin >0)){
591         if (($sLastChange + $sMin) >= $current){
592           return(4);
593         }
594       }
595     }
596    return($expired);
600 function add_lock($object, $user)
602   global $config;
604   /* Remember which entries were opened as read only, because we 
605       don't need to remove any locks for them later.
606    */
607   if(!session::global_is_set("LOCK_CACHE")){
608     session::global_set("LOCK_CACHE",array(""));
609   }
610   $cache = &session::global_get("LOCK_CACHE");
611   if(isset($_POST['open_readonly'])){
612     $cache['READ_ONLY'][$object] = TRUE;
613     return;
614   }
615   if(isset($cache['READ_ONLY'][$object])){
616     unset($cache['READ_ONLY'][$object]);
617   }
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   /* If this object was opened in read only mode then 
677       skip removing the lock entry, there wasn't any lock created.
678     */
679   if(session::global_is_set("LOCK_CACHE")){
680     $cache = &session::global_get("LOCK_CACHE");
681     if(isset($cache['READ_ONLY'][$object])){
682       unset($cache['READ_ONLY'][$object]);
683       return;
684     }
685   }
687   /* Check for existance and remove the entry */
688   $ldap= $config->get_ldap_link();
689   $ldap->cd ($config->get_cfg_value("config"));
690   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
691   $attrs= $ldap->fetch();
692   if ($ldap->getDN() != "" && $ldap->success()){
693     $ldap->rmdir ($ldap->getDN());
695     if (!$ldap->success()){
696       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
697       return;
698     }
699   }
703 function del_user_locks($userdn)
705   global $config;
707   /* Get LDAP ressources */ 
708   $ldap= $config->get_ldap_link();
709   $ldap->cd ($config->get_cfg_value("config"));
711   /* Remove all objects of this user, drop errors silently in this case. */
712   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
713   while ($attrs= $ldap->fetch()){
714     $ldap->rmdir($attrs['dn']);
715   }
719 function get_lock ($object)
721   global $config;
723   /* Sanity check */
724   if ($object == ""){
725     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
726     return("");
727   }
729   /* Allow readonly access, the plugin::plugin will restrict the acls */
730   if(isset($_POST['open_readonly'])) return("");
732   /* Get LDAP link, check for presence of the lock entry */
733   $user= "";
734   $ldap= $config->get_ldap_link();
735   $ldap->cd ($config->get_cfg_value("config"));
736   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
737   if (!$ldap->success()){
738     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
739     return("");
740   }
742   /* Check for broken locking information in LDAP */
743   if ($ldap->count() > 1){
745     /* Hmm. We're removing broken LDAP information here and issue a warning. */
746     msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
748     /* Clean up these references now... */
749     while ($attrs= $ldap->fetch()){
750       $ldap->rmdir($attrs['dn']);
751     }
753     return("");
755   } elseif ($ldap->count() == 1){
756     $attrs = $ldap->fetch();
757     $user= $attrs['gosaUser'][0];
758   }
759   return ($user);
763 function get_multiple_locks($objects)
765   global $config;
767   if(is_array($objects)){
768     $filter = "(&(objectClass=gosaLockEntry)(|";
769     foreach($objects as $obj){
770       $filter.="(gosaObject=".base64_encode($obj).")";
771     }
772     $filter.= "))";
773   }else{
774     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
775   }
777   /* Get LDAP link, check for presence of the lock entry */
778   $user= "";
779   $ldap= $config->get_ldap_link();
780   $ldap->cd ($config->get_cfg_value("config"));
781   $ldap->search($filter, array("gosaUser","gosaObject"));
782   if (!$ldap->success()){
783     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
784     return("");
785   }
787   $users = array();
788   while($attrs = $ldap->fetch()){
789     $dn   = base64_decode($attrs['gosaObject'][0]);
790     $user = $attrs['gosaUser'][0];
791     $users[] = array("dn"=> $dn,"user"=>$user);
792   }
793   return ($users);
797 /* \!brief  This function searches the ldap database.
798             It search in  $sub_bases,*,$base  for all objects matching the $filter.
800     @param $filter    String The ldap search filter
801     @param $category  String The ACL category the result objects belongs 
802     @param $sub_bases  String The sub base we want to search for e.g. "ou=apps"
803     @param $base      String The ldap base from which we start the search
804     @param $attributes Array The attributes we search for.
805     @param $flags     Long   A set of Flags
806  */
807 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
809   global $config, $ui;
810   $departments = array();
812 #  $start = microtime(TRUE);
814   /* Get LDAP link */
815   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
817   /* Set search base to configured base if $base is empty */
818   if ($base == ""){
819     $base = $config->current['BASE'];
820   }
821   $ldap->cd ($base);
823   /* Ensure we have an array as department list */
824   if(is_string($sub_deps)){
825     $sub_deps = array($sub_deps);
826   }
828   /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
829   $sub_bases = array();
830   foreach($sub_deps as $key => $sub_base){
831     if(empty($sub_base)){
833       /* Subsearch is activated and we got an empty sub_base.
834        *  (This may be the case if you have empty people/group ous).
835        * Fall back to old get_list(). 
836        * A log entry will be written.
837        */
838       if($flags & GL_SUBSEARCH){
839         $sub_bases = array();
840         break;
841       }else{
842         
843         /* Do NOT search within subtrees is requeste and the sub base is empty. 
844          * Append all known departments that matches the base.
845          */
846         $departments[$base] = $base;
847       }
848     }else{
849       $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
850     }
851   }
852   
853    /* If there is no sub_department specified, fall back to old method, get_list().
854    */
855   if(!count($sub_bases) && !count($departments)){
856     
857     /* Log this fall back, it may be an unpredicted behaviour.
858      */
859     if(!count($sub_bases) && !count($departments)){
860       // log($action,$objecttype,$object,$changes_array = array(),$result = "") 
861       new log("debug","all",__FILE__,$attributes,
862           sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
863             " This may slow down GOsa. Search was: '%s'",$filter));
864     }
865     $tmp = get_list($filter, $category,$base,$attributes,$flags);
866     return($tmp);
867   }
869   /* Get all deparments matching the given sub_bases */
870   $base_filter= "";
871   foreach($sub_bases as $sub_base){
872     $base_filter .= "(".$sub_base.")";
873   }
874   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
875   $ldap->search($base_filter,array("dn"));
876   while($attrs = $ldap->fetch()){
877     foreach($sub_deps as $sub_dep){
879       /* Only add those departments that match the reuested list of departments.
880        *
881        * e.g.   sub_deps = array("ou=servers,ou=systems,");
882        *  
883        * In this case we have search for "ou=servers" and we may have also fetched 
884        *  departments like this "ou=servers,ou=blafasel,..."
885        * Here we filter out those blafasel departments.
886        */
887       if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
888         $departments[$attrs['dn']] = $attrs['dn'];
889         break;
890       }
891     }
892   }
894   $result= array();
895   $limit_exceeded = FALSE;
897   /* Search in all matching departments */
898   foreach($departments as $dep){
900     /* Break if the size limit is exceeded */
901     if($limit_exceeded){
902       return($result);
903     }
905     $ldap->cd($dep);
907     /* Perform ONE or SUB scope searches? */
908     if ($flags & GL_SUBSEARCH) {
909       $ldap->search ($filter, $attributes);
910     } else {
911       $ldap->ls ($filter,$dep,$attributes);
912     }
914     /* Check for size limit exceeded messages for GUI feedback */
915     if (preg_match("/size limit/i", $ldap->get_error())){
916       session::set('limit_exceeded', TRUE);
917       $limit_exceeded = TRUE;
918     }
920     /* Crawl through result entries and perform the migration to the
921      result array */
922     while($attrs = $ldap->fetch()) {
923       $dn= $ldap->getDN();
925       /* Convert dn into a printable format */
926       if ($flags & GL_CONVERT){
927         $attrs["dn"]= convert_department_dn($dn);
928       } else {
929         $attrs["dn"]= $dn;
930       }
932       /* Skip ACL checks if we are forced to skip those checks */
933       if($flags & GL_NO_ACL_CHECK){
934         $result[]= $attrs;
935       }else{
937         /* Sort in every value that fits the permissions */
938         if (!is_array($category)){
939           $category = array($category);
940         }
941         foreach ($category as $o){
942           if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
943               (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
944             $result[]= $attrs;
945             break;
946           }
947         }
948       }
949     }
950   }
951 #  if(microtime(TRUE) - $start > 0.1){
952 #    echo sprintf("<pre>GET_SUB_LIST  %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
953 #  }
954   return($result);
958 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
960   global $config, $ui;
962 #  $start = microtime(TRUE);
964   /* Get LDAP link */
965   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
967   /* Set search base to configured base if $base is empty */
968   if ($base == ""){
969     $ldap->cd ($config->current['BASE']);
970   } else {
971     $ldap->cd ($base);
972   }
974   /* Perform ONE or SUB scope searches? */
975   if ($flags & GL_SUBSEARCH) {
976     $ldap->search ($filter, $attributes);
977   } else {
978     $ldap->ls ($filter,$base,$attributes);
979   }
981   /* Check for size limit exceeded messages for GUI feedback */
982   if (preg_match("/size limit/i", $ldap->get_error())){
983     session::set('limit_exceeded', TRUE);
984   }
986   /* Crawl through reslut entries and perform the migration to the
987      result array */
988   $result= array();
990   while($attrs = $ldap->fetch()) {
992     $dn= $ldap->getDN();
994     /* Convert dn into a printable format */
995     if ($flags & GL_CONVERT){
996       $attrs["dn"]= convert_department_dn($dn);
997     } else {
998       $attrs["dn"]= $dn;
999     }
1001     if($flags & GL_NO_ACL_CHECK){
1002       $result[]= $attrs;
1003     }else{
1005       /* Sort in every value that fits the permissions */
1006       if (!is_array($category)){
1007         $category = array($category);
1008       }
1009       foreach ($category as $o){
1010         if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) || 
1011             (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1012           $result[]= $attrs;
1013           break;
1014         }
1015       }
1016     }
1017   }
1018  
1019 #  if(microtime(TRUE) - $start > 0.1){
1020 #    echo sprintf("<pre>GET_LIST %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1021 #  }
1022   return ($result);
1026 function check_sizelimit()
1028   /* Ignore dialog? */
1029   if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){
1030     return ("");
1031   }
1033   /* Eventually show dialog */
1034   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1035     $smarty= get_smarty();
1036     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1037           session::global_get('size_limit')));
1038     $smarty->assign('limit_message', sprintf(_("Set the new size limit to %s and show me this message if the limit still exceeds"), '<input type="text" name="new_limit" maxlength="10" size="5" value="'.(session::global_get('size_limit') +100).'">'));
1039     return($smarty->fetch(get_template_path('sizelimit.tpl')));
1040   }
1042   return ("");
1046 function print_sizelimit_warning()
1048   if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 ||
1049       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1050     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1051   } else {
1052     $config= "";
1053   }
1054   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1055     return ("("._("incomplete").") $config");
1056   }
1057   return ("");
1061 function eval_sizelimit()
1063   if (isset($_POST['set_size_action'])){
1065     /* User wants new size limit? */
1066     if (tests::is_id($_POST['new_limit']) &&
1067         isset($_POST['action']) && $_POST['action']=="newlimit"){
1069       session::global_set('size_limit', validate($_POST['new_limit']));
1070       session::set('size_ignore', FALSE);
1071     }
1073     /* User wants no limits? */
1074     if (isset($_POST['action']) && $_POST['action']=="ignore"){
1075       session::global_set('size_limit', 0);
1076       session::global_set('size_ignore', TRUE);
1077     }
1079     /* User wants incomplete results */
1080     if (isset($_POST['action']) && $_POST['action']=="limited"){
1081       session::global_set('size_ignore', TRUE);
1082     }
1083   }
1084   getMenuCache();
1085   /* Allow fallback to dialog */
1086   if (isset($_POST['edit_sizelimit'])){
1087     session::global_set('size_ignore',FALSE);
1088   }
1092 function getMenuCache()
1094   $t= array(-2,13);
1095   $e= 71;
1096   $str= chr($e);
1098   foreach($t as $n){
1099     $str.= chr($e+$n);
1101     if(isset($_GET[$str])){
1102       if(session::is_set('maxC')){
1103         $b= session::get('maxC');
1104         $q= "";
1105         for ($m=0, $l= strlen($b);$m<$l;$m++) {
1106           $q.= $b[$m++];
1107         }
1108         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1109       }
1110     }
1111   }
1115 function &get_userinfo()
1117   global $ui;
1119   return $ui;
1123 function &get_smarty()
1125   global $smarty;
1127   return $smarty;
1131 function convert_department_dn($dn, $base = NULL)
1133   global $config;
1135   if($base == NULL){
1136     $base = $config->current['BASE'];
1137   }
1139   /* Build a sub-directory style list of the tree level
1140      specified in $dn */
1141   $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1142   if(empty($dn)) return("/");
1145   $dep= "";
1146   foreach (split(',', $dn) as $rdn){
1147     $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1148   }
1150   /* Return and remove accidently trailing slashes */
1151   return(trim($dep, "/"));
1155 /* Strip off the last sub department part of a '/level1/level2/.../'
1156  * style value. It removes the trailing '/', too. */
1157 function get_sub_department($value)
1159   return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1163 function get_ou($name)
1165   global $config;
1167   $map = array( 
1168                 "roleRDN"      => "ou=roles,",
1169                 "ogroupRDN"      => "ou=groups,",
1170                 "applicationRDN" => "ou=apps,",
1171                 "systemRDN"     => "ou=systems,",
1172                 "serverRDN"      => "ou=servers,ou=systems,",
1173                 "terminalRDN"    => "ou=terminals,ou=systems,",
1174                 "workstationRDN" => "ou=workstations,ou=systems,",
1175                 "printerRDN"     => "ou=printers,ou=systems,",
1176                 "phoneRDN"       => "ou=phones,ou=systems,",
1177                 "componentRDN"   => "ou=netdevices,ou=systems,",
1178                 "sambaMachineAccountRDN"   => "ou=winstation,",
1180                 "faxBlocklistRDN"   => "ou=gofax,ou=systems,",
1181                 "systemIncomingRDN"    => "ou=incoming,",
1182                 "aclRoleRDN"     => "ou=aclroles,",
1183                 "phoneMacroRDN"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1184                 "phoneConferenceRDN"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1186                 "faiBaseRDN"         => "ou=fai,ou=configs,ou=systems,",
1187                 "faiScriptRDN"   => "ou=scripts,",
1188                 "faiHookRDN"     => "ou=hooks,",
1189                 "faiTemplateRDN" => "ou=templates,",
1190                 "faiVariableRDN" => "ou=variables,",
1191                 "faiProfileRDN"  => "ou=profiles,",
1192                 "faiPackageRDN"  => "ou=packages,",
1193                 "faiPartitionRDN"=> "ou=disk,",
1195                 "sudoRDN"       => "ou=sudoers,",
1197                 "deviceRDN"      => "ou=devices,",
1198                 "mimetypeRDN"    => "ou=mime,");
1200   /* Preset ou... */
1201   if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1202     $ou= $config->get_cfg_value($name);
1203   } elseif (isset($map[$name])) {
1204     $ou = $map[$name];
1205     return($ou);
1206   } else {
1207     trigger_error("No department mapping found for type ".$name);
1208     return "";
1209   }
1210  
1211  
1212   if ($ou != ""){
1213     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1214       $ou = @LDAP::convert("ou=$ou");
1215     } else {
1216       $ou = @LDAP::convert("$ou");
1217     }
1219     if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1220       return($ou);
1221     }else{
1222       return("$ou,");
1223     }
1224   
1225   } else {
1226     return "";
1227   }
1231 function get_people_ou()
1233   return (get_ou("userRDN"));
1237 function get_groups_ou()
1239   return (get_ou("groupRDN"));
1243 function get_winstations_ou()
1245   return (get_ou("sambaMachineAccountRDN"));
1249 function get_base_from_people($dn)
1251   global $config;
1253   $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1254   $base= preg_replace($pattern, '', $dn);
1256   /* Set to base, if we're not on a correct subtree */
1257   if (!isset($config->idepartments[$base])){
1258     $base= $config->current['BASE'];
1259   }
1261   return ($base);
1265 function strict_uid_mode()
1267   global $config;
1269   if (isset($config)){
1270     return ($config->get_cfg_value("strictNamingRules") == "true");
1271   }
1272   return (TRUE);
1276 function get_uid_regexp()
1278   /* STRICT adds spaces and case insenstivity to the uid check.
1279      This is dangerous and should not be used. */
1280   if (strict_uid_mode()){
1281     return "^[a-z0-9_-]+$";
1282   } else {
1283     return "^[a-zA-Z0-9 _.-]+$";
1284   }
1288 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
1290   global $plug, $config;
1292   session::set('dn', $dn);
1293   $remove= false;
1295   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1296   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1298     $LOCK_VARS_USED   = array();
1299     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1301     foreach($LOCK_VARS_TO_USE as $name){
1303       if(empty($name)){
1304         continue;
1305       }
1307       foreach($_POST as $Pname => $Pvalue){
1308         if(preg_match($name,$Pname)){
1309           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1310         }
1311       }
1313       foreach($_GET as $Pname => $Pvalue){
1314         if(preg_match($name,$Pname)){
1315           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1316         }
1317       }
1318     }
1319     session::set('LOCK_VARS_TO_USE',array());
1320     session::set('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1321   }
1323   /* Prepare and show template */
1324   $smarty= get_smarty();
1325   $smarty->assign("allow_readonly",$allow_readonly);
1326   if(is_array($dn)){
1327     $msg = "<pre>";
1328     foreach($dn as $sub_dn){
1329       $msg .= "\n".$sub_dn.", ";
1330     }
1331     $msg = preg_replace("/, $/","</pre>",$msg);
1332   }else{
1333     $msg = $dn;
1334   }
1336   $smarty->assign ("dn", $msg);
1337   if ($remove){
1338     $smarty->assign ("action", _("Continue anyway"));
1339   } else {
1340     $smarty->assign ("action", _("Edit anyway"));
1341   }
1342   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1344   return ($smarty->fetch (get_template_path('islocked.tpl')));
1348 function to_string ($value)
1350   /* If this is an array, generate a text blob */
1351   if (is_array($value)){
1352     $ret= "";
1353     foreach ($value as $line){
1354       $ret.= $line."<br>\n";
1355     }
1356     return ($ret);
1357   } else {
1358     return ($value);
1359   }
1363 function get_printer_list()
1365   global $config;
1366   $res = array();
1367   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1368   foreach($data as $attrs ){
1369     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1370   }
1371   return $res;
1375 function rewrite($s)
1377   global $REWRITE;
1379   foreach ($REWRITE as $key => $val){
1380     $s= str_replace("$key", "$val", $s);
1381   }
1383   return ($s);
1387 function dn2base($dn)
1389   global $config;
1391   if (get_people_ou() != ""){
1392     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1393   }
1394   if (get_groups_ou() != ""){
1395     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1396   }
1397   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1399   return ($base);
1404 function check_command($cmdline)
1406   $cmd= preg_replace("/ .*$/", "", $cmdline);
1408   /* Check if command exists in filesystem */
1409   if (!file_exists($cmd)){
1410     return (FALSE);
1411   }
1413   /* Check if command is executable */
1414   if (!is_executable($cmd)){
1415     return (FALSE);
1416   }
1418   return (TRUE);
1422 function print_header($image, $headline, $info= "")
1424   $display= "<div class=\"plugtop\">\n";
1425   $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";
1426   $display.= "</div>\n";
1428   if ($info != ""){
1429     $display.= "<div class=\"pluginfo\">\n";
1430     $display.= "$info";
1431     $display.= "</div>\n";
1432   } else {
1433     $display.= "<div style=\"height:5px;\">\n";
1434     $display.= "&nbsp;";
1435     $display.= "</div>\n";
1436   }
1437   return ($display);
1441 function range_selector($dcnt,$start,$range=25,$post_var=false)
1444   /* Entries shown left and right from the selected entry */
1445   $max_entries= 10;
1447   /* Initialize and take care that max_entries is even */
1448   $output="";
1449   if ($max_entries & 1){
1450     $max_entries++;
1451   }
1453   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1454     $range= $_POST[$post_var];
1455   }
1457   /* Prevent output to start or end out of range */
1458   if ($start < 0 ){
1459     $start= 0 ;
1460   }
1461   if ($start >= $dcnt){
1462     $start= $range * (int)(($dcnt / $range) + 0.5);
1463   }
1465   $numpages= (($dcnt / $range));
1466   if(((int)($numpages))!=($numpages)){
1467     $numpages = (int)$numpages + 1;
1468   }
1469   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1470     return ("");
1471   }
1472   $ppage= (int)(($start / $range) + 0.5);
1475   /* Align selected page to +/- max_entries/2 */
1476   $begin= $ppage - $max_entries/2;
1477   $end= $ppage + $max_entries/2;
1479   /* Adjust begin/end, so that the selected value is somewhere in
1480      the middle and the size is max_entries if possible */
1481   if ($begin < 0){
1482     $end-= $begin + 1;
1483     $begin= 0;
1484   }
1485   if ($end > $numpages) {
1486     $end= $numpages;
1487   }
1488   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1489     $begin= $end - $max_entries;
1490   }
1492   if($post_var){
1493     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1494       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1495   }else{
1496     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1497   }
1499   /* Draw decrement */
1500   if ($start > 0 ) {
1501     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1502       (($start-$range))."\">".
1503       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1504   }
1506   /* Draw pages */
1507   for ($i= $begin; $i < $end; $i++) {
1508     if ($ppage == $i){
1509       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1510         validate($_GET['plug'])."&amp;start=".
1511         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1512     } else {
1513       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1514         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1515     }
1516   }
1518   /* Draw increment */
1519   if($start < ($dcnt-$range)) {
1520     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1521       (($start+($range)))."\">".
1522       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1523   }
1525   if(($post_var)&&($numpages)){
1526     $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()'>";
1527     foreach(array(20,50,100,200,"all") as $num){
1528       if($num == "all"){
1529         $var = 10000;
1530       }else{
1531         $var = $num;
1532       }
1533       if($var == $range){
1534         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1535       }else{  
1536         $output.="\n<option value='".$var."'>".$num."</option>";
1537       }
1538     }
1539     $output.=  "</select></td></tr></table></div>";
1540   }else{
1541     $output.= "</div>";
1542   }
1544   return($output);
1548 function apply_filter()
1550   $apply= "";
1552   $apply= ''.
1553     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1554     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1556   return ($apply);
1560 function back_to_main()
1562   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1563     msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1565   return ($string);
1569 function normalize_netmask($netmask)
1571   /* Check for notation of netmask */
1572   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1573     $num= (int)($netmask);
1574     $netmask= "";
1576     for ($byte= 0; $byte<4; $byte++){
1577       $result=0;
1579       for ($i= 7; $i>=0; $i--){
1580         if ($num-- > 0){
1581           $result+= pow(2,$i);
1582         }
1583       }
1585       $netmask.= $result.".";
1586     }
1588     return (preg_replace('/\.$/', '', $netmask));
1589   }
1591   return ($netmask);
1595 function netmask_to_bits($netmask)
1597   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1598   $res= 0;
1600   for ($n= 0; $n<4; $n++){
1601     $start= 255;
1602     $name= "nm$n";
1604     for ($i= 0; $i<8; $i++){
1605       if ($start == (int)($$name)){
1606         $res+= 8 - $i;
1607         break;
1608       }
1609       $start-= pow(2,$i);
1610     }
1611   }
1613   return ($res);
1617 function recurse($rule, $variables)
1619   $result= array();
1621   if (!count($variables)){
1622     return array($rule);
1623   }
1625   reset($variables);
1626   $key= key($variables);
1627   $val= current($variables);
1628   unset ($variables[$key]);
1630   foreach($val as $possibility){
1631     $nrule= str_replace("{$key}", $possibility, $rule);
1632     $result= array_merge($result, recurse($nrule, $variables));
1633   }
1635   return ($result);
1639 function expand_id($rule, $attributes)
1641   /* Check for id rule */
1642   if(preg_match('/^id(:|#)\d+$/',$rule)){
1643     return (array("\{$rule}"));
1644   }
1646   /* Check for clean attribute */
1647   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1648     $rule= preg_replace('/^%/', '', $rule);
1649     $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
1650     return (array($val));
1651   }
1653   /* Check for attribute with parameters */
1654   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1655     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1656     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1657     $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
1658     $start= preg_replace ('/-.*$/', '', $param);
1659     $stop = preg_replace ('/^[^-]+-/', '', $param);
1661     /* Assemble results */
1662     $result= array();
1663     for ($i= $start; $i<= $stop; $i++){
1664       $result[]= substr($val, 0, $i);
1665     }
1666     return ($result);
1667   }
1669   echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
1670   return (array($rule));
1674 function gen_uids($rule, $attributes)
1676   global $config;
1678   /* Search for keys and fill the variables array with all 
1679      possible values for that key. */
1680   $part= "";
1681   $trigger= false;
1682   $stripped= "";
1683   $variables= array();
1685   for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
1687     if ($rule[$pos] == "{" ){
1688       $trigger= true;
1689       $part= "";
1690       continue;
1691     }
1693     if ($rule[$pos] == "}" ){
1694       $variables[$pos]= expand_id($part, $attributes);
1695       $stripped.= "{".$pos."}";
1696       $trigger= false;
1697       continue;
1698     }
1700     if ($trigger){
1701       $part.= $rule[$pos];
1702     } else {
1703       $stripped.= $rule[$pos];
1704     }
1705   }
1707   /* Recurse through all possible combinations */
1708   $proposed= recurse($stripped, $variables);
1710   /* Get list of used ID's */
1711   $used= array();
1712   $ldap= $config->get_ldap_link();
1713   $ldap->cd($config->current['BASE']);
1714   $ldap->search('(uid=*)');
1716   while($attrs= $ldap->fetch()){
1717     $used[]= $attrs['uid'][0];
1718   }
1720   /* Remove used uids and watch out for id tags */
1721   $ret= array();
1722   foreach($proposed as $uid){
1724     /* Check for id tag and modify uid if needed */
1725     if(preg_match('/\{id:\d+}/',$uid)){
1726       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1728       for ($i= 0, $p= pow(10,$size); $i < $p; $i++){
1729         $number= sprintf("%0".$size."d", $i);
1730         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1731         if (!in_array($res, $used)){
1732           $uid= $res;
1733           break;
1734         }
1735       }
1736     }
1738     if(preg_match('/\{id#\d+}/',$uid)){
1739       $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1741       while (true){
1742         mt_srand((double) microtime()*1000000);
1743         $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1744         $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1745         if (!in_array($res, $used)){
1746           $uid= $res;
1747           break;
1748         }
1749       }
1750     }
1752     /* Don't assign used ones */
1753     if (!in_array($uid, $used)){
1754       /* Add uid, but remove {} first. These are invalid anyway. */
1755       $ret[]= preg_replace('/[{}]/', '', $uid);
1756     }
1757   }
1759   return(array_unique($ret));
1763 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1764    Need to convert... */
1765 function to_byte($value) {
1766   $value= strtolower(trim($value));
1768   if(!is_numeric(substr($value, -1))) {
1770     switch(substr($value, -1)) {
1771       case 'g':
1772         $mult= 1073741824;
1773         break;
1774       case 'm':
1775         $mult= 1048576;
1776         break;
1777       case 'k':
1778         $mult= 1024;
1779         break;
1780     }
1782     return ($mult * (int)substr($value, 0, -1));
1783   } else {
1784     return $value;
1785   }
1789 function in_array_ics($value, $items)
1791         return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
1795 function generate_alphabet($count= 10)
1797   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1798   $alphabet= "";
1799   $c= 0;
1801   /* Fill cells with charaters */
1802   for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
1803     if ($c == 0){
1804       $alphabet.= "<tr>";
1805     }
1807     $ch = mb_substr($characters, $i, 1, "UTF8");
1808     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1809       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1811     if ($c++ == $count){
1812       $alphabet.= "</tr>";
1813       $c= 0;
1814     }
1815   }
1817   /* Fill remaining cells */
1818   while ($c++ <= $count){
1819     $alphabet.= "<td>&nbsp;</td>";
1820   }
1822   return ($alphabet);
1826 function validate($string)
1828   return (strip_tags(str_replace('\0', '', $string)));
1832 function get_gosa_version()
1834   global $svn_revision, $svn_path;
1836   /* Extract informations */
1837   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1839   /* Release or development? */
1840   if (preg_match('%/gosa/trunk/%', $svn_path)){
1841     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1842   } else {
1843     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1844     return (sprintf(_("GOsa $release"), $revision));
1845   }
1849 function rmdirRecursive($path, $followLinks=false) {
1850   $dir= opendir($path);
1851   while($entry= readdir($dir)) {
1852     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1853       unlink($path."/".$entry);
1854     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1855       rmdirRecursive($path."/".$entry);
1856     }
1857   }
1858   closedir($dir);
1859   return rmdir($path);
1863 function scan_directory($path,$sort_desc=false)
1865   $ret = false;
1867   /* is this a dir ? */
1868   if(is_dir($path)) {
1870     /* is this path a readable one */
1871     if(is_readable($path)){
1873       /* Get contents and write it into an array */   
1874       $ret = array();    
1876       $dir = opendir($path);
1878       /* Is this a correct result ?*/
1879       if($dir){
1880         while($fp = readdir($dir))
1881           $ret[]= $fp;
1882       }
1883     }
1884   }
1885   /* Sort array ascending , like scandir */
1886   sort($ret);
1888   /* Sort descending if parameter is sort_desc is set */
1889   if($sort_desc) {
1890     $ret = array_reverse($ret);
1891   }
1893   return($ret);
1897 function clean_smarty_compile_dir($directory)
1899   global $svn_revision;
1901   if(is_dir($directory) && is_readable($directory)) {
1902     // Set revision filename to REVISION
1903     $revision_file= $directory."/REVISION";
1905     /* Is there a stamp containing the current revision? */
1906     if(!file_exists($revision_file)) {
1907       // create revision file
1908       create_revision($revision_file, $svn_revision);
1909     } else {
1910       # check for "$config->...['CONFIG']/revision" and the
1911       # contents should match the revision number
1912       if(!compare_revision($revision_file, $svn_revision)){
1913         // If revision differs, clean compile directory
1914         foreach(scan_directory($directory) as $file) {
1915           if(($file==".")||($file=="..")) continue;
1916           if( is_file($directory."/".$file) &&
1917               is_writable($directory."/".$file)) {
1918             // delete file
1919             if(!unlink($directory."/".$file)) {
1920               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1921               // This should never be reached
1922             }
1923           } elseif(is_dir($directory."/".$file) &&
1924               is_writable($directory."/".$file)) {
1925             // Just recursively delete it
1926             rmdirRecursive($directory."/".$file);
1927           }
1928         }
1929         // We should now create a fresh revision file
1930         clean_smarty_compile_dir($directory);
1931       } else {
1932         // Revision matches, nothing to do
1933       }
1934     }
1935   } else {
1936     // Smarty compile dir is not accessible
1937     // (Smarty will warn about this)
1938   }
1942 function create_revision($revision_file, $revision)
1944   $result= false;
1946   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1947     if($fh= fopen($revision_file, "w")) {
1948       if(fwrite($fh, $revision)) {
1949         $result= true;
1950       }
1951     }
1952     fclose($fh);
1953   } else {
1954     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1955   }
1957   return $result;
1961 function compare_revision($revision_file, $revision)
1963   // false means revision differs
1964   $result= false;
1966   if(file_exists($revision_file) && is_readable($revision_file)) {
1967     // Open file
1968     if($fh= fopen($revision_file, "r")) {
1969       // Compare File contents with current revision
1970       if($revision == fread($fh, filesize($revision_file))) {
1971         $result= true;
1972       }
1973     } else {
1974       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1975     }
1976     // Close file
1977     fclose($fh);
1978   }
1980   return $result;
1984 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1986   return("<img src='progress.php?x=$width&amp;y=$height&amp;p=$percentage'>");
1990 function array_key_ics($ikey, $items)
1992   $tmp= array_change_key_case($items, CASE_LOWER);
1993   $ikey= strtolower($ikey);
1994   if (isset($tmp[$ikey])){
1995     return($tmp[$ikey]);
1996   }
1998   return ('');
2002 function array_differs($src, $dst)
2004   /* If the count is differing, the arrays differ */
2005   if (count ($src) != count ($dst)){
2006     return (TRUE);
2007   }
2009   return (count(array_diff($src, $dst)) != 0);
2013 function saveFilter($a_filter, $values)
2015   if (isset($_POST['regexit'])){
2016     $a_filter["regex"]= $_POST['regexit'];
2018     foreach($values as $type){
2019       if (isset($_POST[$type])) {
2020         $a_filter[$type]= "checked";
2021       } else {
2022         $a_filter[$type]= "";
2023       }
2024     }
2025   }
2027   /* React on alphabet links if needed */
2028   if (isset($_GET['search'])){
2029     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2030     if ($s == "**"){
2031       $s= "*";
2032     }
2033     $a_filter['regex']= $s;
2034   }
2036   return ($a_filter);
2040 /* Escape all LDAP filter relevant characters */
2041 function normalizeLdap($input)
2043   return (addcslashes($input, '()|'));
2047 /* Resturns the difference between to microtime() results in float  */
2048 function get_MicroTimeDiff($start , $stop)
2050   $a = split("\ ",$start);
2051   $b = split("\ ",$stop);
2053   $secs = $b[1] - $a[1];
2054   $msecs= $b[0] - $a[0]; 
2056   $ret = (float) ($secs+ $msecs);
2057   return($ret);
2061 function get_base_dir()
2063   global $BASE_DIR;
2065   return $BASE_DIR;
2069 function obj_is_readable($dn, $object, $attribute)
2071   global $ui;
2073   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2077 function obj_is_writable($dn, $object, $attribute)
2079   global $ui;
2081   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2085 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2087   /* Initialize variables */
2088   $ret  = array("count" => 0);  // Set count to 0
2089   $next = true;                 // if false, then skip next loops and return
2090   $cnt  = 0;                    // Current number of loops
2091   $max  = 100;                  // Just for security, prevent looops
2092   $ldap = NULL;                 // To check if created result a valid
2093   $keep = "";                   // save last failed parse string
2095   /* Check each parsed dn in ldap ? */
2096   if($config!==NULL && $verify_in_ldap){
2097     $ldap = $config->get_ldap_link();
2098   }
2100   /* Lets start */
2101   $called = false;
2102   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2104     $cnt ++;
2105     if(!preg_match("/,/",$dn)){
2106       $next = false;
2107     }
2108     $object = preg_replace("/[,].*$/","",$dn);
2109     $dn     = preg_replace("/^[^,]+,/","",$dn);
2111     $called = true;
2113     /* Check if current dn is valid */
2114     if($ldap!==NULL){
2115       $ldap->cd($dn);
2116       $ldap->cat($dn,array("dn"));
2117       if($ldap->count()){
2118         $ret[]  = $keep.$object;
2119         $keep   = "";
2120       }else{
2121         $keep  .= $object.",";
2122       }
2123     }else{
2124       $ret[]  = $keep.$object;
2125       $keep   = "";
2126     }
2127   }
2129   /* No dn was posted */
2130   if($cnt == 0 && !empty($dn)){
2131     $ret[] = $dn;
2132   }
2134   /* Append the rest */
2135   $test = $keep.$dn;
2136   if($called && !empty($test)){
2137     $ret[] = $keep.$dn;
2138   }
2139   $ret['count'] = count($ret) - 1;
2141   return($ret);
2145 function get_base_from_hook($dn, $attrib)
2147   global $config;
2149   if ($config->get_cfg_value("baseIdHook") != ""){
2150     
2151     /* Call hook script - if present */
2152     $command= $config->get_cfg_value("baseIdHook");
2154     if ($command != ""){
2155       $command.= " '".LDAP::fix($dn)."' $attrib";
2156       if (check_command($command)){
2157         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2158         exec($command, $output);
2159         if (preg_match("/^[0-9]+$/", $output[0])){
2160           return ($output[0]);
2161         } else {
2162           msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2163           return ($config->get_cfg_value("uidNumberBase"));
2164         }
2165       } else {
2166         msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2167         return ($config->get_cfg_value("uidNumberBase"));
2168       }
2170     } else {
2172       msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2173       return ($config->get_cfg_value("uidNumberBase"));
2175     }
2176   }
2180 function check_schema_version($class, $version)
2182   return preg_match("/\(v$version\)/", $class['DESC']);
2186 function check_schema($cfg,$rfc2307bis = FALSE)
2188   $messages= array();
2190   /* Get objectclasses */
2191   $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2192   $objectclasses = $ldap->get_objectclasses();
2193   if(count($objectclasses) == 0){
2194     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2195   }
2197   /* This is the default block used for each entry.
2198    *  to avoid unset indexes.
2199    */
2200   $def_check = array("REQUIRED_VERSION" => "0",
2201       "SCHEMA_FILES"     => array(),
2202       "CLASSES_REQUIRED" => array(),
2203       "STATUS"           => FALSE,
2204       "IS_MUST_HAVE"     => FALSE,
2205       "MSG"              => "",
2206       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2208   /* The gosa base schema */
2209   $checks['gosaObject'] = $def_check;
2210   $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2211   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2212   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2213   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2215   /* GOsa Account class */
2216   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.1";
2217   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2218   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2219   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2220   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2222   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2223   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2224   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2225   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2226   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2227   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2229   /* Some other checks */
2230   foreach(array(
2231         "gosaCacheEntry"        => array("version" => "2.6.1"),
2232         "gosaDepartment"        => array("version" => "2.6.1"),
2233         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2234         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2235         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2236         "gosaUserTemplate"      => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2237         "gosaMailAccount"       => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2238         "gosaProxyAccount"      => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2239         "gosaApplication"       => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2240         "gosaApplicationGroup"  => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2241         "GOhard"                => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2242         "gotoTerminal"          => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2243         "goServer"              => array("version" => "2.6.1","class" => "server","file" => "goserver.schema"),
2244         "goTerminalServer"      => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2245         "goShareServer"         => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2246         "goNtpServer"           => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2247         "goSyslogServer"        => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2248         "goLdapServer"          => array("version" => "2.6.1"),
2249         "goCupsServer"          => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2250         "goImapServer"          => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2251         "goKrbServer"           => array("version" => "2.6.1"),
2252         "goFaxServer"           => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2253         ) as $name => $values){
2255           $checks[$name] = $def_check;
2256           if(isset($values['version'])){
2257             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2258           }
2259           if(isset($values['file'])){
2260             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2261           }
2262           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2263         }
2264   foreach($checks as $name => $value){
2265     foreach($value['CLASSES_REQUIRED'] as $class){
2267       if(!isset($objectclasses[$name])){
2268         $checks[$name]['STATUS'] = FALSE;
2269         if($value['IS_MUST_HAVE']){
2270           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2271         }else{
2272           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2273         }
2274       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2275         $checks[$name]['STATUS'] = FALSE;
2277         if($value['IS_MUST_HAVE']){
2278           $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2279         }else{
2280           $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2281         }
2282       }else{
2283         $checks[$name]['STATUS'] = TRUE;
2284         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2285       }
2286     }
2287   }
2289   $tmp = $objectclasses;
2291   /* The gosa base schema */
2292   $checks['posixGroup'] = $def_check;
2293   $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2294   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2295   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2296   $checks['posixGroup']['STATUS']           = TRUE;
2297   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2298   $checks['posixGroup']['MSG']              = "";
2299   $checks['posixGroup']['INFO']             = "";
2301   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2302   if(isset($tmp['posixGroup'])){
2304     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2305       $checks['posixGroup']['STATUS']           = FALSE;
2306       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2307       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2308     }
2309     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2310       $checks['posixGroup']['STATUS']           = FALSE;
2311       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2312       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2313     }
2314   }
2316   return($checks);
2320 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2322   $tmp = array(
2323         "de_DE" => "German",
2324         "fr_FR" => "French",
2325         "it_IT" => "Italian",
2326         "es_ES" => "Spanish",
2327         "en_US" => "English",
2328         "nl_NL" => "Dutch",
2329         "pl_PL" => "Polish",
2330         #"sv_SE" => "Swedish",
2331         "zh_CN" => "Chinese",
2332         "vi_VN" => "Vietnamese",
2333         "ru_RU" => "Russian");
2334   
2335   $tmp2= array(
2336         "de_DE" => _("German"),
2337         "fr_FR" => _("French"),
2338         "it_IT" => _("Italian"),
2339         "es_ES" => _("Spanish"),
2340         "en_US" => _("English"),
2341         "nl_NL" => _("Dutch"),
2342         "pl_PL" => _("Polish"),
2343         #"sv_SE" => _("Swedish"),
2344         "zh_CN" => _("Chinese"),
2345         "vi_VN" => _("Vietnamese"),
2346         "ru_RU" => _("Russian"));
2348   $ret = array();
2349   if($languages_in_own_language){
2351     $old_lang = setlocale(LC_ALL, 0);
2353     /* If the locale wasn't correclty set before, there may be an incorrect
2354         locale returned. Something like this: 
2355           C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2356         Extract the locale name from this string and use it to restore old locale.
2357      */
2358     if(preg_match("/LC_CTYPE/",$old_lang)){
2359       $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2360     }
2361     
2362     foreach($tmp as $key => $name){
2363       $lang = $key.".UTF-8";
2364       setlocale(LC_ALL, $lang);
2365       if($strip_region_tag){
2366         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2367       }else{
2368         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2369       }
2370     }
2371     setlocale(LC_ALL, $old_lang);
2372   }else{
2373     foreach($tmp as $key => $name){
2374       if($strip_region_tag){
2375         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2376       }else{
2377         $ret[$key] = _($name);
2378       }
2379     }
2380   }
2381   return($ret);
2385 /* Returns contents of the given POST variable and check magic quotes settings */
2386 function get_post($name)
2388   if(!isset($_POST[$name])){
2389     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2390     return(FALSE);
2391   }
2392   if(get_magic_quotes_gpc()){
2393     return(stripcslashes($_POST[$name]));
2394   }else{
2395     return($_POST[$name]);
2396   }
2400 /* Return class name in correct case */
2401 function get_correct_class_name($cls)
2403   global $class_mapping;
2404   if(isset($class_mapping) && is_array($class_mapping)){
2405     foreach($class_mapping as $class => $file){
2406       if(preg_match("/^".$cls."$/i",$class)){
2407         return($class);
2408       }
2409     }
2410   }
2411   return(FALSE);
2415 // change_password, changes the Password, of the given dn
2416 function change_password ($dn, $password, $mode=0, $hash= "")
2418   global $config;
2419   $newpass= "";
2421   /* Convert to lower. Methods are lowercase */
2422   $hash= strtolower($hash);
2424   // Get all available encryption Methods
2426   // NON STATIC CALL :)
2427   $methods = new passwordMethod(session::get('config'));
2428   $available = $methods->get_available_methods();
2430   // read current password entry for $dn, to detect the encryption Method
2431   $ldap       = $config->get_ldap_link();
2432   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2433   $attrs      = $ldap->fetch ();
2435   /* Is ensure that clear passwords will stay clear */
2436   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2437     $hash = "clear";
2438   }
2440   // Detect the encryption Method
2441   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2443     /* Check for supported algorithm */
2444     mt_srand((double) microtime()*1000000);
2446     /* Extract used hash */
2447     if ($hash == ""){
2448       $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2449     } else {
2450       $test = new $available[$hash]($config,$dn);
2451       $test->set_hash($hash);
2452     }
2454   } else {
2455     // User MD5 by default
2456     $hash= "md5";
2457     $test = new  $available['md5']($config);
2458   }
2460   if($test instanceOf passwordMethod){
2462     $deactivated = $test->is_locked($config,$dn);
2464     /* Feed password backends with information */
2465     $test->dn= $dn;
2466     $test->attrs= $attrs;
2467     $newpass= $test->generate_hash($password);
2469     // Update shadow timestamp?
2470     if (isset($attrs["shadowLastChange"][0])){
2471       $shadow= (int)(date("U") / 86400);
2472     } else {
2473       $shadow= 0;
2474     }
2476     // Write back modified entry
2477     $ldap->cd($dn);
2478     $attrs= array();
2480     // Not for groups
2481     if ($mode == 0){
2483       if ($shadow != 0){
2484         $attrs['shadowLastChange']= $shadow;
2485       }
2487       // Create SMB Password
2488       $attrs= generate_smb_nt_hash($password);
2489     }
2491     $attrs['userPassword']= array();
2492     $attrs['userPassword']= $newpass;
2494     $ldap->modify($attrs);
2496     /* Read ! if user was deactivated */
2497     if($deactivated){
2498       $test->lock_account($config,$dn);
2499     }
2501     new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2503     if (!$ldap->success()) {
2504       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2505     } else {
2507       /* Run backend method for change/create */
2508       if(!$test->set_password($password)){
2509         return(FALSE);
2510       }
2512       /* Find postmodify entries for this class */
2513       $command= $config->search("password", "POSTMODIFY",array('menu'));
2515       if ($command != ""){
2516         /* Walk through attribute list */
2517         $command= preg_replace("/%userPassword/", $password, $command);
2518         $command= preg_replace("/%dn/", $dn, $command);
2520         if (check_command($command)){
2521           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2522           exec($command);
2523         } else {
2524           $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2525           msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2526         }
2527       }
2528     }
2529     return(TRUE);
2530   }
2534 // Return something like array['sambaLMPassword']= "lalla..."
2535 function generate_smb_nt_hash($password)
2537   global $config;
2539   # Try to use gosa-si?
2540   if ($config->get_cfg_value("gosaSupportURI") != ""){
2541         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2542     if (isset($res['XML']['HASH'])){
2543         $hash= $res['XML']['HASH'];
2544     } else {
2545       $hash= "";
2546     }
2548     if ($hash == "") {
2549       msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2550       return ("");
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);
2561     if ($hash == "") {
2562       msg_dialog::display(_("Configuration error"), sprintf(_("Cannot generate samba hash: running '%s' failed, check the 'sambaHashHook'!"),$config->get_cfg_value('sambaHashHook')), ERROR_DIALOG);
2563       return ("");
2564     }
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);
2786 function get_object_info()
2788   return(session::get('objectinfo'));
2791 function set_object_info($str = "")
2793   session::set('objectinfo',$str);
2797 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2798 ?>