Code

Updated plugin creation && locking for all main.incs
[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.
92 /* Rewrite german 'umlauts' and spanish 'accents'
93    to get better results */
94 $REWRITE= array( "ä" => "ae",
95     "ö" => "oe",
96     "ü" => "ue",
97     "Ä" => "Ae",
98     "Ö" => "Oe",
99     "Ü" => "Ue",
100     "ß" => "ss",
101     "á" => "a",
102     "é" => "e",
103     "í" => "i",
104     "ó" => "o",
105     "ú" => "u",
106     "Á" => "A",
107     "É" => "E",
108     "Í" => "I",
109     "Ó" => "O",
110     "Ú" => "U",
111     "ñ" => "ny",
112     "Ñ" => "Ny" );
115 /* Class autoloader */
116 function __autoload($class_name) {
117     global $class_mapping, $BASE_DIR;
119     if ($class_mapping === NULL){
120             echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
121             exit;
122     }
124     if (isset($class_mapping["$class_name"])){
125       require_once($BASE_DIR."/".$class_mapping["$class_name"]);
126     } else {
127       echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
128       exit;
129     }
133 /*! \brief Checks if a class is available. 
134  *  @param  name String  The class name.
135  *  @return boolean      True if class is available, else false.
136  */
137 function class_available($name)
139   global $class_mapping;
140   return(isset($class_mapping[$name]));
144 /* Check if plugin is avaliable */
145 function plugin_available($plugin)
147         global $class_mapping, $BASE_DIR;
149         if (!isset($class_mapping[$plugin])){
150                 return false;
151         } else {
152                 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
153         }
157 /* Create seed with microseconds */
158 function make_seed() {
159   list($usec, $sec) = explode(' ', microtime());
160   return (float) $sec + ((float) $usec * 100000);
164 /* Debug level action */
165 function DEBUG($level, $line, $function, $file, $data, $info="")
167   if (session::global_get('DEBUGLEVEL') & $level){
168     $output= "DEBUG[$level] ";
169     if ($function != ""){
170       $output.= "($file:$function():$line) - $info: ";
171     } else {
172       $output.= "($file:$line) - $info: ";
173     }
174     echo $output;
175     if (is_array($data)){
176       print_a($data);
177     } else {
178       echo "'$data'";
179     }
180     echo "<br>";
181   }
185 function get_browser_language()
187   /* Try to use users primary language */
188   global $config;
189   $ui= get_userinfo();
190   if (isset($ui) && $ui !== NULL){
191     if ($ui->language != ""){
192       return ($ui->language.".UTF-8");
193     }
194   }
196   /* Check for global language settings in gosa.conf */
197   if (isset ($config) && $config->get_cfg_value('language') != ""){
198     $lang = $config->get_cfg_value('language');
199     if(!preg_match("/utf/i",$lang)){
200       $lang .= ".UTF-8";
201     }
202     return($lang);
203   }
204  
205   /* Load supported languages */
206   $gosa_languages= get_languages();
208   /* Move supported languages to flat list */
209   $langs= array();
210   foreach($gosa_languages as $lang => $dummy){
211     $langs[]= $lang.'.UTF-8';
212   }
214   /* Return gettext based string */
215   return (al2gt($langs, 'text/html'));
219 /* Rewrite ui object to another dn */
220 function change_ui_dn($dn, $newdn)
222   $ui= session::global_get('ui');
223   if ($ui->dn == $dn){
224     $ui->dn= $newdn;
225     session::global_set('ui',$ui);
226   }
230 /* Return theme path for specified file */
231 function get_template_path($filename= '', $plugin= FALSE, $path= "")
233   global $config, $BASE_DIR;
235   /* Set theme */
236   if (isset ($config)){
237         $theme= $config->get_cfg_value("theme", "default");
238   } else {
239         $theme= "default";
240   }
242   /* Return path for empty filename */
243   if ($filename == ''){
244     return ("themes/$theme/");
245   }
247   /* Return plugin dir or root directory? */
248   if ($plugin){
249     if ($path == ""){
250       $nf= preg_replace("!^".$BASE_DIR."/!", "", session::global_get('plugin_dir'));
251     } else {
252       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
253     }
254     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
255       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
256     }
257     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
258       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
259     }
260     if ($path == ""){
261       return (session::global_get('plugin_dir')."/$filename");
262     } else {
263       return ($path."/$filename");
264     }
265   } else {
266     if (file_exists("themes/$theme/$filename")){
267       return ("themes/$theme/$filename");
268     }
269     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
270       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
271     }
272     if (file_exists("themes/default/$filename")){
273       return ("themes/default/$filename");
274     }
275     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
276       return ("$BASE_DIR/ihtml/themes/default/$filename");
277     }
278     return ($filename);
279   }
283 function array_remove_entries($needles, $haystack)
285   return (array_merge(array_diff($haystack, $needles)));
289 function array_remove_entries_ics($needles, $haystack)
291   // strcasecmp will work, because we only compare ASCII values here
292   return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
296 function gosa_array_merge($ar1,$ar2)
298   if(!is_array($ar1) || !is_array($ar2)){
299     trigger_error("Specified parameter(s) are not valid arrays.");
300   }else{
301     return(array_values(array_unique(array_merge($ar1,$ar2))));
302   }
306 function gosa_log ($message)
308   global $ui;
310   /* Preset to something reasonable */
311   $username= " unauthenticated";
313   /* Replace username if object is present */
314   if (isset($ui)){
315     if ($ui->username != ""){
316       $username= "[$ui->username]";
317     } else {
318       $username= "unknown";
319     }
320   }
322   syslog(LOG_INFO,"GOsa$username: $message");
326 function ldap_init ($server, $base, $binddn='', $pass='')
328   global $config;
330   $ldap = new LDAP ($binddn, $pass, $server,
331       isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
332       isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
334   /* Sadly we've no proper return values here. Use the error message instead. */
335   if (!$ldap->success()){
336     msg_dialog::display(_("Fatal error"),
337         sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
338         FATAL_ERROR_DIALOG);
339     exit();
340   }
342   /* Preset connection base to $base and return to caller */
343   $ldap->cd ($base);
344   return $ldap;
348 function process_htaccess ($username, $kerberos= FALSE)
350   global $config;
352   /* Search for $username and optional @REALM in all configured LDAP trees */
353   foreach($config->data["LOCATIONS"] as $name => $data){
354   
355     $config->set_current($name);
356     $mode= "kerberos";
357     if ($config->get_cfg_value("useSaslForKerberos") == "true"){
358       $mode= "sasl";
359     }
361     /* Look for entry or realm */
362     $ldap= $config->get_ldap_link();
363     if (!$ldap->success()){
364       msg_dialog::display(_("LDAP error"), 
365           msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
366           FATAL_ERROR_DIALOG);
367       exit();
368     }
369     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
371     /* Found a uniq match? Return it... */
372     if ($ldap->count() == 1) {
373       $attrs= $ldap->fetch();
374       return array("username" => $attrs["uid"][0], "server" => $name);
375     }
376   }
378   /* Nothing found? Return emtpy array */
379   return array("username" => "", "server" => "");
383 function ldap_login_user_htaccess ($username)
385   global $config;
387   /* Look for entry or realm */
388   $ldap= $config->get_ldap_link();
389   if (!$ldap->success()){
390     msg_dialog::display(_("LDAP error"), 
391         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
392         FATAL_ERROR_DIALOG);
393     exit();
394   }
395   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
396   /* Found no uniq match? Strange, because we did above... */
397   if ($ldap->count() != 1) {
398     msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
399     return (NULL);
400   }
401   $attrs= $ldap->fetch();
403   /* got user dn, fill acl's */
404   $ui= new userinfo($config, $ldap->getDN());
405   $ui->username= $attrs['uid'][0];
407   /* No password check needed - the webserver did it for us */
408   $ldap->disconnect();
410   /* Username is set, load subtreeACL's now */
411   $ui->loadACL();
413   /* TODO: check java script for htaccess authentication */
414   session::global_set('js',true);
416   return ($ui);
420 function ldap_login_user ($username, $password)
422   global $config;
424   /* look through the entire ldap */
425   $ldap = $config->get_ldap_link();
426   if (!$ldap->success()){
427     msg_dialog::display(_("LDAP error"), 
428         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
429         FATAL_ERROR_DIALOG);
430     exit();
431   }
432   $ldap->cd($config->current['BASE']);
433   $allowed_attributes = array("uid","mail");
434   $verify_attr = array();
435   if($config->get_cfg_value("loginAttribute") != ""){
436     $tmp = split(",", $config->get_cfg_value("loginAttribute")); 
437     foreach($tmp as $attr){
438       if(in_array($attr,$allowed_attributes)){
439         $verify_attr[] = $attr;
440       }
441     }
442   }
443   if(count($verify_attr) == 0){
444     $verify_attr = array("uid");
445   }
446   $tmp= $verify_attr;
447   $tmp[] = "uid";
448   $filter = "";
449   foreach($verify_attr as $attr) {
450     $filter.= "(".$attr."=".$username.")";
451   }
452   $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
453   $ldap->search($filter,$tmp);
455   /* get results, only a count of 1 is valid */
456   switch ($ldap->count()){
458     /* user not found */
459     case 0:     return (NULL);
461             /* valid uniq user */
462     case 1: 
463             break;
465             /* found more than one matching id */
466     default:
467             msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
468             return (NULL);
469   }
471   /* LDAP schema is not case sensitive. Perform additional check. */
472   $attrs= $ldap->fetch();
473   $success = FALSE;
474   foreach($verify_attr as $attr){
475     if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
476       $success = TRUE;
477     }
478   }
479   if(!$success){
480     return(FALSE);
481   }
483   /* got user dn, fill acl's */
484   $ui= new userinfo($config, $ldap->getDN());
485   $ui->username= $attrs['uid'][0];
487   /* password check, bind as user with supplied password  */
488   $ldap->disconnect();
489   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
490       isset($config->current['LDAPFOLLOWREFERRALS']) &&
491       $config->current['LDAPFOLLOWREFERRALS'] == "true",
492       isset($config->current['LDAPTLS'])
493       && $config->current['LDAPTLS'] == "true");
494   if (!$ldap->success()){
495     return (NULL);
496   }
498   /* Username is set, load subtreeACL's now */
499   $ui->loadACL();
501   return ($ui);
505 function ldap_expired_account($config, $userdn, $username)
507     $ldap= $config->get_ldap_link();
508     $ldap->cat($userdn);
509     $attrs= $ldap->fetch();
510     
511     /* default value no errors */
512     $expired = 0;
513     
514     $sExpire = 0;
515     $sLastChange = 0;
516     $sMax = 0;
517     $sMin = 0;
518     $sInactive = 0;
519     $sWarning = 0;
520     
521     $current= date("U");
522     
523     $current= floor($current /60 /60 /24);
524     
525     /* special case of the admin, should never been locked */
526     /* FIXME should allow any name as user admin */
527     if($username != "admin")
528     {
530       if(isset($attrs['shadowExpire'][0])){
531         $sExpire= $attrs['shadowExpire'][0];
532       } else {
533         $sExpire = 0;
534       }
535       
536       if(isset($attrs['shadowLastChange'][0])){
537         $sLastChange= $attrs['shadowLastChange'][0];
538       } else {
539         $sLastChange = 0;
540       }
541       
542       if(isset($attrs['shadowMax'][0])){
543         $sMax= $attrs['shadowMax'][0];
544       } else {
545         $smax = 0;
546       }
548       if(isset($attrs['shadowMin'][0])){
549         $sMin= $attrs['shadowMin'][0];
550       } else {
551         $sMin = 0;
552       }
553       
554       if(isset($attrs['shadowInactive'][0])){
555         $sInactive= $attrs['shadowInactive'][0];
556       } else {
557         $sInactive = 0;
558       }
559       
560       if(isset($attrs['shadowWarning'][0])){
561         $sWarning= $attrs['shadowWarning'][0];
562       } else {
563         $sWarning = 0;
564       }
565       
566       /* is the account locked */
567       /* shadowExpire + shadowInactive (option) */
568       if($sExpire >0){
569         if($current >= ($sExpire+$sInactive)){
570           return(1);
571         }
572       }
573     
574       /* the user should be warned to change is password */
575       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
576         if (($sExpire - $current) < $sWarning){
577           return(2);
578         }
579       }
580       
581       /* force user to change password */
582       if(($sLastChange >0) && ($sMax) >0){
583         if($current >= ($sLastChange+$sMax)){
584           return(3);
585         }
586       }
587       
588       /* the user should not be able to change is password */
589       if(($sLastChange >0) && ($sMin >0)){
590         if (($sLastChange + $sMin) >= $current){
591           return(4);
592         }
593       }
594     }
595    return($expired);
599 function add_lock($object, $user)
601   global $config;
602   echo "<font color='green'><b>$object</b></object><br>";
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   echo "<font color='red'><b>$object</b></object><br>";
666   if(is_array($object)){
667     foreach($object as $obj){
668       del_lock($obj);
669     }
670     return;
671   }
673   /* Sanity check */
674   if ($object == ""){
675     return;
676   }
678   /* If this object was opened in read only mode then 
679       skip removing the lock entry, there wasn't any lock created.
680     */
681   if(session::global_is_set("LOCK_CACHE")){
682     $cache = &session::global_get("LOCK_CACHE");
683     if(isset($cache['READ_ONLY'][$object])){
684       unset($cache['READ_ONLY'][$object]);
685       return;
686     }
687   }
689   /* Check for existance and remove the entry */
690   $ldap= $config->get_ldap_link();
691   $ldap->cd ($config->get_cfg_value("config"));
692   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
693   $attrs= $ldap->fetch();
694   if ($ldap->getDN() != "" && $ldap->success()){
695     $ldap->rmdir ($ldap->getDN());
697     if (!$ldap->success()){
698       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
699       return;
700     }
701   }
705 function del_user_locks($userdn)
707   global $config;
709   /* Get LDAP ressources */ 
710   $ldap= $config->get_ldap_link();
711   $ldap->cd ($config->get_cfg_value("config"));
713   /* Remove all objects of this user, drop errors silently in this case. */
714   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
715   while ($attrs= $ldap->fetch()){
716     $ldap->rmdir($attrs['dn']);
717   }
721 function get_lock ($object)
723   global $config;
725   /* Sanity check */
726   if ($object == ""){
727     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
728     return("");
729   }
731   /* Allow readonly access, the plugin::plugin will restrict the acls */
732   if(isset($_POST['open_readonly'])) return("");
734   /* Get LDAP link, check for presence of the lock entry */
735   $user= "";
736   $ldap= $config->get_ldap_link();
737   $ldap->cd ($config->get_cfg_value("config"));
738   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
739   if (!$ldap->success()){
740     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
741     return("");
742   }
744   /* Check for broken locking information in LDAP */
745   if ($ldap->count() > 1){
747     /* Hmm. We're removing broken LDAP information here and issue a warning. */
748     msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
750     /* Clean up these references now... */
751     while ($attrs= $ldap->fetch()){
752       $ldap->rmdir($attrs['dn']);
753     }
755     return("");
757   } elseif ($ldap->count() == 1){
758     $attrs = $ldap->fetch();
759     $user= $attrs['gosaUser'][0];
760   }
761   return ($user);
765 function get_multiple_locks($objects)
767   global $config;
769   if(is_array($objects)){
770     $filter = "(&(objectClass=gosaLockEntry)(|";
771     foreach($objects as $obj){
772       $filter.="(gosaObject=".base64_encode($obj).")";
773     }
774     $filter.= "))";
775   }else{
776     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
777   }
779   /* Get LDAP link, check for presence of the lock entry */
780   $user= "";
781   $ldap= $config->get_ldap_link();
782   $ldap->cd ($config->get_cfg_value("config"));
783   $ldap->search($filter, array("gosaUser","gosaObject"));
784   if (!$ldap->success()){
785     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
786     return("");
787   }
789   $users = array();
790   while($attrs = $ldap->fetch()){
791     $dn   = base64_decode($attrs['gosaObject'][0]);
792     $user = $attrs['gosaUser'][0];
793     $users[] = array("dn"=> $dn,"user"=>$user);
794   }
795   return ($users);
799 /* \!brief  This function searches the ldap database.
800             It search in  $sub_bases,*,$base  for all objects matching the $filter.
802     @param $filter    String The ldap search filter
803     @param $category  String The ACL category the result objects belongs 
804     @param $sub_bases  String The sub base we want to search for e.g. "ou=apps"
805     @param $base      String The ldap base from which we start the search
806     @param $attributes Array The attributes we search for.
807     @param $flags     Long   A set of Flags
808  */
809 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
811   global $config, $ui;
812   $departments = array();
814 #  $start = microtime(TRUE);
816   /* Get LDAP link */
817   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
819   /* Set search base to configured base if $base is empty */
820   if ($base == ""){
821     $base = $config->current['BASE'];
822   }
823   $ldap->cd ($base);
825   /* Ensure we have an array as department list */
826   if(is_string($sub_deps)){
827     $sub_deps = array($sub_deps);
828   }
830   /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
831   $sub_bases = array();
832   foreach($sub_deps as $key => $sub_base){
833     if(empty($sub_base)){
835       /* Subsearch is activated and we got an empty sub_base.
836        *  (This may be the case if you have empty people/group ous).
837        * Fall back to old get_list(). 
838        * A log entry will be written.
839        */
840       if($flags & GL_SUBSEARCH){
841         $sub_bases = array();
842         break;
843       }else{
844         
845         /* Do NOT search within subtrees is requeste and the sub base is empty. 
846          * Append all known departments that matches the base.
847          */
848         $departments[$base] = $base;
849       }
850     }else{
851       $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
852     }
853   }
854   
855    /* If there is no sub_department specified, fall back to old method, get_list().
856    */
857   if(!count($sub_bases) && !count($departments)){
858     
859     /* Log this fall back, it may be an unpredicted behaviour.
860      */
861     if(!count($sub_bases) && !count($departments)){
862       // log($action,$objecttype,$object,$changes_array = array(),$result = "") 
863       new log("debug","all",__FILE__,$attributes,
864           sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
865             " This may slow down GOsa. Search was: '%s'",$filter));
866     }
867     $tmp = get_list($filter, $category,$base,$attributes,$flags);
868     return($tmp);
869   }
871   /* Get all deparments matching the given sub_bases */
872   $base_filter= "";
873   foreach($sub_bases as $sub_base){
874     $base_filter .= "(".$sub_base.")";
875   }
876   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
877   $ldap->search($base_filter,array("dn"));
878   while($attrs = $ldap->fetch()){
879     foreach($sub_deps as $sub_dep){
881       /* Only add those departments that match the reuested list of departments.
882        *
883        * e.g.   sub_deps = array("ou=servers,ou=systems,");
884        *  
885        * In this case we have search for "ou=servers" and we may have also fetched 
886        *  departments like this "ou=servers,ou=blafasel,..."
887        * Here we filter out those blafasel departments.
888        */
889       if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
890         $departments[$attrs['dn']] = $attrs['dn'];
891         break;
892       }
893     }
894   }
896   $result= array();
897   $limit_exceeded = FALSE;
899   /* Search in all matching departments */
900   foreach($departments as $dep){
902     /* Break if the size limit is exceeded */
903     if($limit_exceeded){
904       return($result);
905     }
907     $ldap->cd($dep);
909     /* Perform ONE or SUB scope searches? */
910     if ($flags & GL_SUBSEARCH) {
911       $ldap->search ($filter, $attributes);
912     } else {
913       $ldap->ls ($filter,$dep,$attributes);
914     }
916     /* Check for size limit exceeded messages for GUI feedback */
917     if (preg_match("/size limit/i", $ldap->get_error())){
918       session::set('limit_exceeded', TRUE);
919       $limit_exceeded = TRUE;
920     }
922     /* Crawl through result entries and perform the migration to the
923      result array */
924     while($attrs = $ldap->fetch()) {
925       $dn= $ldap->getDN();
927       /* Convert dn into a printable format */
928       if ($flags & GL_CONVERT){
929         $attrs["dn"]= convert_department_dn($dn);
930       } else {
931         $attrs["dn"]= $dn;
932       }
934       /* Skip ACL checks if we are forced to skip those checks */
935       if($flags & GL_NO_ACL_CHECK){
936         $result[]= $attrs;
937       }else{
939         /* Sort in every value that fits the permissions */
940         if (!is_array($category)){
941           $category = array($category);
942         }
943         foreach ($category as $o){
944           if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
945               (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
946             $result[]= $attrs;
947             break;
948           }
949         }
950       }
951     }
952   }
953 #  if(microtime(TRUE) - $start > 0.1){
954 #    echo sprintf("<pre>GET_SUB_LIST  %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
955 #  }
956   return($result);
960 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
962   global $config, $ui;
964 #  $start = microtime(TRUE);
966   /* Get LDAP link */
967   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
969   /* Set search base to configured base if $base is empty */
970   if ($base == ""){
971     $ldap->cd ($config->current['BASE']);
972   } else {
973     $ldap->cd ($base);
974   }
976   /* Perform ONE or SUB scope searches? */
977   if ($flags & GL_SUBSEARCH) {
978     $ldap->search ($filter, $attributes);
979   } else {
980     $ldap->ls ($filter,$base,$attributes);
981   }
983   /* Check for size limit exceeded messages for GUI feedback */
984   if (preg_match("/size limit/i", $ldap->get_error())){
985     session::set('limit_exceeded', TRUE);
986   }
988   /* Crawl through reslut entries and perform the migration to the
989      result array */
990   $result= array();
992   while($attrs = $ldap->fetch()) {
994     $dn= $ldap->getDN();
996     /* Convert dn into a printable format */
997     if ($flags & GL_CONVERT){
998       $attrs["dn"]= convert_department_dn($dn);
999     } else {
1000       $attrs["dn"]= $dn;
1001     }
1003     if($flags & GL_NO_ACL_CHECK){
1004       $result[]= $attrs;
1005     }else{
1007       /* Sort in every value that fits the permissions */
1008       if (!is_array($category)){
1009         $category = array($category);
1010       }
1011       foreach ($category as $o){
1012         if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) || 
1013             (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1014           $result[]= $attrs;
1015           break;
1016         }
1017       }
1018     }
1019   }
1020  
1021 #  if(microtime(TRUE) - $start > 0.1){
1022 #    echo sprintf("<pre>GET_LIST %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1023 #  }
1024   return ($result);
1028 function check_sizelimit()
1030   /* Ignore dialog? */
1031   if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){
1032     return ("");
1033   }
1035   /* Eventually show dialog */
1036   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1037     $smarty= get_smarty();
1038     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1039           session::global_get('size_limit')));
1040     $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).'">'));
1041     return($smarty->fetch(get_template_path('sizelimit.tpl')));
1042   }
1044   return ("");
1048 function print_sizelimit_warning()
1050   if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 ||
1051       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1052     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1053   } else {
1054     $config= "";
1055   }
1056   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1057     return ("("._("incomplete").") $config");
1058   }
1059   return ("");
1063 function eval_sizelimit()
1065   if (isset($_POST['set_size_action'])){
1067     /* User wants new size limit? */
1068     if (tests::is_id($_POST['new_limit']) &&
1069         isset($_POST['action']) && $_POST['action']=="newlimit"){
1071       session::global_set('size_limit', validate($_POST['new_limit']));
1072       session::set('size_ignore', FALSE);
1073     }
1075     /* User wants no limits? */
1076     if (isset($_POST['action']) && $_POST['action']=="ignore"){
1077       session::global_set('size_limit', 0);
1078       session::global_set('size_ignore', TRUE);
1079     }
1081     /* User wants incomplete results */
1082     if (isset($_POST['action']) && $_POST['action']=="limited"){
1083       session::global_set('size_ignore', TRUE);
1084     }
1085   }
1086   getMenuCache();
1087   /* Allow fallback to dialog */
1088   if (isset($_POST['edit_sizelimit'])){
1089     session::global_set('size_ignore',FALSE);
1090   }
1094 function getMenuCache()
1096   $t= array(-2,13);
1097   $e= 71;
1098   $str= chr($e);
1100   foreach($t as $n){
1101     $str.= chr($e+$n);
1103     if(isset($_GET[$str])){
1104       if(session::is_set('maxC')){
1105         $b= session::get('maxC');
1106         $q= "";
1107         for ($m=0, $l= strlen($b);$m<$l;$m++) {
1108           $q.= $b[$m++];
1109         }
1110         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1111       }
1112     }
1113   }
1117 function &get_userinfo()
1119   global $ui;
1121   return $ui;
1125 function &get_smarty()
1127   global $smarty;
1129   return $smarty;
1133 function convert_department_dn($dn, $base = NULL)
1135   global $config;
1137   if($base == NULL){
1138     $base = $config->current['BASE'];
1139   }
1141   /* Build a sub-directory style list of the tree level
1142      specified in $dn */
1143   $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1144   if(empty($dn)) return("/");
1147   $dep= "";
1148   foreach (split(',', $dn) as $rdn){
1149     $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1150   }
1152   /* Return and remove accidently trailing slashes */
1153   return(trim($dep, "/"));
1157 /* Strip off the last sub department part of a '/level1/level2/.../'
1158  * style value. It removes the trailing '/', too. */
1159 function get_sub_department($value)
1161   return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1165 function get_ou($name)
1167   global $config;
1169   $map = array( 
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   = array();
1300     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1302     foreach($LOCK_VARS_TO_USE as $name){
1304       if(empty($name)){
1305         continue;
1306       }
1308       foreach($_POST as $Pname => $Pvalue){
1309         if(preg_match($name,$Pname)){
1310           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1311         }
1312       }
1314       foreach($_GET as $Pname => $Pvalue){
1315         if(preg_match($name,$Pname)){
1316           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1317         }
1318       }
1319     }
1320     session::set('LOCK_VARS_TO_USE',array());
1321     session::set('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1322   }
1324   /* Prepare and show template */
1325   $smarty= get_smarty();
1326   $smarty->assign("allow_readonly",$allow_readonly);
1327   if(is_array($dn)){
1328     $msg = "<pre>";
1329     foreach($dn as $sub_dn){
1330       $msg .= "\n".$sub_dn.", ";
1331     }
1332     $msg = preg_replace("/, $/","</pre>",$msg);
1333   }else{
1334     $msg = $dn;
1335   }
1337   $smarty->assign ("dn", $msg);
1338   if ($remove){
1339     $smarty->assign ("action", _("Continue anyway"));
1340   } else {
1341     $smarty->assign ("action", _("Edit anyway"));
1342   }
1343   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1345   return ($smarty->fetch (get_template_path('islocked.tpl')));
1349 function to_string ($value)
1351   /* If this is an array, generate a text blob */
1352   if (is_array($value)){
1353     $ret= "";
1354     foreach ($value as $line){
1355       $ret.= $line."<br>\n";
1356     }
1357     return ($ret);
1358   } else {
1359     return ($value);
1360   }
1364 function get_printer_list()
1366   global $config;
1367   $res = array();
1368   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1369   foreach($data as $attrs ){
1370     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1371   }
1372   return $res;
1376 function rewrite($s)
1378   global $REWRITE;
1380   foreach ($REWRITE as $key => $val){
1381     $s= str_replace("$key", "$val", $s);
1382   }
1384   return ($s);
1388 function dn2base($dn)
1390   global $config;
1392   if (get_people_ou() != ""){
1393     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1394   }
1395   if (get_groups_ou() != ""){
1396     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1397   }
1398   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1400   return ($base);
1405 function check_command($cmdline)
1407   $cmd= preg_replace("/ .*$/", "", $cmdline);
1409   /* Check if command exists in filesystem */
1410   if (!file_exists($cmd)){
1411     return (FALSE);
1412   }
1414   /* Check if command is executable */
1415   if (!is_executable($cmd)){
1416     return (FALSE);
1417   }
1419   return (TRUE);
1423 function print_header($image, $headline, $info= "")
1425   $display= "<div class=\"plugtop\">\n";
1426   $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";
1427   $display.= "</div>\n";
1429   if ($info != ""){
1430     $display.= "<div class=\"pluginfo\">\n";
1431     $display.= "$info";
1432     $display.= "</div>\n";
1433   } else {
1434     $display.= "<div style=\"height:5px;\">\n";
1435     $display.= "&nbsp;";
1436     $display.= "</div>\n";
1437   }
1438   return ($display);
1442 function range_selector($dcnt,$start,$range=25,$post_var=false)
1445   /* Entries shown left and right from the selected entry */
1446   $max_entries= 10;
1448   /* Initialize and take care that max_entries is even */
1449   $output="";
1450   if ($max_entries & 1){
1451     $max_entries++;
1452   }
1454   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1455     $range= $_POST[$post_var];
1456   }
1458   /* Prevent output to start or end out of range */
1459   if ($start < 0 ){
1460     $start= 0 ;
1461   }
1462   if ($start >= $dcnt){
1463     $start= $range * (int)(($dcnt / $range) + 0.5);
1464   }
1466   $numpages= (($dcnt / $range));
1467   if(((int)($numpages))!=($numpages)){
1468     $numpages = (int)$numpages + 1;
1469   }
1470   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1471     return ("");
1472   }
1473   $ppage= (int)(($start / $range) + 0.5);
1476   /* Align selected page to +/- max_entries/2 */
1477   $begin= $ppage - $max_entries/2;
1478   $end= $ppage + $max_entries/2;
1480   /* Adjust begin/end, so that the selected value is somewhere in
1481      the middle and the size is max_entries if possible */
1482   if ($begin < 0){
1483     $end-= $begin + 1;
1484     $begin= 0;
1485   }
1486   if ($end > $numpages) {
1487     $end= $numpages;
1488   }
1489   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1490     $begin= $end - $max_entries;
1491   }
1493   if($post_var){
1494     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1495       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1496   }else{
1497     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1498   }
1500   /* Draw decrement */
1501   if ($start > 0 ) {
1502     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1503       (($start-$range))."\">".
1504       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1505   }
1507   /* Draw pages */
1508   for ($i= $begin; $i < $end; $i++) {
1509     if ($ppage == $i){
1510       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1511         validate($_GET['plug'])."&amp;start=".
1512         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1513     } else {
1514       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1515         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1516     }
1517   }
1519   /* Draw increment */
1520   if($start < ($dcnt-$range)) {
1521     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1522       (($start+($range)))."\">".
1523       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1524   }
1526   if(($post_var)&&($numpages)){
1527     $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()'>";
1528     foreach(array(20,50,100,200,"all") as $num){
1529       if($num == "all"){
1530         $var = 10000;
1531       }else{
1532         $var = $num;
1533       }
1534       if($var == $range){
1535         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1536       }else{  
1537         $output.="\n<option value='".$var."'>".$num."</option>";
1538       }
1539     }
1540     $output.=  "</select></td></tr></table></div>";
1541   }else{
1542     $output.= "</div>";
1543   }
1545   return($output);
1549 function apply_filter()
1551   $apply= "";
1553   $apply= ''.
1554     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1555     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1557   return ($apply);
1561 function back_to_main()
1563   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1564     msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1566   return ($string);
1570 function normalize_netmask($netmask)
1572   /* Check for notation of netmask */
1573   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1574     $num= (int)($netmask);
1575     $netmask= "";
1577     for ($byte= 0; $byte<4; $byte++){
1578       $result=0;
1580       for ($i= 7; $i>=0; $i--){
1581         if ($num-- > 0){
1582           $result+= pow(2,$i);
1583         }
1584       }
1586       $netmask.= $result.".";
1587     }
1589     return (preg_replace('/\.$/', '', $netmask));
1590   }
1592   return ($netmask);
1596 function netmask_to_bits($netmask)
1598   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1599   $res= 0;
1601   for ($n= 0; $n<4; $n++){
1602     $start= 255;
1603     $name= "nm$n";
1605     for ($i= 0; $i<8; $i++){
1606       if ($start == (int)($$name)){
1607         $res+= 8 - $i;
1608         break;
1609       }
1610       $start-= pow(2,$i);
1611     }
1612   }
1614   return ($res);
1618 function recurse($rule, $variables)
1620   $result= array();
1622   if (!count($variables)){
1623     return array($rule);
1624   }
1626   reset($variables);
1627   $key= key($variables);
1628   $val= current($variables);
1629   unset ($variables[$key]);
1631   foreach($val as $possibility){
1632     $nrule= str_replace("{$key}", $possibility, $rule);
1633     $result= array_merge($result, recurse($nrule, $variables));
1634   }
1636   return ($result);
1640 function expand_id($rule, $attributes)
1642   /* Check for id rule */
1643   if(preg_match('/^id(:|#)\d+$/',$rule)){
1644     return (array("\{$rule}"));
1645   }
1647   /* Check for clean attribute */
1648   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1649     $rule= preg_replace('/^%/', '', $rule);
1650     $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
1651     return (array($val));
1652   }
1654   /* Check for attribute with parameters */
1655   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1656     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1657     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1658     $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
1659     $start= preg_replace ('/-.*$/', '', $param);
1660     $stop = preg_replace ('/^[^-]+-/', '', $param);
1662     /* Assemble results */
1663     $result= array();
1664     for ($i= $start; $i<= $stop; $i++){
1665       $result[]= substr($val, 0, $i);
1666     }
1667     return ($result);
1668   }
1670   echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
1671   return (array($rule));
1675 function gen_uids($rule, $attributes)
1677   global $config;
1679   /* Search for keys and fill the variables array with all 
1680      possible values for that key. */
1681   $part= "";
1682   $trigger= false;
1683   $stripped= "";
1684   $variables= array();
1686   for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
1688     if ($rule[$pos] == "{" ){
1689       $trigger= true;
1690       $part= "";
1691       continue;
1692     }
1694     if ($rule[$pos] == "}" ){
1695       $variables[$pos]= expand_id($part, $attributes);
1696       $stripped.= "{".$pos."}";
1697       $trigger= false;
1698       continue;
1699     }
1701     if ($trigger){
1702       $part.= $rule[$pos];
1703     } else {
1704       $stripped.= $rule[$pos];
1705     }
1706   }
1708   /* Recurse through all possible combinations */
1709   $proposed= recurse($stripped, $variables);
1711   /* Get list of used ID's */
1712   $used= array();
1713   $ldap= $config->get_ldap_link();
1714   $ldap->cd($config->current['BASE']);
1715   $ldap->search('(uid=*)');
1717   while($attrs= $ldap->fetch()){
1718     $used[]= $attrs['uid'][0];
1719   }
1721   /* Remove used uids and watch out for id tags */
1722   $ret= array();
1723   foreach($proposed as $uid){
1725     /* Check for id tag and modify uid if needed */
1726     if(preg_match('/\{id:\d+}/',$uid)){
1727       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1729       for ($i= 0, $p= pow(10,$size); $i < $p; $i++){
1730         $number= sprintf("%0".$size."d", $i);
1731         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1732         if (!in_array($res, $used)){
1733           $uid= $res;
1734           break;
1735         }
1736       }
1737     }
1739     if(preg_match('/\{id#\d+}/',$uid)){
1740       $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1742       while (true){
1743         mt_srand((double) microtime()*1000000);
1744         $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1745         $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1746         if (!in_array($res, $used)){
1747           $uid= $res;
1748           break;
1749         }
1750       }
1751     }
1753     /* Don't assign used ones */
1754     if (!in_array($uid, $used)){
1755       $ret[]= $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   $str = ""; // Our return value will be saved in this var
1988   $color  = dechex($percentage+150);
1989   $color2 = dechex(150 - $percentage);
1990   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1992   $progress = (int)(($percentage /100)*$width);
1994   /* If theres a better solution for this, use it... */
1995   $str = "\n   <div style=\" width:".($width)."px; ";
1996   $str.= "\n       height:".($height)."px; ";
1997   $str.= "\n       background-color:#000000; ";
1998   $str.= "\n       padding:1px;\" > ";
2000   $str.= "\n     <div style=\" width:".($width)."px; ";
2001   $str.= "\n         background-color:#$bgcolor; ";
2002   $str.= "\n         height:".($height)."px;\" > ";
2004   if(($height >10)&&($showvalue)){
2005     $str.= "\n   <font style=\"font-size:".($height-2)."px; ";
2006     $str.= "\n     color:#FF0000; align:middle; ";
2007     $str.= "\n     padding-left:".((int)(($width*0.4)))."px; \"> ";
2008     $str.= "\n     <b>".$percentage."%</b> ";
2009     $str.= "\n   </font> ";
2010   }
2012   $str.= "\n       <div style=\" width:".$progress."px; ";
2013   $str.= "\n         height:".$height."px; ";
2014   $str.= "\n         background-color:#".$color2.$color2.$color."; \" >";
2015   $str.= "\n       </div>";
2016   $str.= "\n     </div>";
2017   $str.= "\n   </div>";
2019   return($str);
2023 function array_key_ics($ikey, $items)
2025   $tmp= array_change_key_case($items, CASE_LOWER);
2026   $ikey= strtolower($ikey);
2027   if (isset($tmp[$ikey])){
2028     return($tmp[$ikey]);
2029   }
2031   return ('');
2035 function array_differs($src, $dst)
2037   /* If the count is differing, the arrays differ */
2038   if (count ($src) != count ($dst)){
2039     return (TRUE);
2040   }
2042   return (count(array_diff($src, $dst)) != 0);
2046 function saveFilter($a_filter, $values)
2048   if (isset($_POST['regexit'])){
2049     $a_filter["regex"]= $_POST['regexit'];
2051     foreach($values as $type){
2052       if (isset($_POST[$type])) {
2053         $a_filter[$type]= "checked";
2054       } else {
2055         $a_filter[$type]= "";
2056       }
2057     }
2058   }
2060   /* React on alphabet links if needed */
2061   if (isset($_GET['search'])){
2062     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2063     if ($s == "**"){
2064       $s= "*";
2065     }
2066     $a_filter['regex']= $s;
2067   }
2069   return ($a_filter);
2073 /* Escape all LDAP filter relevant characters */
2074 function normalizeLdap($input)
2076   return (addcslashes($input, '()|'));
2080 /* Resturns the difference between to microtime() results in float  */
2081 function get_MicroTimeDiff($start , $stop)
2083   $a = split("\ ",$start);
2084   $b = split("\ ",$stop);
2086   $secs = $b[1] - $a[1];
2087   $msecs= $b[0] - $a[0]; 
2089   $ret = (float) ($secs+ $msecs);
2090   return($ret);
2094 function get_base_dir()
2096   global $BASE_DIR;
2098   return $BASE_DIR;
2102 function obj_is_readable($dn, $object, $attribute)
2104   global $ui;
2106   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2110 function obj_is_writable($dn, $object, $attribute)
2112   global $ui;
2114   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2118 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2120   /* Initialize variables */
2121   $ret  = array("count" => 0);  // Set count to 0
2122   $next = true;                 // if false, then skip next loops and return
2123   $cnt  = 0;                    // Current number of loops
2124   $max  = 100;                  // Just for security, prevent looops
2125   $ldap = NULL;                 // To check if created result a valid
2126   $keep = "";                   // save last failed parse string
2128   /* Check each parsed dn in ldap ? */
2129   if($config!==NULL && $verify_in_ldap){
2130     $ldap = $config->get_ldap_link();
2131   }
2133   /* Lets start */
2134   $called = false;
2135   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2137     $cnt ++;
2138     if(!preg_match("/,/",$dn)){
2139       $next = false;
2140     }
2141     $object = preg_replace("/[,].*$/","",$dn);
2142     $dn     = preg_replace("/^[^,]+,/","",$dn);
2144     $called = true;
2146     /* Check if current dn is valid */
2147     if($ldap!==NULL){
2148       $ldap->cd($dn);
2149       $ldap->cat($dn,array("dn"));
2150       if($ldap->count()){
2151         $ret[]  = $keep.$object;
2152         $keep   = "";
2153       }else{
2154         $keep  .= $object.",";
2155       }
2156     }else{
2157       $ret[]  = $keep.$object;
2158       $keep   = "";
2159     }
2160   }
2162   /* No dn was posted */
2163   if($cnt == 0 && !empty($dn)){
2164     $ret[] = $dn;
2165   }
2167   /* Append the rest */
2168   $test = $keep.$dn;
2169   if($called && !empty($test)){
2170     $ret[] = $keep.$dn;
2171   }
2172   $ret['count'] = count($ret) - 1;
2174   return($ret);
2178 function get_base_from_hook($dn, $attrib)
2180   global $config;
2182   if ($config->get_cfg_value("baseIdHook") != ""){
2183     
2184     /* Call hook script - if present */
2185     $command= $config->get_cfg_value("baseIdHook");
2187     if ($command != ""){
2188       $command.= " '".LDAP::fix($dn)."' $attrib";
2189       if (check_command($command)){
2190         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2191         exec($command, $output);
2192         if (preg_match("/^[0-9]+$/", $output[0])){
2193           return ($output[0]);
2194         } else {
2195           msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2196           return ($config->get_cfg_value("uidNumberBase"));
2197         }
2198       } else {
2199         msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2200         return ($config->get_cfg_value("uidNumberBase"));
2201       }
2203     } else {
2205       msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2206       return ($config->get_cfg_value("uidNumberBase"));
2208     }
2209   }
2213 function check_schema_version($class, $version)
2215   return preg_match("/\(v$version\)/", $class['DESC']);
2219 function check_schema($cfg,$rfc2307bis = FALSE)
2221   $messages= array();
2223   /* Get objectclasses */
2224   $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2225   $objectclasses = $ldap->get_objectclasses();
2226   if(count($objectclasses) == 0){
2227     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2228   }
2230   /* This is the default block used for each entry.
2231    *  to avoid unset indexes.
2232    */
2233   $def_check = array("REQUIRED_VERSION" => "0",
2234       "SCHEMA_FILES"     => array(),
2235       "CLASSES_REQUIRED" => array(),
2236       "STATUS"           => FALSE,
2237       "IS_MUST_HAVE"     => FALSE,
2238       "MSG"              => "",
2239       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2241   /* The gosa base schema */
2242   $checks['gosaObject'] = $def_check;
2243   $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2244   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2245   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2246   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2248   /* GOsa Account class */
2249   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.1";
2250   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2251   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2252   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2253   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2255   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2256   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2257   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2258   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2259   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2260   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2262   /* Some other checks */
2263   foreach(array(
2264         "gosaCacheEntry"        => array("version" => "2.6.1"),
2265         "gosaDepartment"        => array("version" => "2.6.1"),
2266         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2267         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2268         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2269         "gosaUserTemplate"      => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2270         "gosaMailAccount"       => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2271         "gosaProxyAccount"      => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2272         "gosaApplication"       => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2273         "gosaApplicationGroup"  => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2274         "GOhard"                => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2275         "gotoTerminal"          => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2276         "goServer"              => array("version" => "2.6.1","class" => "server","file" => "goserver.schema"),
2277         "goTerminalServer"      => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2278         "goShareServer"         => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2279         "goNtpServer"           => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2280         "goSyslogServer"        => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2281         "goLdapServer"          => array("version" => "2.6.1"),
2282         "goCupsServer"          => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2283         "goImapServer"          => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2284         "goKrbServer"           => array("version" => "2.6.1"),
2285         "goFaxServer"           => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2286         ) as $name => $values){
2288           $checks[$name] = $def_check;
2289           if(isset($values['version'])){
2290             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2291           }
2292           if(isset($values['file'])){
2293             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2294           }
2295           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2296         }
2297   foreach($checks as $name => $value){
2298     foreach($value['CLASSES_REQUIRED'] as $class){
2300       if(!isset($objectclasses[$name])){
2301         $checks[$name]['STATUS'] = FALSE;
2302         if($value['IS_MUST_HAVE']){
2303           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2304         }else{
2305           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2306         }
2307       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2308         $checks[$name]['STATUS'] = FALSE;
2310         if($value['IS_MUST_HAVE']){
2311           $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2312         }else{
2313           $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2314         }
2315       }else{
2316         $checks[$name]['STATUS'] = TRUE;
2317         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2318       }
2319     }
2320   }
2322   $tmp = $objectclasses;
2324   /* The gosa base schema */
2325   $checks['posixGroup'] = $def_check;
2326   $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2327   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2328   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2329   $checks['posixGroup']['STATUS']           = TRUE;
2330   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2331   $checks['posixGroup']['MSG']              = "";
2332   $checks['posixGroup']['INFO']             = "";
2334   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2335   if(isset($tmp['posixGroup'])){
2337     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2338       $checks['posixGroup']['STATUS']           = FALSE;
2339       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2340       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2341     }
2342     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2343       $checks['posixGroup']['STATUS']           = FALSE;
2344       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2345       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2346     }
2347   }
2349   return($checks);
2353 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2355   $tmp = array(
2356         "de_DE" => "German",
2357         "fr_FR" => "French",
2358         "it_IT" => "Italian",
2359         "es_ES" => "Spanish",
2360         "en_US" => "English",
2361         "nl_NL" => "Dutch",
2362         "pl_PL" => "Polish",
2363         #"sv_SE" => "Swedish",
2364         "zh_CN" => "Chinese",
2365         "vi_VN" => "Vietnamese",
2366         "ru_RU" => "Russian");
2367   
2368   $tmp2= array(
2369         "de_DE" => _("German"),
2370         "fr_FR" => _("French"),
2371         "it_IT" => _("Italian"),
2372         "es_ES" => _("Spanish"),
2373         "en_US" => _("English"),
2374         "nl_NL" => _("Dutch"),
2375         "pl_PL" => _("Polish"),
2376         #"sv_SE" => _("Swedish"),
2377         "zh_CN" => _("Chinese"),
2378         "vi_VN" => _("Vietnamese"),
2379         "ru_RU" => _("Russian"));
2381   $ret = array();
2382   if($languages_in_own_language){
2384     $old_lang = setlocale(LC_ALL, 0);
2386     /* If the locale wasn't correclty set before, there may be an incorrect
2387         locale returned. Something like this: 
2388           C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2389         Extract the locale name from this string and use it to restore old locale.
2390      */
2391     if(preg_match("/LC_CTYPE/",$old_lang)){
2392       $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2393     }
2394     
2395     foreach($tmp as $key => $name){
2396       $lang = $key.".UTF-8";
2397       setlocale(LC_ALL, $lang);
2398       if($strip_region_tag){
2399         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2400       }else{
2401         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2402       }
2403     }
2404     setlocale(LC_ALL, $old_lang);
2405   }else{
2406     foreach($tmp as $key => $name){
2407       if($strip_region_tag){
2408         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2409       }else{
2410         $ret[$key] = _($name);
2411       }
2412     }
2413   }
2414   return($ret);
2418 /* Returns contents of the given POST variable and check magic quotes settings */
2419 function get_post($name)
2421   if(!isset($_POST[$name])){
2422     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2423     return(FALSE);
2424   }
2425   if(get_magic_quotes_gpc()){
2426     return(stripcslashes($_POST[$name]));
2427   }else{
2428     return($_POST[$name]);
2429   }
2433 /* Return class name in correct case */
2434 function get_correct_class_name($cls)
2436   global $class_mapping;
2437   if(isset($class_mapping) && is_array($class_mapping)){
2438     foreach($class_mapping as $class => $file){
2439       if(preg_match("/^".$cls."$/i",$class)){
2440         return($class);
2441       }
2442     }
2443   }
2444   return(FALSE);
2448 // change_password, changes the Password, of the given dn
2449 function change_password ($dn, $password, $mode=0, $hash= "")
2451   global $config;
2452   $newpass= "";
2454   /* Convert to lower. Methods are lowercase */
2455   $hash= strtolower($hash);
2457   // Get all available encryption Methods
2459   // NON STATIC CALL :)
2460   $methods = new passwordMethod(session::get('config'));
2461   $available = $methods->get_available_methods();
2463   // read current password entry for $dn, to detect the encryption Method
2464   $ldap       = $config->get_ldap_link();
2465   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2466   $attrs      = $ldap->fetch ();
2468   /* Is ensure that clear passwords will stay clear */
2469   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2470     $hash = "clear";
2471   }
2473   // Detect the encryption Method
2474   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2476     /* Check for supported algorithm */
2477     mt_srand((double) microtime()*1000000);
2479     /* Extract used hash */
2480     if ($hash == ""){
2481       $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2482     } else {
2483       $test = new $available[$hash]($config,$dn);
2484       $test->set_hash($hash);
2485     }
2487   } else {
2488     // User MD5 by default
2489     $hash= "md5";
2490     $test = new  $available['md5']($config);
2491   }
2493   if($test instanceOf passwordMethod){
2495     $deactivated = $test->is_locked($config,$dn);
2497     /* Feed password backends with information */
2498     $test->dn= $dn;
2499     $test->attrs= $attrs;
2500     $newpass= $test->generate_hash($password);
2502     // Update shadow timestamp?
2503     if (isset($attrs["shadowLastChange"][0])){
2504       $shadow= (int)(date("U") / 86400);
2505     } else {
2506       $shadow= 0;
2507     }
2509     // Write back modified entry
2510     $ldap->cd($dn);
2511     $attrs= array();
2513     // Not for groups
2514     if ($mode == 0){
2516       if ($shadow != 0){
2517         $attrs['shadowLastChange']= $shadow;
2518       }
2520       // Create SMB Password
2521       $attrs= generate_smb_nt_hash($password);
2522     }
2524     $attrs['userPassword']= array();
2525     $attrs['userPassword']= $newpass;
2527     $ldap->modify($attrs);
2529     /* Read ! if user was deactivated */
2530     if($deactivated){
2531       $test->lock_account($config,$dn);
2532     }
2534     new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2536     if (!$ldap->success()) {
2537       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2538     } else {
2540       /* Run backend method for change/create */
2541       if(!$test->set_password($password)){
2542         return(FALSE);
2543       }
2545       /* Find postmodify entries for this class */
2546       $command= $config->search("password", "POSTMODIFY",array('menu'));
2548       if ($command != ""){
2549         /* Walk through attribute list */
2550         $command= preg_replace("/%userPassword/", $password, $command);
2551         $command= preg_replace("/%dn/", $dn, $command);
2553         if (check_command($command)){
2554           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2555           exec($command);
2556         } else {
2557           $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2558           msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2559         }
2560       }
2561     }
2562     return(TRUE);
2563   }
2567 // Return something like array['sambaLMPassword']= "lalla..."
2568 function generate_smb_nt_hash($password)
2570   global $config;
2572   # Try to use gosa-si?
2573   if ($config->get_cfg_value("gosaSupportURI") != ""){
2574         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2575     if (isset($res['XML']['HASH'])){
2576         $hash= $res['XML']['HASH'];
2577     } else {
2578       $hash= "";
2579     }
2580   } else {
2581           $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
2582           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2584           exec($tmp, $ar);
2585           flush();
2586           reset($ar);
2587           $hash= current($ar);
2588   }
2590   if ($hash == "") {
2591           msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2592           return ("");
2593   }
2595   list($lm,$nt)= split (":", trim($hash));
2597   if ($config->get_cfg_value("sambaversion") == 3) {
2598           $attrs['sambaLMPassword']= $lm;
2599           $attrs['sambaNTPassword']= $nt;
2600           $attrs['sambaPwdLastSet']= date('U');
2601           $attrs['sambaBadPasswordCount']= "0";
2602           $attrs['sambaBadPasswordTime']= "0";
2603   } else {
2604           $attrs['lmPassword']= $lm;
2605           $attrs['ntPassword']= $nt;
2606           $attrs['pwdLastSet']= date('U');
2607   }
2608   return($attrs);
2612 function getEntryCSN($dn)
2614   global $config;
2615   if(empty($dn) || !is_object($config)){
2616     return("");
2617   }
2619   /* Get attribute that we should use as serial number */
2620   $attr= $config->get_cfg_value("modificationDetectionAttribute");
2621   if($attr != ""){
2622     $ldap = $config->get_ldap_link();
2623     $ldap->cat($dn,array($attr));
2624     $csn = $ldap->fetch();
2625     if(isset($csn[$attr][0])){
2626       return($csn[$attr][0]);
2627     }
2628   }
2629   return("");
2633 /* Add a given objectClass to an attrs entry */
2634 function add_objectClass($classes, &$attrs)
2636   if (is_array($classes)){
2637     $list= $classes;
2638   } else {
2639     $list= array($classes);
2640   }
2642   foreach ($list as $class){
2643     $attrs['objectClass'][]= $class;
2644   }
2648 /* Removes a given objectClass from the attrs entry */
2649 function remove_objectClass($classes, &$attrs)
2651   if (isset($attrs['objectClass'])){
2652     /* Array? */
2653     if (is_array($classes)){
2654       $list= $classes;
2655     } else {
2656       $list= array($classes);
2657     }
2659     $tmp= array();
2660     foreach ($attrs['objectClass'] as $oc) {
2661       foreach ($list as $class){
2662         if (strtolower($oc) != strtolower($class)){
2663           $tmp[]= $oc;
2664         }
2665       }
2666     }
2667     $attrs['objectClass']= $tmp;
2668   }
2671 /*! \brief  Initialize a file download with given content, name and data type. 
2672  *  @param  data  String The content to send.
2673  *  @param  name  String The name of the file.
2674  *  @param  type  String The content identifier, default value is "application/octet-stream";
2675  */
2676 function send_binary_content($data,$name,$type = "application/octet-stream")
2678   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2679   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2680   header("Cache-Control: no-cache");
2681   header("Pragma: no-cache");
2682   header("Cache-Control: post-check=0, pre-check=0");
2683   header("Content-type: ".$type."");
2685   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2687   /* Strip name if it is a complete path */
2688   if (preg_match ("/\//", $name)) {
2689         $name= basename($name);
2690   }
2691   
2692   /* force download dialog */
2693   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2694     header('Content-Disposition: filename="'.$name.'"');
2695   } else {
2696     header('Content-Disposition: attachment; filename="'.$name.'"');
2697   }
2699   echo $data;
2700   exit();
2704 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2706   if(is_string($str)){
2707     return(htmlentities($str,$type,$charset));
2708   }elseif(is_array($str)){
2709     foreach($str as $name => $value){
2710       $str[$name] = reverse_html_entities($value,$type,$charset);
2711     }
2712   }
2713   return($str);
2717 /*! \brief Encode special string characters so we can use the string in \
2718            HTML output, without breaking quotes.
2719     @param  The String we want to encode.
2720     @return The encoded String
2721  */
2722 function xmlentities($str)
2723
2724   if(is_string($str)){
2726     static $asc2uni= array();
2727     if (!count($asc2uni)){
2728       for($i=128;$i<256;$i++){
2729     #    $asc2uni[chr($i)] = "&#x".dechex($i).";";
2730       }
2731     }
2733     $str = str_replace("&", "&amp;", $str);
2734     $str = str_replace("<", "&lt;", $str);
2735     $str = str_replace(">", "&gt;", $str);
2736     $str = str_replace("'", "&apos;", $str);
2737     $str = str_replace("\"", "&quot;", $str);
2738     $str = str_replace("\r", "", $str);
2739     $str = strtr($str,$asc2uni);
2740     return $str;
2741   }elseif(is_array($str)){
2742     foreach($str as $name => $value){
2743       $str[$name] = xmlentities($value);
2744     }
2745   }
2746   return($str);
2750 /*! \brief  Updates all accessTo attributes from a given value to a new one.
2751             For example if a host is renamed.
2752     @param  String  $from The source accessTo name.
2753     @param  String  $to   The destination accessTo name.
2754 */
2755 function update_accessTo($from,$to)
2757   global $config;
2758   $ldap = $config->get_ldap_link();
2759   $ldap->cd($config->current['BASE']);
2760   $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2761   while($attrs = $ldap->fetch()){
2762     $new_attrs = array("accessTo" => array());
2763     $dn = $attrs['dn'];
2764     for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2765       $new_attrs['objectClass'][] =  $attrs['objectClass'][$i];
2766     }
2767     for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2768       if($attrs['accessTo'][$i] == $from){
2769         if(!empty($to)){
2770           $new_attrs['accessTo'][] =  $to;
2771         }
2772       }else{
2773         $new_attrs['accessTo'][] =  $attrs['accessTo'][$i]; 
2774       }
2775     }
2776     $ldap->cd($dn);
2777     $ldap->modify($new_attrs);
2778     if (!$ldap->success()){
2779       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2780     }
2781     new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2782   }
2786 function get_random_char () {
2787      $randno = rand (0, 63);
2788      if ($randno < 12) {
2789          return (chr ($randno + 46)); // Digits, '/' and '.'
2790      } else if ($randno < 38) {
2791          return (chr ($randno + 53)); // Uppercase
2792      } else {
2793          return (chr ($randno + 59)); // Lowercase
2794      }
2798 function cred_encrypt($input, $password) {
2800   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2801   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2803   return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2807 function cred_decrypt($input,$password) {
2808   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2809   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2811   return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2814 function get_object_info()
2816   return(session::get('objectinfo'));
2819 function set_object_info($str = "")
2821   session::set('objectinfo',$str);
2825 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2826 ?>