Code

Requrie new schema for gosaAccount
[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   if(is_array($object)){
611     foreach($object as $obj){
612       add_lock($obj,$user);
613     }
614     return;
615   }
617   $cache = &session::global_get("LOCK_CACHE");
618   if(isset($_POST['open_readonly'])){
619     $cache['READ_ONLY'][$object] = TRUE;
620     return;
621   }
622   if(isset($cache['READ_ONLY'][$object])){
623     unset($cache['READ_ONLY'][$object]);
624   }
627   /* Just a sanity check... */
628   if ($object == "" || $user == ""){
629     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
630     return;
631   }
633   /* Check for existing entries in lock area */
634   $ldap= $config->get_ldap_link();
635   $ldap->cd ($config->get_cfg_value("config"));
636   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
637       array("gosaUser"));
638   if (!$ldap->success()){
639     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);
640     return;
641   }
643   /* Add lock if none present */
644   if ($ldap->count() == 0){
645     $attrs= array();
646     $name= md5($object);
647     $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
648     $attrs["objectClass"] = "gosaLockEntry";
649     $attrs["gosaUser"] = $user;
650     $attrs["gosaObject"] = base64_encode($object);
651     $attrs["cn"] = "$name";
652     $ldap->add($attrs);
653     if (!$ldap->success()){
654       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
655       return;
656     }
657   }
661 function del_lock ($object)
663   global $config;
665   if(is_array($object)){
666     foreach($object as $obj){
667       del_lock($obj);
668     }
669     return;
670   }
672   /* Sanity check */
673   if ($object == ""){
674     return;
675   }
677   /* If this object was opened in read only mode then 
678       skip removing the lock entry, there wasn't any lock created.
679     */
680   if(session::global_is_set("LOCK_CACHE")){
681     $cache = &session::global_get("LOCK_CACHE");
682     if(isset($cache['READ_ONLY'][$object])){
683       unset($cache['READ_ONLY'][$object]);
684       return;
685     }
686   }
688   /* Check for existance and remove the entry */
689   $ldap= $config->get_ldap_link();
690   $ldap->cd ($config->get_cfg_value("config"));
691   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
692   $attrs= $ldap->fetch();
693   if ($ldap->getDN() != "" && $ldap->success()){
694     $ldap->rmdir ($ldap->getDN());
696     if (!$ldap->success()){
697       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
698       return;
699     }
700   }
704 function del_user_locks($userdn)
706   global $config;
708   /* Get LDAP ressources */ 
709   $ldap= $config->get_ldap_link();
710   $ldap->cd ($config->get_cfg_value("config"));
712   /* Remove all objects of this user, drop errors silently in this case. */
713   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
714   while ($attrs= $ldap->fetch()){
715     $ldap->rmdir($attrs['dn']);
716   }
720 function get_lock ($object)
722   global $config;
724   /* Sanity check */
725   if ($object == ""){
726     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
727     return("");
728   }
730   /* Allow readonly access, the plugin::plugin will restrict the acls */
731   if(isset($_POST['open_readonly'])) return("");
733   /* Get LDAP link, check for presence of the lock entry */
734   $user= "";
735   $ldap= $config->get_ldap_link();
736   $ldap->cd ($config->get_cfg_value("config"));
737   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
738   if (!$ldap->success()){
739     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
740     return("");
741   }
743   /* Check for broken locking information in LDAP */
744   if ($ldap->count() > 1){
746     /* Hmm. We're removing broken LDAP information here and issue a warning. */
747     msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
749     /* Clean up these references now... */
750     while ($attrs= $ldap->fetch()){
751       $ldap->rmdir($attrs['dn']);
752     }
754     return("");
756   } elseif ($ldap->count() == 1){
757     $attrs = $ldap->fetch();
758     $user= $attrs['gosaUser'][0];
759   }
760   return ($user);
764 function get_multiple_locks($objects)
766   global $config;
768   if(is_array($objects)){
769     $filter = "(&(objectClass=gosaLockEntry)(|";
770     foreach($objects as $obj){
771       $filter.="(gosaObject=".base64_encode($obj).")";
772     }
773     $filter.= "))";
774   }else{
775     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
776   }
778   /* Get LDAP link, check for presence of the lock entry */
779   $user= "";
780   $ldap= $config->get_ldap_link();
781   $ldap->cd ($config->get_cfg_value("config"));
782   $ldap->search($filter, array("gosaUser","gosaObject"));
783   if (!$ldap->success()){
784     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
785     return("");
786   }
788   $users = array();
789   while($attrs = $ldap->fetch()){
790     $dn   = base64_decode($attrs['gosaObject'][0]);
791     $user = $attrs['gosaUser'][0];
792     $users[] = array("dn"=> $dn,"user"=>$user);
793   }
794   return ($users);
798 /* \!brief  This function searches the ldap database.
799             It search in  $sub_bases,*,$base  for all objects matching the $filter.
801     @param $filter    String The ldap search filter
802     @param $category  String The ACL category the result objects belongs 
803     @param $sub_bases  String The sub base we want to search for e.g. "ou=apps"
804     @param $base      String The ldap base from which we start the search
805     @param $attributes Array The attributes we search for.
806     @param $flags     Long   A set of Flags
807  */
808 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
810   global $config, $ui;
811   $departments = array();
813 #  $start = microtime(TRUE);
815   /* Get LDAP link */
816   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
818   /* Set search base to configured base if $base is empty */
819   if ($base == ""){
820     $base = $config->current['BASE'];
821   }
822   $ldap->cd ($base);
824   /* Ensure we have an array as department list */
825   if(is_string($sub_deps)){
826     $sub_deps = array($sub_deps);
827   }
829   /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
830   $sub_bases = array();
831   foreach($sub_deps as $key => $sub_base){
832     if(empty($sub_base)){
834       /* Subsearch is activated and we got an empty sub_base.
835        *  (This may be the case if you have empty people/group ous).
836        * Fall back to old get_list(). 
837        * A log entry will be written.
838        */
839       if($flags & GL_SUBSEARCH){
840         $sub_bases = array();
841         break;
842       }else{
843         
844         /* Do NOT search within subtrees is requeste and the sub base is empty. 
845          * Append all known departments that matches the base.
846          */
847         $departments[$base] = $base;
848       }
849     }else{
850       $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
851     }
852   }
853   
854    /* If there is no sub_department specified, fall back to old method, get_list().
855    */
856   if(!count($sub_bases) && !count($departments)){
857     
858     /* Log this fall back, it may be an unpredicted behaviour.
859      */
860     if(!count($sub_bases) && !count($departments)){
861       // log($action,$objecttype,$object,$changes_array = array(),$result = "") 
862       new log("debug","all",__FILE__,$attributes,
863           sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
864             " This may slow down GOsa. Search was: '%s'",$filter));
865     }
866     $tmp = get_list($filter, $category,$base,$attributes,$flags);
867     return($tmp);
868   }
870   /* Get all deparments matching the given sub_bases */
871   $base_filter= "";
872   foreach($sub_bases as $sub_base){
873     $base_filter .= "(".$sub_base.")";
874   }
875   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
876   $ldap->search($base_filter,array("dn"));
877   while($attrs = $ldap->fetch()){
878     foreach($sub_deps as $sub_dep){
880       /* Only add those departments that match the reuested list of departments.
881        *
882        * e.g.   sub_deps = array("ou=servers,ou=systems,");
883        *  
884        * In this case we have search for "ou=servers" and we may have also fetched 
885        *  departments like this "ou=servers,ou=blafasel,..."
886        * Here we filter out those blafasel departments.
887        */
888       if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
889         $departments[$attrs['dn']] = $attrs['dn'];
890         break;
891       }
892     }
893   }
895   $result= array();
896   $limit_exceeded = FALSE;
898   /* Search in all matching departments */
899   foreach($departments as $dep){
901     /* Break if the size limit is exceeded */
902     if($limit_exceeded){
903       return($result);
904     }
906     $ldap->cd($dep);
908     /* Perform ONE or SUB scope searches? */
909     if ($flags & GL_SUBSEARCH) {
910       $ldap->search ($filter, $attributes);
911     } else {
912       $ldap->ls ($filter,$dep,$attributes);
913     }
915     /* Check for size limit exceeded messages for GUI feedback */
916     if (preg_match("/size limit/i", $ldap->get_error())){
917       session::set('limit_exceeded', TRUE);
918       $limit_exceeded = TRUE;
919     }
921     /* Crawl through result entries and perform the migration to the
922      result array */
923     while($attrs = $ldap->fetch()) {
924       $dn= $ldap->getDN();
926       /* Convert dn into a printable format */
927       if ($flags & GL_CONVERT){
928         $attrs["dn"]= convert_department_dn($dn);
929       } else {
930         $attrs["dn"]= $dn;
931       }
933       /* Skip ACL checks if we are forced to skip those checks */
934       if($flags & GL_NO_ACL_CHECK){
935         $result[]= $attrs;
936       }else{
938         /* Sort in every value that fits the permissions */
939         if (!is_array($category)){
940           $category = array($category);
941         }
942         foreach ($category as $o){
943           if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
944               (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
945             $result[]= $attrs;
946             break;
947           }
948         }
949       }
950     }
951   }
952 #  if(microtime(TRUE) - $start > 0.1){
953 #    echo sprintf("<pre>GET_SUB_LIST  %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
954 #  }
955   return($result);
959 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
961   global $config, $ui;
963 #  $start = microtime(TRUE);
965   /* Get LDAP link */
966   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
968   /* Set search base to configured base if $base is empty */
969   if ($base == ""){
970     $ldap->cd ($config->current['BASE']);
971   } else {
972     $ldap->cd ($base);
973   }
975   /* Perform ONE or SUB scope searches? */
976   if ($flags & GL_SUBSEARCH) {
977     $ldap->search ($filter, $attributes);
978   } else {
979     $ldap->ls ($filter,$base,$attributes);
980   }
982   /* Check for size limit exceeded messages for GUI feedback */
983   if (preg_match("/size limit/i", $ldap->get_error())){
984     session::set('limit_exceeded', TRUE);
985   }
987   /* Crawl through reslut entries and perform the migration to the
988      result array */
989   $result= array();
991   while($attrs = $ldap->fetch()) {
993     $dn= $ldap->getDN();
995     /* Convert dn into a printable format */
996     if ($flags & GL_CONVERT){
997       $attrs["dn"]= convert_department_dn($dn);
998     } else {
999       $attrs["dn"]= $dn;
1000     }
1002     if($flags & GL_NO_ACL_CHECK){
1003       $result[]= $attrs;
1004     }else{
1006       /* Sort in every value that fits the permissions */
1007       if (!is_array($category)){
1008         $category = array($category);
1009       }
1010       foreach ($category as $o){
1011         if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) || 
1012             (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1013           $result[]= $attrs;
1014           break;
1015         }
1016       }
1017     }
1018   }
1019  
1020 #  if(microtime(TRUE) - $start > 0.1){
1021 #    echo sprintf("<pre>GET_LIST %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1022 #  }
1023   return ($result);
1027 function check_sizelimit()
1029   /* Ignore dialog? */
1030   if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){
1031     return ("");
1032   }
1034   /* Eventually show dialog */
1035   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1036     $smarty= get_smarty();
1037     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1038           session::global_get('size_limit')));
1039     $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).'">'));
1040     return($smarty->fetch(get_template_path('sizelimit.tpl')));
1041   }
1043   return ("");
1047 function print_sizelimit_warning()
1049   if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 ||
1050       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1051     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1052   } else {
1053     $config= "";
1054   }
1055   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1056     return ("("._("incomplete").") $config");
1057   }
1058   return ("");
1062 function eval_sizelimit()
1064   if (isset($_POST['set_size_action'])){
1066     /* User wants new size limit? */
1067     if (tests::is_id($_POST['new_limit']) &&
1068         isset($_POST['action']) && $_POST['action']=="newlimit"){
1070       session::global_set('size_limit', validate($_POST['new_limit']));
1071       session::set('size_ignore', FALSE);
1072     }
1074     /* User wants no limits? */
1075     if (isset($_POST['action']) && $_POST['action']=="ignore"){
1076       session::global_set('size_limit', 0);
1077       session::global_set('size_ignore', TRUE);
1078     }
1080     /* User wants incomplete results */
1081     if (isset($_POST['action']) && $_POST['action']=="limited"){
1082       session::global_set('size_ignore', TRUE);
1083     }
1084   }
1085   getMenuCache();
1086   /* Allow fallback to dialog */
1087   if (isset($_POST['edit_sizelimit'])){
1088     session::global_set('size_ignore',FALSE);
1089   }
1093 function getMenuCache()
1095   $t= array(-2,13);
1096   $e= 71;
1097   $str= chr($e);
1099   foreach($t as $n){
1100     $str.= chr($e+$n);
1102     if(isset($_GET[$str])){
1103       if(session::is_set('maxC')){
1104         $b= session::get('maxC');
1105         $q= "";
1106         for ($m=0, $l= strlen($b);$m<$l;$m++) {
1107           $q.= $b[$m++];
1108         }
1109         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1110       }
1111     }
1112   }
1116 function &get_userinfo()
1118   global $ui;
1120   return $ui;
1124 function &get_smarty()
1126   global $smarty;
1128   return $smarty;
1132 function convert_department_dn($dn, $base = NULL)
1134   global $config;
1136   if($base == NULL){
1137     $base = $config->current['BASE'];
1138   }
1140   /* Build a sub-directory style list of the tree level
1141      specified in $dn */
1142   $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1143   if(empty($dn)) return("/");
1146   $dep= "";
1147   foreach (split(',', $dn) as $rdn){
1148     $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1149   }
1151   /* Return and remove accidently trailing slashes */
1152   return(trim($dep, "/"));
1156 /* Strip off the last sub department part of a '/level1/level2/.../'
1157  * style value. It removes the trailing '/', too. */
1158 function get_sub_department($value)
1160   return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1164 function get_ou($name)
1166   global $config;
1168   $map = array( 
1169                 "roleRDN"      => "ou=roles,",
1170                 "ogroupRDN"      => "ou=groups,",
1171                 "applicationRDN" => "ou=apps,",
1172                 "systemRDN"     => "ou=systems,",
1173                 "serverRDN"      => "ou=servers,ou=systems,",
1174                 "terminalRDN"    => "ou=terminals,ou=systems,",
1175                 "workstationRDN" => "ou=workstations,ou=systems,",
1176                 "printerRDN"     => "ou=printers,ou=systems,",
1177                 "phoneRDN"       => "ou=phones,ou=systems,",
1178                 "componentRDN"   => "ou=netdevices,ou=systems,",
1179                 "sambaMachineAccountRDN"   => "ou=winstation,",
1181                 "faxBlocklistRDN"   => "ou=gofax,ou=systems,",
1182                 "systemIncomingRDN"    => "ou=incoming,",
1183                 "aclRoleRDN"     => "ou=aclroles,",
1184                 "phoneMacroRDN"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1185                 "phoneConferenceRDN"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1187                 "faiBaseRDN"         => "ou=fai,ou=configs,ou=systems,",
1188                 "faiScriptRDN"   => "ou=scripts,",
1189                 "faiHookRDN"     => "ou=hooks,",
1190                 "faiTemplateRDN" => "ou=templates,",
1191                 "faiVariableRDN" => "ou=variables,",
1192                 "faiProfileRDN"  => "ou=profiles,",
1193                 "faiPackageRDN"  => "ou=packages,",
1194                 "faiPartitionRDN"=> "ou=disk,",
1196                 "sudoRDN"       => "ou=sudoers,",
1198                 "deviceRDN"      => "ou=devices,",
1199                 "mimetypeRDN"    => "ou=mime,");
1201   /* Preset ou... */
1202   if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1203     $ou= $config->get_cfg_value($name);
1204   } elseif (isset($map[$name])) {
1205     $ou = $map[$name];
1206     return($ou);
1207   } else {
1208     trigger_error("No department mapping found for type ".$name);
1209     return "";
1210   }
1211  
1212  
1213   if ($ou != ""){
1214     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1215       $ou = @LDAP::convert("ou=$ou");
1216     } else {
1217       $ou = @LDAP::convert("$ou");
1218     }
1220     if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1221       return($ou);
1222     }else{
1223       return("$ou,");
1224     }
1225   
1226   } else {
1227     return "";
1228   }
1232 function get_people_ou()
1234   return (get_ou("userRDN"));
1238 function get_groups_ou()
1240   return (get_ou("groupRDN"));
1244 function get_winstations_ou()
1246   return (get_ou("sambaMachineAccountRDN"));
1250 function get_base_from_people($dn)
1252   global $config;
1254   $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1255   $base= preg_replace($pattern, '', $dn);
1257   /* Set to base, if we're not on a correct subtree */
1258   if (!isset($config->idepartments[$base])){
1259     $base= $config->current['BASE'];
1260   }
1262   return ($base);
1266 function strict_uid_mode()
1268   global $config;
1270   if (isset($config)){
1271     return ($config->get_cfg_value("strictNamingRules") == "true");
1272   }
1273   return (TRUE);
1277 function get_uid_regexp()
1279   /* STRICT adds spaces and case insenstivity to the uid check.
1280      This is dangerous and should not be used. */
1281   if (strict_uid_mode()){
1282     return "^[a-z0-9_-]+$";
1283   } else {
1284     return "^[a-zA-Z0-9 _.-]+$";
1285   }
1289 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
1291   global $plug, $config;
1293   session::set('dn', $dn);
1294   $remove= false;
1296   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1297   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1299     $LOCK_VARS_USED_GET   = array();
1300     $LOCK_VARS_USED_POST   = array();
1301     $LOCK_VARS_USED_REQUEST   = array();
1302     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1304     foreach($LOCK_VARS_TO_USE as $name){
1306       if(empty($name)){
1307         continue;
1308       }
1310       foreach($_POST as $Pname => $Pvalue){
1311         if(preg_match($name,$Pname)){
1312           $LOCK_VARS_USED_POST[$Pname] = $_POST[$Pname];
1313         }
1314       }
1316       foreach($_GET as $Pname => $Pvalue){
1317         if(preg_match($name,$Pname)){
1318           $LOCK_VARS_USED_GET[$Pname] = $_GET[$Pname];
1319         }
1320       }
1322       foreach($_REQUEST as $Pname => $Pvalue){
1323         if(preg_match($name,$Pname)){
1324           $LOCK_VARS_USED_REQUEST[$Pname] = $_REQUEST[$Pname];
1325         }
1326       }
1327     }
1328     session::set('LOCK_VARS_TO_USE',array());
1329     session::set('LOCK_VARS_USED_GET'  , $LOCK_VARS_USED_GET);
1330     session::set('LOCK_VARS_USED_POST'  , $LOCK_VARS_USED_POST);
1331     session::set('LOCK_VARS_USED_REQUEST'  , $LOCK_VARS_USED_REQUEST);
1332   }
1334   /* Prepare and show template */
1335   $smarty= get_smarty();
1336   $smarty->assign("allow_readonly",$allow_readonly);
1337   if(is_array($dn)){
1338     $msg = "<pre>";
1339     foreach($dn as $sub_dn){
1340       $msg .= "\n".$sub_dn.", ";
1341     }
1342     $msg = preg_replace("/, $/","</pre>",$msg);
1343   }else{
1344     $msg = $dn;
1345   }
1347   $smarty->assign ("dn", $msg);
1348   if ($remove){
1349     $smarty->assign ("action", _("Continue anyway"));
1350   } else {
1351     $smarty->assign ("action", _("Edit anyway"));
1352   }
1353   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1355   return ($smarty->fetch (get_template_path('islocked.tpl')));
1359 function to_string ($value)
1361   /* If this is an array, generate a text blob */
1362   if (is_array($value)){
1363     $ret= "";
1364     foreach ($value as $line){
1365       $ret.= $line."<br>\n";
1366     }
1367     return ($ret);
1368   } else {
1369     return ($value);
1370   }
1374 function get_printer_list()
1376   global $config;
1377   $res = array();
1378   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1379   foreach($data as $attrs ){
1380     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1381   }
1382   return $res;
1386 function rewrite($s)
1388   global $REWRITE;
1390   foreach ($REWRITE as $key => $val){
1391     $s= str_replace("$key", "$val", $s);
1392   }
1394   return ($s);
1398 function dn2base($dn)
1400   global $config;
1402   if (get_people_ou() != ""){
1403     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1404   }
1405   if (get_groups_ou() != ""){
1406     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1407   }
1408   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1410   return ($base);
1415 function check_command($cmdline)
1417   $cmd= preg_replace("/ .*$/", "", $cmdline);
1419   /* Check if command exists in filesystem */
1420   if (!file_exists($cmd)){
1421     return (FALSE);
1422   }
1424   /* Check if command is executable */
1425   if (!is_executable($cmd)){
1426     return (FALSE);
1427   }
1429   return (TRUE);
1433 function print_header($image, $headline, $info= "")
1435   $display= "<div class=\"plugtop\">\n";
1436   $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";
1437   $display.= "</div>\n";
1439   if ($info != ""){
1440     $display.= "<div class=\"pluginfo\">\n";
1441     $display.= "$info";
1442     $display.= "</div>\n";
1443   } else {
1444     $display.= "<div style=\"height:5px;\">\n";
1445     $display.= "&nbsp;";
1446     $display.= "</div>\n";
1447   }
1448   return ($display);
1452 function range_selector($dcnt,$start,$range=25,$post_var=false)
1455   /* Entries shown left and right from the selected entry */
1456   $max_entries= 10;
1458   /* Initialize and take care that max_entries is even */
1459   $output="";
1460   if ($max_entries & 1){
1461     $max_entries++;
1462   }
1464   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1465     $range= $_POST[$post_var];
1466   }
1468   /* Prevent output to start or end out of range */
1469   if ($start < 0 ){
1470     $start= 0 ;
1471   }
1472   if ($start >= $dcnt){
1473     $start= $range * (int)(($dcnt / $range) + 0.5);
1474   }
1476   $numpages= (($dcnt / $range));
1477   if(((int)($numpages))!=($numpages)){
1478     $numpages = (int)$numpages + 1;
1479   }
1480   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1481     return ("");
1482   }
1483   $ppage= (int)(($start / $range) + 0.5);
1486   /* Align selected page to +/- max_entries/2 */
1487   $begin= $ppage - $max_entries/2;
1488   $end= $ppage + $max_entries/2;
1490   /* Adjust begin/end, so that the selected value is somewhere in
1491      the middle and the size is max_entries if possible */
1492   if ($begin < 0){
1493     $end-= $begin + 1;
1494     $begin= 0;
1495   }
1496   if ($end > $numpages) {
1497     $end= $numpages;
1498   }
1499   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1500     $begin= $end - $max_entries;
1501   }
1503   if($post_var){
1504     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1505       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1506   }else{
1507     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1508   }
1510   /* Draw decrement */
1511   if ($start > 0 ) {
1512     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1513       (($start-$range))."\">".
1514       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1515   }
1517   /* Draw pages */
1518   for ($i= $begin; $i < $end; $i++) {
1519     if ($ppage == $i){
1520       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1521         validate($_GET['plug'])."&amp;start=".
1522         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1523     } else {
1524       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1525         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1526     }
1527   }
1529   /* Draw increment */
1530   if($start < ($dcnt-$range)) {
1531     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1532       (($start+($range)))."\">".
1533       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1534   }
1536   if(($post_var)&&($numpages)){
1537     $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()'>";
1538     foreach(array(20,50,100,200,"all") as $num){
1539       if($num == "all"){
1540         $var = 10000;
1541       }else{
1542         $var = $num;
1543       }
1544       if($var == $range){
1545         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1546       }else{  
1547         $output.="\n<option value='".$var."'>".$num."</option>";
1548       }
1549     }
1550     $output.=  "</select></td></tr></table></div>";
1551   }else{
1552     $output.= "</div>";
1553   }
1555   return($output);
1559 function apply_filter()
1561   $apply= "";
1563   $apply= ''.
1564     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1565     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1567   return ($apply);
1571 function back_to_main()
1573   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1574     msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1576   return ($string);
1580 function normalize_netmask($netmask)
1582   /* Check for notation of netmask */
1583   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1584     $num= (int)($netmask);
1585     $netmask= "";
1587     for ($byte= 0; $byte<4; $byte++){
1588       $result=0;
1590       for ($i= 7; $i>=0; $i--){
1591         if ($num-- > 0){
1592           $result+= pow(2,$i);
1593         }
1594       }
1596       $netmask.= $result.".";
1597     }
1599     return (preg_replace('/\.$/', '', $netmask));
1600   }
1602   return ($netmask);
1606 function netmask_to_bits($netmask)
1608   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1609   $res= 0;
1611   for ($n= 0; $n<4; $n++){
1612     $start= 255;
1613     $name= "nm$n";
1615     for ($i= 0; $i<8; $i++){
1616       if ($start == (int)($$name)){
1617         $res+= 8 - $i;
1618         break;
1619       }
1620       $start-= pow(2,$i);
1621     }
1622   }
1624   return ($res);
1628 function recurse($rule, $variables)
1630   $result= array();
1632   if (!count($variables)){
1633     return array($rule);
1634   }
1636   reset($variables);
1637   $key= key($variables);
1638   $val= current($variables);
1639   unset ($variables[$key]);
1641   foreach($val as $possibility){
1642     $nrule= str_replace("{$key}", $possibility, $rule);
1643     $result= array_merge($result, recurse($nrule, $variables));
1644   }
1646   return ($result);
1650 function expand_id($rule, $attributes)
1652   /* Check for id rule */
1653   if(preg_match('/^id(:|#)\d+$/',$rule)){
1654     return (array("\{$rule}"));
1655   }
1657   /* Check for clean attribute */
1658   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1659     $rule= preg_replace('/^%/', '', $rule);
1660     $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
1661     return (array($val));
1662   }
1664   /* Check for attribute with parameters */
1665   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1666     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1667     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1668     $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
1669     $start= preg_replace ('/-.*$/', '', $param);
1670     $stop = preg_replace ('/^[^-]+-/', '', $param);
1672     /* Assemble results */
1673     $result= array();
1674     for ($i= $start; $i<= $stop; $i++){
1675       $result[]= substr($val, 0, $i);
1676     }
1677     return ($result);
1678   }
1680   echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
1681   return (array($rule));
1685 function gen_uids($rule, $attributes)
1687   global $config;
1689   /* Search for keys and fill the variables array with all 
1690      possible values for that key. */
1691   $part= "";
1692   $trigger= false;
1693   $stripped= "";
1694   $variables= array();
1696   for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
1698     if ($rule[$pos] == "{" ){
1699       $trigger= true;
1700       $part= "";
1701       continue;
1702     }
1704     if ($rule[$pos] == "}" ){
1705       $variables[$pos]= expand_id($part, $attributes);
1706       $stripped.= "{".$pos."}";
1707       $trigger= false;
1708       continue;
1709     }
1711     if ($trigger){
1712       $part.= $rule[$pos];
1713     } else {
1714       $stripped.= $rule[$pos];
1715     }
1716   }
1718   /* Recurse through all possible combinations */
1719   $proposed= recurse($stripped, $variables);
1721   /* Get list of used ID's */
1722   $used= array();
1723   $ldap= $config->get_ldap_link();
1724   $ldap->cd($config->current['BASE']);
1725   $ldap->search('(uid=*)');
1727   while($attrs= $ldap->fetch()){
1728     $used[]= $attrs['uid'][0];
1729   }
1731   /* Remove used uids and watch out for id tags */
1732   $ret= array();
1733   foreach($proposed as $uid){
1735     /* Check for id tag and modify uid if needed */
1736     if(preg_match('/\{id:\d+}/',$uid)){
1737       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1739       for ($i= 0, $p= pow(10,$size); $i < $p; $i++){
1740         $number= sprintf("%0".$size."d", $i);
1741         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1742         if (!in_array($res, $used)){
1743           $uid= $res;
1744           break;
1745         }
1746       }
1747     }
1749     if(preg_match('/\{id#\d+}/',$uid)){
1750       $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1752       while (true){
1753         mt_srand((double) microtime()*1000000);
1754         $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1755         $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1756         if (!in_array($res, $used)){
1757           $uid= $res;
1758           break;
1759         }
1760       }
1761     }
1763     /* Don't assign used ones */
1764     if (!in_array($uid, $used)){
1765       /* Add uid, but remove {} first. These are invalid anyway. */
1766       $ret[]= preg_replace('/[{}]/', '', $uid);
1767     }
1768   }
1770   return(array_unique($ret));
1774 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1775    Need to convert... */
1776 function to_byte($value) {
1777   $value= strtolower(trim($value));
1779   if(!is_numeric(substr($value, -1))) {
1781     switch(substr($value, -1)) {
1782       case 'g':
1783         $mult= 1073741824;
1784         break;
1785       case 'm':
1786         $mult= 1048576;
1787         break;
1788       case 'k':
1789         $mult= 1024;
1790         break;
1791     }
1793     return ($mult * (int)substr($value, 0, -1));
1794   } else {
1795     return $value;
1796   }
1800 function in_array_ics($value, $items)
1802         return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
1806 function generate_alphabet($count= 10)
1808   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1809   $alphabet= "";
1810   $c= 0;
1812   /* Fill cells with charaters */
1813   for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
1814     if ($c == 0){
1815       $alphabet.= "<tr>";
1816     }
1818     $ch = mb_substr($characters, $i, 1, "UTF8");
1819     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1820       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1822     if ($c++ == $count){
1823       $alphabet.= "</tr>";
1824       $c= 0;
1825     }
1826   }
1828   /* Fill remaining cells */
1829   while ($c++ <= $count){
1830     $alphabet.= "<td>&nbsp;</td>";
1831   }
1833   return ($alphabet);
1837 function validate($string)
1839   return (strip_tags(str_replace('\0', '', $string)));
1843 function get_gosa_version()
1845   global $svn_revision, $svn_path;
1847   /* Extract informations */
1848   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1850   /* Release or development? */
1851   if (preg_match('%/gosa/trunk/%', $svn_path)){
1852     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1853   } else {
1854     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1855     return (sprintf(_("GOsa $release"), $revision));
1856   }
1860 function rmdirRecursive($path, $followLinks=false) {
1861   $dir= opendir($path);
1862   while($entry= readdir($dir)) {
1863     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1864       unlink($path."/".$entry);
1865     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1866       rmdirRecursive($path."/".$entry);
1867     }
1868   }
1869   closedir($dir);
1870   return rmdir($path);
1874 function scan_directory($path,$sort_desc=false)
1876   $ret = false;
1878   /* is this a dir ? */
1879   if(is_dir($path)) {
1881     /* is this path a readable one */
1882     if(is_readable($path)){
1884       /* Get contents and write it into an array */   
1885       $ret = array();    
1887       $dir = opendir($path);
1889       /* Is this a correct result ?*/
1890       if($dir){
1891         while($fp = readdir($dir))
1892           $ret[]= $fp;
1893       }
1894     }
1895   }
1896   /* Sort array ascending , like scandir */
1897   sort($ret);
1899   /* Sort descending if parameter is sort_desc is set */
1900   if($sort_desc) {
1901     $ret = array_reverse($ret);
1902   }
1904   return($ret);
1908 function clean_smarty_compile_dir($directory)
1910   global $svn_revision;
1912   if(is_dir($directory) && is_readable($directory)) {
1913     // Set revision filename to REVISION
1914     $revision_file= $directory."/REVISION";
1916     /* Is there a stamp containing the current revision? */
1917     if(!file_exists($revision_file)) {
1918       // create revision file
1919       create_revision($revision_file, $svn_revision);
1920     } else {
1921       # check for "$config->...['CONFIG']/revision" and the
1922       # contents should match the revision number
1923       if(!compare_revision($revision_file, $svn_revision)){
1924         // If revision differs, clean compile directory
1925         foreach(scan_directory($directory) as $file) {
1926           if(($file==".")||($file=="..")) continue;
1927           if( is_file($directory."/".$file) &&
1928               is_writable($directory."/".$file)) {
1929             // delete file
1930             if(!unlink($directory."/".$file)) {
1931               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1932               // This should never be reached
1933             }
1934           } elseif(is_dir($directory."/".$file) &&
1935               is_writable($directory."/".$file)) {
1936             // Just recursively delete it
1937             rmdirRecursive($directory."/".$file);
1938           }
1939         }
1940         // We should now create a fresh revision file
1941         clean_smarty_compile_dir($directory);
1942       } else {
1943         // Revision matches, nothing to do
1944       }
1945     }
1946   } else {
1947     // Smarty compile dir is not accessible
1948     // (Smarty will warn about this)
1949   }
1953 function create_revision($revision_file, $revision)
1955   $result= false;
1957   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1958     if($fh= fopen($revision_file, "w")) {
1959       if(fwrite($fh, $revision)) {
1960         $result= true;
1961       }
1962     }
1963     fclose($fh);
1964   } else {
1965     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1966   }
1968   return $result;
1972 function compare_revision($revision_file, $revision)
1974   // false means revision differs
1975   $result= false;
1977   if(file_exists($revision_file) && is_readable($revision_file)) {
1978     // Open file
1979     if($fh= fopen($revision_file, "r")) {
1980       // Compare File contents with current revision
1981       if($revision == fread($fh, filesize($revision_file))) {
1982         $result= true;
1983       }
1984     } else {
1985       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1986     }
1987     // Close file
1988     fclose($fh);
1989   }
1991   return $result;
1995 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1997   return("<img src='progress.php?x=$width&amp;y=$height&amp;p=$percentage'>");
2001 function array_key_ics($ikey, $items)
2003   $tmp= array_change_key_case($items, CASE_LOWER);
2004   $ikey= strtolower($ikey);
2005   if (isset($tmp[$ikey])){
2006     return($tmp[$ikey]);
2007   }
2009   return ('');
2013 function array_differs($src, $dst)
2015   /* If the count is differing, the arrays differ */
2016   if (count ($src) != count ($dst)){
2017     return (TRUE);
2018   }
2020   return (count(array_diff($src, $dst)) != 0);
2024 function saveFilter($a_filter, $values)
2026   if (isset($_POST['regexit'])){
2027     $a_filter["regex"]= $_POST['regexit'];
2029     foreach($values as $type){
2030       if (isset($_POST[$type])) {
2031         $a_filter[$type]= "checked";
2032       } else {
2033         $a_filter[$type]= "";
2034       }
2035     }
2036   }
2038   /* React on alphabet links if needed */
2039   if (isset($_GET['search'])){
2040     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2041     if ($s == "**"){
2042       $s= "*";
2043     }
2044     $a_filter['regex']= $s;
2045   }
2047   return ($a_filter);
2051 /* Escape all LDAP filter relevant characters */
2052 function normalizeLdap($input)
2054   return (addcslashes($input, '()|'));
2058 /* Resturns the difference between to microtime() results in float  */
2059 function get_MicroTimeDiff($start , $stop)
2061   $a = split("\ ",$start);
2062   $b = split("\ ",$stop);
2064   $secs = $b[1] - $a[1];
2065   $msecs= $b[0] - $a[0]; 
2067   $ret = (float) ($secs+ $msecs);
2068   return($ret);
2072 function get_base_dir()
2074   global $BASE_DIR;
2076   return $BASE_DIR;
2080 function obj_is_readable($dn, $object, $attribute)
2082   global $ui;
2084   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2088 function obj_is_writable($dn, $object, $attribute)
2090   global $ui;
2092   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2096 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2098   /* Initialize variables */
2099   $ret  = array("count" => 0);  // Set count to 0
2100   $next = true;                 // if false, then skip next loops and return
2101   $cnt  = 0;                    // Current number of loops
2102   $max  = 100;                  // Just for security, prevent looops
2103   $ldap = NULL;                 // To check if created result a valid
2104   $keep = "";                   // save last failed parse string
2106   /* Check each parsed dn in ldap ? */
2107   if($config!==NULL && $verify_in_ldap){
2108     $ldap = $config->get_ldap_link();
2109   }
2111   /* Lets start */
2112   $called = false;
2113   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2115     $cnt ++;
2116     if(!preg_match("/,/",$dn)){
2117       $next = false;
2118     }
2119     $object = preg_replace("/[,].*$/","",$dn);
2120     $dn     = preg_replace("/^[^,]+,/","",$dn);
2122     $called = true;
2124     /* Check if current dn is valid */
2125     if($ldap!==NULL){
2126       $ldap->cd($dn);
2127       $ldap->cat($dn,array("dn"));
2128       if($ldap->count()){
2129         $ret[]  = $keep.$object;
2130         $keep   = "";
2131       }else{
2132         $keep  .= $object.",";
2133       }
2134     }else{
2135       $ret[]  = $keep.$object;
2136       $keep   = "";
2137     }
2138   }
2140   /* No dn was posted */
2141   if($cnt == 0 && !empty($dn)){
2142     $ret[] = $dn;
2143   }
2145   /* Append the rest */
2146   $test = $keep.$dn;
2147   if($called && !empty($test)){
2148     $ret[] = $keep.$dn;
2149   }
2150   $ret['count'] = count($ret) - 1;
2152   return($ret);
2156 function get_base_from_hook($dn, $attrib)
2158   global $config;
2160   if ($config->get_cfg_value("baseIdHook") != ""){
2161     
2162     /* Call hook script - if present */
2163     $command= $config->get_cfg_value("baseIdHook");
2165     if ($command != ""){
2166       $command.= " '".LDAP::fix($dn)."' $attrib";
2167       if (check_command($command)){
2168         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2169         exec($command, $output);
2170         if (preg_match("/^[0-9]+$/", $output[0])){
2171           return ($output[0]);
2172         } else {
2173           msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2174           return ($config->get_cfg_value("uidNumberBase"));
2175         }
2176       } else {
2177         msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2178         return ($config->get_cfg_value("uidNumberBase"));
2179       }
2181     } else {
2183       msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2184       return ($config->get_cfg_value("uidNumberBase"));
2186     }
2187   }
2191 function check_schema_version($class, $version)
2193   return preg_match("/\(v$version\)/", $class['DESC']);
2197 function check_schema($cfg,$rfc2307bis = FALSE)
2199   $messages= array();
2201   /* Get objectclasses */
2202   $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2203   $objectclasses = $ldap->get_objectclasses();
2204   if(count($objectclasses) == 0){
2205     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2206   }
2208   /* This is the default block used for each entry.
2209    *  to avoid unset indexes.
2210    */
2211   $def_check = array("REQUIRED_VERSION" => "0",
2212       "SCHEMA_FILES"     => array(),
2213       "CLASSES_REQUIRED" => array(),
2214       "STATUS"           => FALSE,
2215       "IS_MUST_HAVE"     => FALSE,
2216       "MSG"              => "",
2217       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2219   /* The gosa base schema */
2220   $checks['gosaObject'] = $def_check;
2221   $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2222   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2223   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2224   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2226   /* GOsa Account class */
2227   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.6";
2228   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2229   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2230   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2231   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2233   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2234   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2235   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2236   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2237   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2238   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2240   /* Some other checks */
2241   foreach(array(
2242         "gosaCacheEntry"        => array("version" => "2.6.1"),
2243         "gosaDepartment"        => array("version" => "2.6.1"),
2244         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2245         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2246         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2247         "gosaUserTemplate"      => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2248         "gosaMailAccount"       => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2249         "gosaProxyAccount"      => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2250         "gosaApplication"       => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2251         "gosaApplicationGroup"  => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2252         "GOhard"                => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2253         "gotoTerminal"          => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2254         "goServer"              => array("version" => "2.6.1","class" => "server","file" => "goserver.schema"),
2255         "goTerminalServer"      => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2256         "goShareServer"         => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2257         "goNtpServer"           => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2258         "goSyslogServer"        => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2259         "goLdapServer"          => array("version" => "2.6.1"),
2260         "goCupsServer"          => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2261         "goImapServer"          => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2262         "goKrbServer"           => array("version" => "2.6.1"),
2263         "goFaxServer"           => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2264         ) as $name => $values){
2266           $checks[$name] = $def_check;
2267           if(isset($values['version'])){
2268             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2269           }
2270           if(isset($values['file'])){
2271             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2272           }
2273           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2274         }
2275   foreach($checks as $name => $value){
2276     foreach($value['CLASSES_REQUIRED'] as $class){
2278       if(!isset($objectclasses[$name])){
2279         $checks[$name]['STATUS'] = FALSE;
2280         if($value['IS_MUST_HAVE']){
2281           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2282         }else{
2283           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2284         }
2285       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2286         $checks[$name]['STATUS'] = FALSE;
2288         if($value['IS_MUST_HAVE']){
2289           $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2290         }else{
2291           $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2292         }
2293       }else{
2294         $checks[$name]['STATUS'] = TRUE;
2295         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2296       }
2297     }
2298   }
2300   $tmp = $objectclasses;
2302   /* The gosa base schema */
2303   $checks['posixGroup'] = $def_check;
2304   $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2305   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2306   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2307   $checks['posixGroup']['STATUS']           = TRUE;
2308   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2309   $checks['posixGroup']['MSG']              = "";
2310   $checks['posixGroup']['INFO']             = "";
2312   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2313   if(isset($tmp['posixGroup'])){
2315     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2316       $checks['posixGroup']['STATUS']           = FALSE;
2317       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2318       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2319     }
2320     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2321       $checks['posixGroup']['STATUS']           = FALSE;
2322       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2323       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2324     }
2325   }
2327   return($checks);
2331 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2333   $tmp = array(
2334         "de_DE" => "German",
2335         "fr_FR" => "French",
2336         "it_IT" => "Italian",
2337         "es_ES" => "Spanish",
2338         "en_US" => "English",
2339         "nl_NL" => "Dutch",
2340         "pl_PL" => "Polish",
2341         #"sv_SE" => "Swedish",
2342         "zh_CN" => "Chinese",
2343         "vi_VN" => "Vietnamese",
2344         "ru_RU" => "Russian");
2345   
2346   $tmp2= array(
2347         "de_DE" => _("German"),
2348         "fr_FR" => _("French"),
2349         "it_IT" => _("Italian"),
2350         "es_ES" => _("Spanish"),
2351         "en_US" => _("English"),
2352         "nl_NL" => _("Dutch"),
2353         "pl_PL" => _("Polish"),
2354         #"sv_SE" => _("Swedish"),
2355         "zh_CN" => _("Chinese"),
2356         "vi_VN" => _("Vietnamese"),
2357         "ru_RU" => _("Russian"));
2359   $ret = array();
2360   if($languages_in_own_language){
2362     $old_lang = setlocale(LC_ALL, 0);
2364     /* If the locale wasn't correclty set before, there may be an incorrect
2365         locale returned. Something like this: 
2366           C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2367         Extract the locale name from this string and use it to restore old locale.
2368      */
2369     if(preg_match("/LC_CTYPE/",$old_lang)){
2370       $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2371     }
2372     
2373     foreach($tmp as $key => $name){
2374       $lang = $key.".UTF-8";
2375       setlocale(LC_ALL, $lang);
2376       if($strip_region_tag){
2377         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2378       }else{
2379         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2380       }
2381     }
2382     setlocale(LC_ALL, $old_lang);
2383   }else{
2384     foreach($tmp as $key => $name){
2385       if($strip_region_tag){
2386         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2387       }else{
2388         $ret[$key] = _($name);
2389       }
2390     }
2391   }
2392   return($ret);
2396 /* Returns contents of the given POST variable and check magic quotes settings */
2397 function get_post($name)
2399   if(!isset($_POST[$name])){
2400     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2401     return(FALSE);
2402   }
2403   if(get_magic_quotes_gpc()){
2404     return(stripcslashes($_POST[$name]));
2405   }else{
2406     return($_POST[$name]);
2407   }
2411 /* Return class name in correct case */
2412 function get_correct_class_name($cls)
2414   global $class_mapping;
2415   if(isset($class_mapping) && is_array($class_mapping)){
2416     foreach($class_mapping as $class => $file){
2417       if(preg_match("/^".$cls."$/i",$class)){
2418         return($class);
2419       }
2420     }
2421   }
2422   return(FALSE);
2426 // change_password, changes the Password, of the given dn
2427 function change_password ($dn, $password, $mode=0, $hash= "")
2429   global $config;
2430   $newpass= "";
2432   /* Convert to lower. Methods are lowercase */
2433   $hash= strtolower($hash);
2435   // Get all available encryption Methods
2437   // NON STATIC CALL :)
2438   $methods = new passwordMethod(session::get('config'));
2439   $available = $methods->get_available_methods();
2441   // read current password entry for $dn, to detect the encryption Method
2442   $ldap       = $config->get_ldap_link();
2443   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2444   $attrs      = $ldap->fetch ();
2446   /* Is ensure that clear passwords will stay clear */
2447   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2448     $hash = "clear";
2449   }
2451   // Detect the encryption Method
2452   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2454     /* Check for supported algorithm */
2455     mt_srand((double) microtime()*1000000);
2457     /* Extract used hash */
2458     if ($hash == ""){
2459       $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2460     } else {
2461       $test = new $available[$hash]($config,$dn);
2462       $test->set_hash($hash);
2463     }
2465   } else {
2466     // User MD5 by default
2467     $hash= "md5";
2468     $test = new  $available['md5']($config);
2469   }
2471   if($test instanceOf passwordMethod){
2473     $deactivated = $test->is_locked($config,$dn);
2475     /* Feed password backends with information */
2476     $test->dn= $dn;
2477     $test->attrs= $attrs;
2478     $newpass= $test->generate_hash($password);
2480     // Update shadow timestamp?
2481     if (isset($attrs["shadowLastChange"][0])){
2482       $shadow= (int)(date("U") / 86400);
2483     } else {
2484       $shadow= 0;
2485     }
2487     // Write back modified entry
2488     $ldap->cd($dn);
2489     $attrs= array();
2491     // Not for groups
2492     if ($mode == 0){
2494       if ($shadow != 0){
2495         $attrs['shadowLastChange']= $shadow;
2496       }
2498       // Create SMB Password
2499       $attrs= generate_smb_nt_hash($password);
2500     }
2502     $attrs['userPassword']= array();
2503     $attrs['userPassword']= $newpass;
2505     $ldap->modify($attrs);
2507     /* Read ! if user was deactivated */
2508     if($deactivated){
2509       $test->lock_account($config,$dn);
2510     }
2512     new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2514     if (!$ldap->success()) {
2515       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2516     } else {
2518       /* Run backend method for change/create */
2519       if(!$test->set_password($password)){
2520         return(FALSE);
2521       }
2523       /* Find postmodify entries for this class */
2524       $command= $config->search("password", "POSTMODIFY",array('menu'));
2526       if ($command != ""){
2527         /* Walk through attribute list */
2528         $command= preg_replace("/%userPassword/", $password, $command);
2529         $command= preg_replace("/%dn/", $dn, $command);
2531         if (check_command($command)){
2532           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2533           exec($command);
2534         } else {
2535           $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2536           msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2537         }
2538       }
2539     }
2540     return(TRUE);
2541   }
2545 // Return something like array['sambaLMPassword']= "lalla..."
2546 function generate_smb_nt_hash($password)
2548   global $config;
2550   # Try to use gosa-si?
2551   if ($config->get_cfg_value("gosaSupportURI") != ""){
2552         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2553     if (isset($res['XML']['HASH'])){
2554         $hash= $res['XML']['HASH'];
2555     } else {
2556       $hash= "";
2557     }
2559     if ($hash == "") {
2560       msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2561       return ("");
2562     }
2563   } else {
2564           $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
2565           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2567           exec($tmp, $ar);
2568           flush();
2569           reset($ar);
2570           $hash= current($ar);
2572     if ($hash == "") {
2573       msg_dialog::display(_("Configuration error"), sprintf(_("Cannot generate samba hash: running '%s' failed, check the 'sambaHashHook'!"),$config->get_cfg_value('sambaHashHook')), ERROR_DIALOG);
2574       return ("");
2575     }
2576   }
2578   list($lm,$nt)= split (":", trim($hash));
2580   if ($config->get_cfg_value("sambaversion") == 3) {
2581           $attrs['sambaLMPassword']= $lm;
2582           $attrs['sambaNTPassword']= $nt;
2583           $attrs['sambaPwdLastSet']= date('U');
2584           $attrs['sambaBadPasswordCount']= "0";
2585           $attrs['sambaBadPasswordTime']= "0";
2586   } else {
2587           $attrs['lmPassword']= $lm;
2588           $attrs['ntPassword']= $nt;
2589           $attrs['pwdLastSet']= date('U');
2590   }
2591   return($attrs);
2595 function getEntryCSN($dn)
2597   global $config;
2598   if(empty($dn) || !is_object($config)){
2599     return("");
2600   }
2602   /* Get attribute that we should use as serial number */
2603   $attr= $config->get_cfg_value("modificationDetectionAttribute");
2604   if($attr != ""){
2605     $ldap = $config->get_ldap_link();
2606     $ldap->cat($dn,array($attr));
2607     $csn = $ldap->fetch();
2608     if(isset($csn[$attr][0])){
2609       return($csn[$attr][0]);
2610     }
2611   }
2612   return("");
2616 /* Add a given objectClass to an attrs entry */
2617 function add_objectClass($classes, &$attrs)
2619   if (is_array($classes)){
2620     $list= $classes;
2621   } else {
2622     $list= array($classes);
2623   }
2625   foreach ($list as $class){
2626     $attrs['objectClass'][]= $class;
2627   }
2631 /* Removes a given objectClass from the attrs entry */
2632 function remove_objectClass($classes, &$attrs)
2634   if (isset($attrs['objectClass'])){
2635     /* Array? */
2636     if (is_array($classes)){
2637       $list= $classes;
2638     } else {
2639       $list= array($classes);
2640     }
2642     $tmp= array();
2643     foreach ($attrs['objectClass'] as $oc) {
2644       foreach ($list as $class){
2645         if (strtolower($oc) != strtolower($class)){
2646           $tmp[]= $oc;
2647         }
2648       }
2649     }
2650     $attrs['objectClass']= $tmp;
2651   }
2654 /*! \brief  Initialize a file download with given content, name and data type. 
2655  *  @param  data  String The content to send.
2656  *  @param  name  String The name of the file.
2657  *  @param  type  String The content identifier, default value is "application/octet-stream";
2658  */
2659 function send_binary_content($data,$name,$type = "application/octet-stream")
2661   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2662   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2663   header("Cache-Control: no-cache");
2664   header("Pragma: no-cache");
2665   header("Cache-Control: post-check=0, pre-check=0");
2666   header("Content-type: ".$type."");
2668   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2670   /* Strip name if it is a complete path */
2671   if (preg_match ("/\//", $name)) {
2672         $name= basename($name);
2673   }
2674   
2675   /* force download dialog */
2676   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2677     header('Content-Disposition: filename="'.$name.'"');
2678   } else {
2679     header('Content-Disposition: attachment; filename="'.$name.'"');
2680   }
2682   echo $data;
2683   exit();
2687 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2689   if(is_string($str)){
2690     return(htmlentities($str,$type,$charset));
2691   }elseif(is_array($str)){
2692     foreach($str as $name => $value){
2693       $str[$name] = reverse_html_entities($value,$type,$charset);
2694     }
2695   }
2696   return($str);
2700 /*! \brief Encode special string characters so we can use the string in \
2701            HTML output, without breaking quotes.
2702     @param  The String we want to encode.
2703     @return The encoded String
2704  */
2705 function xmlentities($str)
2706
2707   if(is_string($str)){
2709     static $asc2uni= array();
2710     if (!count($asc2uni)){
2711       for($i=128;$i<256;$i++){
2712     #    $asc2uni[chr($i)] = "&#x".dechex($i).";";
2713       }
2714     }
2716     $str = str_replace("&", "&amp;", $str);
2717     $str = str_replace("<", "&lt;", $str);
2718     $str = str_replace(">", "&gt;", $str);
2719     $str = str_replace("'", "&apos;", $str);
2720     $str = str_replace("\"", "&quot;", $str);
2721     $str = str_replace("\r", "", $str);
2722     $str = strtr($str,$asc2uni);
2723     return $str;
2724   }elseif(is_array($str)){
2725     foreach($str as $name => $value){
2726       $str[$name] = xmlentities($value);
2727     }
2728   }
2729   return($str);
2733 /*! \brief  Updates all accessTo attributes from a given value to a new one.
2734             For example if a host is renamed.
2735     @param  String  $from The source accessTo name.
2736     @param  String  $to   The destination accessTo name.
2737 */
2738 function update_accessTo($from,$to)
2740   global $config;
2741   $ldap = $config->get_ldap_link();
2742   $ldap->cd($config->current['BASE']);
2743   $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2744   while($attrs = $ldap->fetch()){
2745     $new_attrs = array("accessTo" => array());
2746     $dn = $attrs['dn'];
2747     for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2748       $new_attrs['objectClass'][] =  $attrs['objectClass'][$i];
2749     }
2750     for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2751       if($attrs['accessTo'][$i] == $from){
2752         if(!empty($to)){
2753           $new_attrs['accessTo'][] =  $to;
2754         }
2755       }else{
2756         $new_attrs['accessTo'][] =  $attrs['accessTo'][$i]; 
2757       }
2758     }
2759     $ldap->cd($dn);
2760     $ldap->modify($new_attrs);
2761     if (!$ldap->success()){
2762       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2763     }
2764     new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2765   }
2769 function get_random_char () {
2770      $randno = rand (0, 63);
2771      if ($randno < 12) {
2772          return (chr ($randno + 46)); // Digits, '/' and '.'
2773      } else if ($randno < 38) {
2774          return (chr ($randno + 53)); // Uppercase
2775      } else {
2776          return (chr ($randno + 59)); // Lowercase
2777      }
2781 function cred_encrypt($input, $password) {
2783   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2784   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2786   return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2790 function cred_decrypt($input,$password) {
2791   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2792   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2794   return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2797 function get_object_info()
2799   return(session::get('objectinfo'));
2802 function set_object_info($str = "")
2804   session::set('objectinfo',$str);
2808 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2809 ?>