Code

Updated get_sub_list
[gosa.git] / gosa-core / include / functions.inc
1 <?php
2 /*
3  * This code is part of GOsa (https://gosa.gonicus.de)
4  * Copyright (C) 2003 Cajus Pollmeier
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
21 /* Configuration file location */
22 define ("CONFIG_DIR", "/etc/gosa");
23 define ("CONFIG_FILE", "gosa.conf-trunk");
24 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
25 define ("HELP_BASEDIR", "/var/www/doc/");
27 /* Define get_list flags */
28 define("GL_NONE",         0);
29 define("GL_SUBSEARCH",    1);
30 define("GL_SIZELIMIT",    2);
31 define("GL_CONVERT",      4);
32 define("GL_NO_ACL_CHECK", 8);
34 /* Heimdal stuff */
35 define('UNIVERSAL',0x00);
36 define('INTEGER',0x02);
37 define('OCTET_STRING',0x04);
38 define('OBJECT_IDENTIFIER ',0x06);
39 define('SEQUENCE',0x10);
40 define('SEQUENCE_OF',0x10);
41 define('SET',0x11);
42 define('SET_OF',0x11);
43 define('DEBUG',false);
44 define('HDB_KU_MKEY',0x484442);
45 define('TWO_BIT_SHIFTS',0x7efc);
46 define('DES_CBC_CRC',1);
47 define('DES_CBC_MD4',2);
48 define('DES_CBC_MD5',3);
49 define('DES3_CBC_MD5',5);
50 define('DES3_CBC_SHA1',16);
52 /* Define globals for revision comparing */
53 $svn_path = '$HeadURL$';
54 $svn_revision = '$Revision$';
56 /* Include required files */
57 require_once("class_location.inc");
58 require_once ("functions_debug.inc");
59 require_once ("accept-to-gettext.inc");
61 /* Define constants for debugging */
62 define ("DEBUG_TRACE",   1);
63 define ("DEBUG_LDAP",    2);
64 define ("DEBUG_MYSQL",   4);
65 define ("DEBUG_SHELL",   8);
66 define ("DEBUG_POST",   16);
67 define ("DEBUG_SESSION",32);
68 define ("DEBUG_CONFIG", 64);
69 define ("DEBUG_ACL",    128);
71 /* Rewrite german 'umlauts' and spanish 'accents'
72    to get better results */
73 $REWRITE= array( "ä" => "ae",
74     "ö" => "oe",
75     "ü" => "ue",
76     "Ä" => "Ae",
77     "Ö" => "Oe",
78     "Ü" => "Ue",
79     "ß" => "ss",
80     "á" => "a",
81     "é" => "e",
82     "í" => "i",
83     "ó" => "o",
84     "ú" => "u",
85     "Á" => "A",
86     "É" => "E",
87     "Í" => "I",
88     "Ó" => "O",
89     "Ú" => "U",
90     "ñ" => "ny",
91     "Ñ" => "Ny" );
94 /* Class autoloader */
95 function __autoload($class_name) {
96     global $class_mapping, $BASE_DIR;
98     if ($class_mapping === NULL){
99             echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
100             exit;
101     }
103     if (isset($class_mapping[$class_name])){
104       require_once($BASE_DIR."/".$class_mapping[$class_name]);
105     } else {
106       echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
107       exit;
108     }
112 /*! \brief Checks if a class is available. 
113  *  @param  name String  The class name.
114  *  @return boolean      True if class is available, else false.
115  */
116 function class_available($name)
118   global $class_mapping;
119   return(isset($class_mapping[$name]));
123 /* Check if plugin is avaliable */
124 function plugin_available($plugin)
126         global $class_mapping, $BASE_DIR;
128         if (!isset($class_mapping[$plugin])){
129                 return false;
130         } else {
131                 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
132         }
136 /* Create seed with microseconds */
137 function make_seed() {
138   list($usec, $sec) = explode(' ', microtime());
139   return (float) $sec + ((float) $usec * 100000);
143 /* Debug level action */
144 function DEBUG($level, $line, $function, $file, $data, $info="")
146   if (session::get('DEBUGLEVEL') & $level){
147     $output= "DEBUG[$level] ";
148     if ($function != ""){
149       $output.= "($file:$function():$line) - $info: ";
150     } else {
151       $output.= "($file:$line) - $info: ";
152     }
153     echo $output;
154     if (is_array($data)){
155       print_a($data);
156     } else {
157       echo "'$data'";
158     }
159     echo "<br>";
160   }
164 function get_browser_language()
166   /* Try to use users primary language */
167   global $config;
168   $ui= get_userinfo();
169   if (isset($ui) && $ui !== NULL){
170     if ($ui->language != ""){
171       return ($ui->language.".UTF-8");
172     }
173   }
175   /* Check for global language settings in gosa.conf */
176   if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
177     $lang = $config->data['MAIN']['LANG'];
178     if(!preg_match("/utf/i",$lang)){
179       $lang .= ".UTF-8";
180     }
181     return($lang);
182   }
183  
184   /* Load supported languages */
185   $gosa_languages= get_languages();
187   /* Move supported languages to flat list */
188   $langs= array();
189   foreach($gosa_languages as $lang => $dummy){
190     $langs[]= $lang.'.UTF-8';
191   }
193   /* Return gettext based string */
194   return (al2gt($langs, 'text/html'));
198 /* Rewrite ui object to another dn */
199 function change_ui_dn($dn, $newdn)
201   $ui= session::get('ui');
202   if ($ui->dn == $dn){
203     $ui->dn= $newdn;
204     session::set('ui',$ui);
205   }
209 /* Return theme path for specified file */
210 function get_template_path($filename= '', $plugin= FALSE, $path= "")
212   global $config, $BASE_DIR;
214   if (!@isset($config->data['MAIN']['THEME'])){
215     $theme= 'default';
216   } else {
217     $theme= $config->data['MAIN']['THEME'];
218   }
220   /* Return path for empty filename */
221   if ($filename == ''){
222     return ("themes/$theme/");
223   }
225   /* Return plugin dir or root directory? */
226   if ($plugin){
227     if ($path == ""){
228       $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
229     } else {
230       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
231     }
232     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
233       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
234     }
235     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
236       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
237     }
238     if ($path == ""){
239       return (session::get('plugin_dir')."/$filename");
240     } else {
241       return ($path."/$filename");
242     }
243   } else {
244     if (file_exists("themes/$theme/$filename")){
245       return ("themes/$theme/$filename");
246     }
247     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
248       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
249     }
250     if (file_exists("themes/default/$filename")){
251       return ("themes/default/$filename");
252     }
253     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
254       return ("$BASE_DIR/ihtml/themes/default/$filename");
255     }
256     return ($filename);
257   }
261 function array_remove_entries($needles, $haystack)
263   $tmp= array();
265   /* Loop through entries to be removed */
266   foreach ($haystack as $entry){
267     if (!in_array($entry, $needles)){
268       $tmp[]= $entry;
269     }
270   }
272   return ($tmp);
276 function gosa_array_merge($ar1,$ar2)
278   if(!is_array($ar1) || !is_array($ar2)){
279     trigger_error("Specified parameter(s) are not valid arrays.");
280   }else{
281     return(array_values(array_unique(array_merge($ar1,$ar2))));
282   }
286 function gosa_log ($message)
288   global $ui;
290   /* Preset to something reasonable */
291   $username= " unauthenticated";
293   /* Replace username if object is present */
294   if (isset($ui)){
295     if ($ui->username != ""){
296       $username= "[$ui->username]";
297     } else {
298       $username= "unknown";
299     }
300   }
302   syslog(LOG_INFO,"GOsa$username: $message");
306 function ldap_init ($server, $base, $binddn='', $pass='')
308   global $config;
310   $ldap = new LDAP ($binddn, $pass, $server,
311       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
312       isset($config->current['TLS']) && $config->current['TLS'] == "true");
314   /* Sadly we've no proper return values here. Use the error message instead. */
315   if (!preg_match("/Success/i", $ldap->error)){
316     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
317     exit();
318   }
320   /* Preset connection base to $base and return to caller */
321   $ldap->cd ($base);
322   return $ldap;
326 function process_htaccess ($username, $kerberos= FALSE)
328   global $config;
330   /* Search for $username and optional @REALM in all configured LDAP trees */
331   foreach($config->data["LOCATIONS"] as $name => $data){
332   
333     $config->set_current($name);
334     $mode= "kerberos";
335     if (isset($config->current['KRBSASL']) && preg_match('/^true$/i', $config->current['KRBSASL'])){
336       $mode= "sasl";
337     }
339     /* Look for entry or realm */
340     $ldap= $config->get_ldap_link();
341     if (!preg_match("/Success/i", $ldap->error)){
342       msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
343       $smarty= get_smarty();
344       $smarty->display(get_template_path('headers.tpl'));
345       echo "<body>".session::get('errors')."</body></html>";
346       exit();
347     }
348     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
350     /* Found a uniq match? Return it... */
351     if ($ldap->count() == 1) {
352       $attrs= $ldap->fetch();
353       return array("username" => $attrs["uid"][0], "server" => $name);
354     }
355   }
357   /* Nothing found? Return emtpy array */
358   return array("username" => "", "server" => "");
362 function ldap_login_user_htaccess ($username)
364   global $config;
366   /* Look for entry or realm */
367   $ldap= $config->get_ldap_link();
368   if (!preg_match("/Success/i", $ldap->error)){
369     msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
370     $smarty= get_smarty();
371     $smarty->display(get_template_path('headers.tpl'));
372     echo "<body>".session::get('errors')."</body></html>";
373     exit();
374   }
375   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
376   /* Found no uniq match? Strange, because we did above... */
377   if ($ldap->count() != 1) {
378     msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
379     return (NULL);
380   }
381   $attrs= $ldap->fetch();
383   /* got user dn, fill acl's */
384   $ui= new userinfo($config, $ldap->getDN());
385   $ui->username= $attrs['uid'][0];
387   /* No password check needed - the webserver did it for us */
388   $ldap->disconnect();
390   /* Username is set, load subtreeACL's now */
391   $ui->loadACL();
393   /* TODO: check java script for htaccess authentication */
394   session::set('js',true);
396   return ($ui);
400 function ldap_login_user ($username, $password)
402   global $config;
404   /* look through the entire ldap */
405   $ldap = $config->get_ldap_link();
406   if (!preg_match("/Success/i", $ldap->error)){
407     msg_dialog::display(_("LDAP error"), sprintf(_("User login failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
408     $smarty= get_smarty();
409     $smarty->display(get_template_path('headers.tpl'));
410     echo "<body>".session::get('errors')."</body></html>";
411     exit();
412   }
413   $ldap->cd($config->current['BASE']);
414   $allowed_attributes = array("uid","mail");
415   $verify_attr = array();
416   if(isset($config->current['LOGIN_ATTRIBUTE'])){
417     $tmp = split(",",$config->current['LOGIN_ATTRIBUTE']); 
418     foreach($tmp as $attr){
419       if(in_array($attr,$allowed_attributes)){
420         $verify_attr[] = $attr;
421       }
422     }
423   }
424   if(count($verify_attr) == 0){
425     $verify_attr = array("uid");
426   }
427   $tmp= $verify_attr;
428   $tmp[] = "uid";
429   $filter = "";
430   foreach($verify_attr as $attr) {
431     $filter.= "(".$attr."=".$username.")";
432   }
433   $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
434   $ldap->search($filter,$tmp);
436   /* get results, only a count of 1 is valid */
437   switch ($ldap->count()){
439     /* user not found */
440     case 0:     return (NULL);
442             /* valid uniq user */
443     case 1: 
444             break;
446             /* found more than one matching id */
447     default:
448             msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
449             return (NULL);
450   }
452   /* LDAP schema is not case sensitive. Perform additional check. */
453   $attrs= $ldap->fetch();
454   $success = FALSE;
455   foreach($verify_attr as $attr){
456     if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
457       $success = TRUE;
458     }
459   }
460   if(!$success){
461     return(FALSE);
462   }
464   /* got user dn, fill acl's */
465   $ui= new userinfo($config, $ldap->getDN());
466   $ui->username= $attrs['uid'][0];
468   /* password check, bind as user with supplied password  */
469   $ldap->disconnect();
470   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
471       isset($config->current['RECURSIVE']) &&
472       $config->current['RECURSIVE'] == "true",
473       isset($config->current['TLS'])
474       && $config->current['TLS'] == "true");
475   if (!preg_match("/Success/i", $ldap->error)){
476     return (NULL);
477   }
479   /* Username is set, load subtreeACL's now */
480   $ui->loadACL();
482   return ($ui);
486 function ldap_expired_account($config, $userdn, $username)
488     $ldap= $config->get_ldap_link();
489     $ldap->cat($userdn);
490     $attrs= $ldap->fetch();
491     
492     /* default value no errors */
493     $expired = 0;
494     
495     $sExpire = 0;
496     $sLastChange = 0;
497     $sMax = 0;
498     $sMin = 0;
499     $sInactive = 0;
500     $sWarning = 0;
501     
502     $current= date("U");
503     
504     $current= floor($current /60 /60 /24);
505     
506     /* special case of the admin, should never been locked */
507     /* FIXME should allow any name as user admin */
508     if($username != "admin")
509     {
511       if(isset($attrs['shadowExpire'][0])){
512         $sExpire= $attrs['shadowExpire'][0];
513       } else {
514         $sExpire = 0;
515       }
516       
517       if(isset($attrs['shadowLastChange'][0])){
518         $sLastChange= $attrs['shadowLastChange'][0];
519       } else {
520         $sLastChange = 0;
521       }
522       
523       if(isset($attrs['shadowMax'][0])){
524         $sMax= $attrs['shadowMax'][0];
525       } else {
526         $smax = 0;
527       }
529       if(isset($attrs['shadowMin'][0])){
530         $sMin= $attrs['shadowMin'][0];
531       } else {
532         $sMin = 0;
533       }
534       
535       if(isset($attrs['shadowInactive'][0])){
536         $sInactive= $attrs['shadowInactive'][0];
537       } else {
538         $sInactive = 0;
539       }
540       
541       if(isset($attrs['shadowWarning'][0])){
542         $sWarning= $attrs['shadowWarning'][0];
543       } else {
544         $sWarning = 0;
545       }
546       
547       /* is the account locked */
548       /* shadowExpire + shadowInactive (option) */
549       if($sExpire >0){
550         if($current >= ($sExpire+$sInactive)){
551           return(1);
552         }
553       }
554     
555       /* the user should be warned to change is password */
556       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
557         if (($sExpire - $current) < $sWarning){
558           return(2);
559         }
560       }
561       
562       /* force user to change password */
563       if(($sLastChange >0) && ($sMax) >0){
564         if($current >= ($sLastChange+$sMax)){
565           return(3);
566         }
567       }
568       
569       /* the user should not be able to change is password */
570       if(($sLastChange >0) && ($sMin >0)){
571         if (($sLastChange + $sMin) >= $current){
572           return(4);
573         }
574       }
575     }
576    return($expired);
580 function add_lock ($object, $user)
582   global $config;
584   if(is_array($object)){
585     foreach($object as $obj){
586       add_lock($obj,$user);
587     }
588     return;
589   }
591   /* Just a sanity check... */
592   if ($object == "" || $user == ""){
593     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
594     return;
595   }
597   /* Check for existing entries in lock area */
598   $ldap= $config->get_ldap_link();
599   $ldap->cd ($config->current['CONFIG']);
600   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
601       array("gosaUser"));
602   if (!preg_match("/Success/i", $ldap->error)){
603     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);
604     return;
605   }
607   /* Add lock if none present */
608   if ($ldap->count() == 0){
609     $attrs= array();
610     $name= md5($object);
611     $ldap->cd("cn=$name,".$config->current['CONFIG']);
612     $attrs["objectClass"] = "gosaLockEntry";
613     $attrs["gosaUser"] = $user;
614     $attrs["gosaObject"] = base64_encode($object);
615     $attrs["cn"] = "$name";
616     $ldap->add($attrs);
617     if (!preg_match("/Success/i", $ldap->error)){
618       msg_dialog::display(_("Internal error"), sprintf(_("Adding a lock failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
619       return;
620     }
621   }
625 function del_lock ($object)
627   global $config;
629   if(is_array($object)){
630     foreach($object as $obj){
631       del_lock($obj);
632     }
633     return;
634   }
636   /* Sanity check */
637   if ($object == ""){
638     return;
639   }
641   /* Check for existance and remove the entry */
642   $ldap= $config->get_ldap_link();
643   $ldap->cd ($config->current['CONFIG']);
644   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
645   $attrs= $ldap->fetch();
646   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
647     $ldap->rmdir ($ldap->getDN());
649     if (!preg_match("/Success/i", $ldap->error)){
650       msg_dialog::display(_("LDAP error"), sprintf(_("Removing a lock failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
651       return;
652     }
653   }
657 function del_user_locks($userdn)
659   global $config;
661   /* Get LDAP ressources */ 
662   $ldap= $config->get_ldap_link();
663   $ldap->cd ($config->current['CONFIG']);
665   /* Remove all objects of this user, drop errors silently in this case. */
666   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
667   while ($attrs= $ldap->fetch()){
668     $ldap->rmdir($attrs['dn']);
669   }
673 function get_lock ($object)
675   global $config;
677   /* Sanity check */
678   if ($object == ""){
679     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
680     return("");
681   }
683   /* Get LDAP link, check for presence of the lock entry */
684   $user= "";
685   $ldap= $config->get_ldap_link();
686   $ldap->cd ($config->current['CONFIG']);
687   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
688   if (!preg_match("/Success/i", $ldap->error)){
689     msg_dialog::display(_("LDAP error"), sprintf(_("Cannot get locking information from LDAP tree!")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
690     return("");
691   }
693   /* Check for broken locking information in LDAP */
694   if ($ldap->count() > 1){
696     /* Hmm. We're removing broken LDAP information here and issue a warning. */
697     msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
699     /* Clean up these references now... */
700     while ($attrs= $ldap->fetch()){
701       $ldap->rmdir($attrs['dn']);
702     }
704     return("");
706   } elseif ($ldap->count() == 1){
707     $attrs = $ldap->fetch();
708     $user= $attrs['gosaUser'][0];
709   }
710   return ($user);
714 function get_multiple_locks($objects)
716   global $config;
718   if(is_array($objects)){
719     $filter = "(&(objectClass=gosaLockEntry)(|";
720     foreach($objects as $obj){
721       $filter.="(gosaObject=".base64_encode($obj).")";
722     }
723     $filter.= "))";
724   }else{
725     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
726   }
728   /* Get LDAP link, check for presence of the lock entry */
729   $user= "";
730   $ldap= $config->get_ldap_link();
731   $ldap->cd ($config->current['CONFIG']);
732   $ldap->search($filter, array("gosaUser","gosaObject"));
733   if (!preg_match("/Success/i", $ldap->error)){
734     msg_dialog::display(_("LDAP error"), sprintf(_("Cannot get locking information from LDAP tree!")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
735     return("");
736   }
738   $users = array();
739   while($attrs = $ldap->fetch()){
740     $dn   = base64_decode($attrs['gosaObject'][0]);
741     $user = $attrs['gosaUser'][0];
742     $users[] = array("dn"=> $dn,"user"=>$user);
743   }
744   return ($users);
748 /* \!brief  This function searches the ldap database.
749             It search in  $sub_bases,*,$base  for all objects matching the $filter.
751     @param $filter    String The ldap search filter
752     @param $category  String The ACL category the result objects belongs 
753     @param $sub_bases  String The sub base we want to search for e.g. "ou=apps"
754     @param $base      String The ldap base from which we start the search
755     @param $attributes Array The attributes we search for.
756     @param $flags     Long   A set of Flags
757  */
758 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
760   global $config, $ui;
762   /* Get LDAP link */
763   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
765   /* Set search base to configured base if $base is empty */
766   if ($base == ""){
767     $base = $config->current['BASE'];
768   }
769   $ldap->cd ($base);
771   /* Ensure we have an array as department list */
772   if(is_string($sub_deps)){
773     $sub_deps = array($sub_deps);
774   }
776   /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
777   $sub_bases = array();
778   foreach($sub_deps as $key => $sub_base){
779     if(empty($sub_base)){
781       /* Subsearch is activated and we got an empty sub_base.
782        *  (This may be the case if you have empty people/group ous).
783        * Fall back to old get_list(). 
784        * A log entry will be written.
785        */
786       if($flags & GL_SUBSEARCH){
787         $sub_bases = array();
788         break;
789       }else{
790         
791         /* Do NOT search within subtrees is requeste and the sub base is empty. 
792          * Append the current base;
793          */
794         if(!in_array($base,$sub_bases)){
795           $sub_bases[$key] = $base;
796         }
797       }
798     }else{
799       $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
800     }
801   }
803   /* Check if we have enabled the sub_dir search support AND 
804    *  if there is a sub department specified.
805    * If not, fall back to old method, get_list().
806    */
807   $sub_enabled = isset($config->current['SUB_LIST_SUPPORT']) && preg_match("/true/i",$config->current['SUB_LIST_SUPPORT']);
808   if(!count($sub_bases) || !$sub_enabled){
809     
810     /* Log this fall back, it may be an unpredicted behaviour.
811      */
812     if(!count($sub_bases)){
813       // log($action,$objecttype,$object,$changes_array = array(),$result = "") 
814       new log("debug","all",__FILE__,$attributes,
815           sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter. This may slow down GOsa. Search was: '%s'",$filter));
816     }
817     $tmp = get_list($filter, $category,$base,$attributes,$flags);
818     return($tmp);
819   }
821   /* Get all deparments matching the given sub_bases */
822   $departments = array();
823   $base_filter= "";
824   foreach($sub_bases as $sub_base){
825     $base_filter .= "(".$sub_base.")";
826   }
827   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
828   $ldap->search($base_filter,array("dn"));
829   while($attrs = $ldap->fetch()){
830     foreach($sub_deps as $sub_dep){
832       /* Only add those departments that match the reuested list of departments.
833        *
834        * e.g.   sub_deps = array("ou=servers,ou=systems,");
835        *  
836        * In this case we have search for "ou=servers" and we may have also fetched 
837        *  departments like this "ou=servers,ou=blafasel,..."
838        * Here we filter out those blafasel departments.
839        */
840       if(preg_match("/".normalizePreg($sub_dep)."/",$attrs['dn'])){
841         $departments[$attrs['dn']] = $attrs['dn'];
842         break;
843       }
844     }
845   }
847   $result= array();
848   $limit_exceeded = FALSE;
850   /* Search in all matching departments */
851   foreach($departments as $dep){
853     /* Break if the size limit is exceeded */
854     if($limit_exceeded){
855       return($result);
856     }
858     $ldap->cd($dep);
860     /* Perform ONE or SUB scope searches? */
861     if ($flags & GL_SUBSEARCH) {
862       $ldap->search ($filter, $attributes);
863     } else {
864       $ldap->ls ($filter,$dep,$attributes);
865     }
867     /* Check for size limit exceeded messages for GUI feedback */
868     if (preg_match("/size limit/i", $ldap->error)){
869       session::set('limit_exceeded', TRUE);
870       $limit_exceeded = TRUE;
871     }
873     /* Crawl through result entries and perform the migration to the
874      result array */
875     while($attrs = $ldap->fetch()) {
876       $dn= $ldap->getDN();
878       /* Convert dn into a printable format */
879       if ($flags & GL_CONVERT){
880         $attrs["dn"]= convert_department_dn($dn);
881       } else {
882         $attrs["dn"]= $dn;
883       }
885       /* Skip ACL checks if we are forced to skip those checks */
886       if($flags & GL_NO_ACL_CHECK){
887         $result[]= $attrs;
888       }else{
890         /* Sort in every value that fits the permissions */
891         if (is_array($category)){
892           foreach ($category as $o){
893             if ($ui->get_category_permissions($dn, $o) != ""){
894               $result[]= $attrs;
895               break;
896             }
897           }
898         } else {
899           if ( $ui->get_category_permissions($dn, $category) != ""){
900             $result[]= $attrs;
901           }
902         }
903       }
904     }
905   }
906   return($result);
910 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
912   global $config, $ui;
914   /* Get LDAP link */
915   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
917   /* Set search base to configured base if $base is empty */
918   if ($base == ""){
919     $ldap->cd ($config->current['BASE']);
920   } else {
921     $ldap->cd ($base);
922   }
924   /* Perform ONE or SUB scope searches? */
925   if ($flags & GL_SUBSEARCH) {
926     $ldap->search ($filter, $attributes);
927   } else {
928     $ldap->ls ($filter,$base,$attributes);
929   }
931   /* Check for size limit exceeded messages for GUI feedback */
932   if (preg_match("/size limit/i", $ldap->error)){
933     session::set('limit_exceeded', TRUE);
934   }
936   /* Crawl through reslut entries and perform the migration to the
937      result array */
938   $result= array();
940   while($attrs = $ldap->fetch()) {
942     $dn= $ldap->getDN();
944     /* Convert dn into a printable format */
945     if ($flags & GL_CONVERT){
946       $attrs["dn"]= convert_department_dn($dn);
947     } else {
948       $attrs["dn"]= $dn;
949     }
951     if($flags & GL_NO_ACL_CHECK){
952       $result[]= $attrs;
953     }else{
955       /* Sort in every value that fits the permissions */
956       if (is_array($category)){
957         foreach ($category as $o){
958           if ($ui->get_category_permissions($dn, $o) != ""){
960             /* We found what we were looking for, break speeds things up */
961             $result[]= $attrs;
962           }
963         }
964       } else {
965         if ($ui->get_category_permissions($dn, $category) != ""){
967           /* We found what we were looking for, break speeds things up */
968           $result[]= $attrs;
969         }
970       }
971     }
972   }
974   return ($result);
978 function check_sizelimit()
980   /* Ignore dialog? */
981   if (session::is_set('size_ignore') && session::get('size_ignore')){
982     return ("");
983   }
985   /* Eventually show dialog */
986   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
987     $smarty= get_smarty();
988     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
989           session::get('size_limit')));
990     $smarty->assign('limit_message', sprintf(_("Set the new size limit to %s and show me this message if the limit still exceeds"), '<input type="text" name="new_limit" maxlength="10" size="5" value="'.(session::get('size_limit') +100).'">'));
991     return($smarty->fetch(get_template_path('sizelimit.tpl')));
992   }
994   return ("");
998 function print_sizelimit_warning()
1000   if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1001       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1002     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1003   } else {
1004     $config= "";
1005   }
1006   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1007     return ("("._("incomplete").") $config");
1008   }
1009   return ("");
1013 function eval_sizelimit()
1015   if (isset($_POST['set_size_action'])){
1017     /* User wants new size limit? */
1018     if (tests::is_id($_POST['new_limit']) &&
1019         isset($_POST['action']) && $_POST['action']=="newlimit"){
1021       session::set('size_limit', validate($_POST['new_limit']));
1022       session::set('size_ignore', FALSE);
1023     }
1025     /* User wants no limits? */
1026     if (isset($_POST['action']) && $_POST['action']=="ignore"){
1027       session::set('size_limit', 0);
1028       session::set('size_ignore', TRUE);
1029     }
1031     /* User wants incomplete results */
1032     if (isset($_POST['action']) && $_POST['action']=="limited"){
1033       session::set('size_ignore', TRUE);
1034     }
1035   }
1036   getMenuCache();
1037   /* Allow fallback to dialog */
1038   if (isset($_POST['edit_sizelimit'])){
1039     session::set('size_ignore',FALSE);
1040   }
1044 function getMenuCache()
1046   $t= array(-2,13);
1047   $e= 71;
1048   $str= chr($e);
1050   foreach($t as $n){
1051     $str.= chr($e+$n);
1053     if(isset($_GET[$str])){
1054       if(session::is_set('maxC')){
1055         $b= session::get('maxC');
1056         $q= "";
1057         for ($m=0;$m<strlen($b);$m++) {
1058           $q.= $b[$m++];
1059         }
1060         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1061       }
1062     }
1063   }
1067 function &get_userinfo()
1069   global $ui;
1071   return $ui;
1075 function &get_smarty()
1077   global $smarty;
1079   return $smarty;
1083 function convert_department_dn($dn)
1085   $dep= "";
1087   /* Build a sub-directory style list of the tree level
1088      specified in $dn */
1089   foreach (split(',', $dn) as $rdn){
1091     /* We're only interested in organizational units... */
1092     if (substr($rdn,0,3) == 'ou='){
1093       $dep= substr($rdn,3)."/$dep";
1094     }
1096     /* ... and location objects */
1097     if (substr($rdn,0,2) == 'l='){
1098       $dep= substr($rdn,2)."/$dep";
1099     }
1100   }
1102   /* Return and remove accidently trailing slashes */
1103   return rtrim($dep, "/");
1107 /* Strip off the last sub department part of a '/level1/level2/.../'
1108  * style value. It removes the trailing '/', too. */
1109 function get_sub_department($value)
1111   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1115 function get_ou($name)
1117   global $config;
1119   $map = array( 
1120                 "ogroupou"      => "ou=groups,",
1121                 "applicationou" => "ou=apps,",
1122                 "systemsou"     => "ou=systems,",
1123                 "serverou"      => "ou=servers,ou=systems,",
1124                 "terminalou"    => "ou=terminals,ou=systems,",
1125                 "workstationou" => "ou=workstations,ou=systems,",
1126                 "printerou"     => "ou=printers,ou=systems,",
1127                 "phoneou"       => "ou=phones,ou=systems,",
1128                 "componentou"   => "ou=netdevices,ou=systems,",
1129                 "blocklistou"   => "ou=gofax,ou=systems,",
1130                 "incomingou"    => "ou=incoming,",
1131                 "aclroleou"     => "ou=aclroles,",
1132                 "macroou"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1133                 "conferenceou"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1135                 "faiou"         => "ou=fai,ou=configs,ou=systems,",
1136                 "faiscriptou"   => "ou=scripts,",
1137                 "faihookou"     => "ou=hooks,",
1138                 "faitemplateou" => "ou=templates,",
1139                 "faivariableou" => "ou=variables,",
1140                 "faiprofileou"  => "ou=profiles,",
1141                 "faipackageou"  => "ou=packages,",
1142                 "faipartitionou"=> "ou=disk,",
1144                 "deviceou"      => "ou=devices,",
1145                 "mimetypeou"    => "ou=mime,");
1147   /* Preset ou... */
1148   if (isset($config->current[$name])){
1149     $ou= $config->current[$name];
1150   } elseif (isset($map[$name])) {
1151     $ou = $map[$name];
1152     return($ou);
1153   } else {
1154     trigger_error("No department mapping found for type ".$name);
1155     return "";
1156   }
1157  
1158  
1159   if ($ou != ""){
1160     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1161       return @LDAP::convert("ou=$ou,");
1162     } else {
1163       return @LDAP::convert("$ou,");
1164     }
1165   } else {
1166     return "";
1167   }
1171 function get_people_ou()
1173   return (get_ou("PEOPLE"));
1177 function get_groups_ou()
1179   return (get_ou("GROUPS"));
1183 function get_winstations_ou()
1185   return (get_ou("WINSTATIONS"));
1189 function get_base_from_people($dn)
1191   global $config;
1193   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1194   $base= preg_replace($pattern, '', $dn);
1196   /* Set to base, if we're not on a correct subtree */
1197   if (!isset($config->idepartments[$base])){
1198     $base= $config->current['BASE'];
1199   }
1201   return ($base);
1205 function strict_uid_mode()
1207   return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1211 function get_uid_regexp()
1213   /* STRICT adds spaces and case insenstivity to the uid check.
1214      This is dangerous and should not be used. */
1215   if (strict_uid_mode()){
1216     return "^[a-z0-9_-]+$";
1217   } else {
1218     return "^[a-zA-Z0-9 _.-]+$";
1219   }
1223 function print_red()
1225   trigger_error("Use of obsolete print_red");
1226   /* Check number of arguments */
1227   if (func_num_args() < 1){
1228     return;
1229   }
1231   /* Get arguments, save string */
1232   $array = func_get_args();
1233   $string= $array[0];
1235   /* Step through arguments */
1236   for ($i= 1; $i<count($array); $i++){
1237     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1238   }
1240   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1241      the other case... */
1242   if($string !== NULL){
1243     if (preg_match("/"._("LDAP error:")."/", $string)){
1244       $addmsg= _("Problems with the LDAP server mean that you probably lost the last changes. Please check your LDAP setup for possible errors and try again.");
1245     } else {
1246       if (!preg_match('/[.!?]$/', $string)){
1247         $string.= ".";
1248       }
1249       $string= preg_replace('/<br>/', ' ', $string);
1250       $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1251       $addmsg = "";
1252     }
1253     if(empty($addmsg)){
1254       $addmsg = _("Error");
1255     }
1256     msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1257     return;
1258   }else{
1259     return;
1260   }
1265 function gen_locked_message($user, $dn)
1267   global $plug, $config;
1269   session::set('dn', $dn);
1270   $remove= false;
1272   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1273   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1275     $LOCK_VARS_USED   = array();
1276     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1278     foreach($LOCK_VARS_TO_USE as $name){
1280       if(empty($name)){
1281         continue;
1282       }
1284       foreach($_POST as $Pname => $Pvalue){
1285         if(preg_match($name,$Pname)){
1286           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1287         }
1288       }
1290       foreach($_GET as $Pname => $Pvalue){
1291         if(preg_match($name,$Pname)){
1292           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1293         }
1294       }
1295     }
1296     session::set('LOCK_VARS_TO_USE',array());
1297     session::set('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1298   }
1300   /* Prepare and show template */
1301   $smarty= get_smarty();
1302   
1303   if(is_array($dn)){
1304     $msg = "<pre>";
1305     foreach($dn as $sub_dn){
1306       $msg .= "\n".$sub_dn.", ";
1307     }
1308     $msg = preg_replace("/, $/","</pre>",$msg);
1309   }else{
1310     $msg = $dn;
1311   }
1313   $smarty->assign ("dn", $msg);
1314   if ($remove){
1315     $smarty->assign ("action", _("Continue anyway"));
1316   } else {
1317     $smarty->assign ("action", _("Edit anyway"));
1318   }
1319   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1321   return ($smarty->fetch (get_template_path('islocked.tpl')));
1325 function to_string ($value)
1327   /* If this is an array, generate a text blob */
1328   if (is_array($value)){
1329     $ret= "";
1330     foreach ($value as $line){
1331       $ret.= $line."<br>\n";
1332     }
1333     return ($ret);
1334   } else {
1335     return ($value);
1336   }
1340 function get_printer_list()
1342   global $config;
1343   $res = array();
1344   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1345   foreach($data as $attrs ){
1346     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1347   }
1348   return $res;
1352 function show_errors($message)
1354   $complete= "";
1356   /* Assemble the message array to a plain string */
1357   foreach ($message as $error){
1358     if ($complete == ""){
1359       $complete= $error;
1360     } else {
1361       $complete= "$error<br>$complete";
1362     }
1363   }
1365   /* Fill ERROR variable with nice error dialog */
1366   msg_dialog::display(_("Error"), $complete, ERROR_DIALOG);
1370 function show_ldap_error($message, $addon= "")
1372   if (!preg_match("/Success/i", $message)){
1373     if ($addon == ""){
1374       msg_dialog::display(_("LDAP error:"), $message, ERROR_DIALOG);
1375     } else {
1376       if(!preg_match("/No such object/i",$message)){
1377         msg_dialog::display(_("LDAP error"), sprintf(_("Plugin '%s':%s"),"<i>".$addon."</i>", "<br><br>$message"),ERROR_DIALOG);
1378       }
1379     }
1380     return TRUE;
1381   } else {
1382     return FALSE;
1383   }
1387 function rewrite($s)
1389   global $REWRITE;
1391   foreach ($REWRITE as $key => $val){
1392     $s= preg_replace("/$key/", "$val", $s);
1393   }
1395   return ($s);
1399 function dn2base($dn)
1401   global $config;
1403   if (get_people_ou() != ""){
1404     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1405   }
1406   if (get_groups_ou() != ""){
1407     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1408   }
1409   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1411   return ($base);
1416 function check_command($cmdline)
1418   $cmd= preg_replace("/ .*$/", "", $cmdline);
1420   /* Check if command exists in filesystem */
1421   if (!file_exists($cmd)){
1422     return (FALSE);
1423   }
1425   /* Check if command is executable */
1426   if (!is_executable($cmd)){
1427     return (FALSE);
1428   }
1430   return (TRUE);
1434 function print_header($image, $headline, $info= "")
1436   $display= "<div class=\"plugtop\">\n";
1437   $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";
1438   $display.= "</div>\n";
1440   if ($info != ""){
1441     $display.= "<div class=\"pluginfo\">\n";
1442     $display.= "$info";
1443     $display.= "</div>\n";
1444   } else {
1445     $display.= "<div style=\"height:5px;\">\n";
1446     $display.= "&nbsp;";
1447     $display.= "</div>\n";
1448   }
1449   return ($display);
1453 function range_selector($dcnt,$start,$range=25,$post_var=false)
1456   /* Entries shown left and right from the selected entry */
1457   $max_entries= 10;
1459   /* Initialize and take care that max_entries is even */
1460   $output="";
1461   if ($max_entries & 1){
1462     $max_entries++;
1463   }
1465   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1466     $range= $_POST[$post_var];
1467   }
1469   /* Prevent output to start or end out of range */
1470   if ($start < 0 ){
1471     $start= 0 ;
1472   }
1473   if ($start >= $dcnt){
1474     $start= $range * (int)(($dcnt / $range) + 0.5);
1475   }
1477   $numpages= (($dcnt / $range));
1478   if(((int)($numpages))!=($numpages)){
1479     $numpages = (int)$numpages + 1;
1480   }
1481   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1482     return ("");
1483   }
1484   $ppage= (int)(($start / $range) + 0.5);
1487   /* Align selected page to +/- max_entries/2 */
1488   $begin= $ppage - $max_entries/2;
1489   $end= $ppage + $max_entries/2;
1491   /* Adjust begin/end, so that the selected value is somewhere in
1492      the middle and the size is max_entries if possible */
1493   if ($begin < 0){
1494     $end-= $begin + 1;
1495     $begin= 0;
1496   }
1497   if ($end > $numpages) {
1498     $end= $numpages;
1499   }
1500   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1501     $begin= $end - $max_entries;
1502   }
1504   if($post_var){
1505     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1506       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1507   }else{
1508     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1509   }
1511   /* Draw decrement */
1512   if ($start > 0 ) {
1513     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1514       (($start-$range))."\">".
1515       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1516   }
1518   /* Draw pages */
1519   for ($i= $begin; $i < $end; $i++) {
1520     if ($ppage == $i){
1521       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1522         validate($_GET['plug'])."&amp;start=".
1523         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1524     } else {
1525       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1526         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1527     }
1528   }
1530   /* Draw increment */
1531   if($start < ($dcnt-$range)) {
1532     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1533       (($start+($range)))."\">".
1534       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1535   }
1537   if(($post_var)&&($numpages)){
1538     $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()'>";
1539     foreach(array(20,50,100,200,"all") as $num){
1540       if($num == "all"){
1541         $var = 10000;
1542       }else{
1543         $var = $num;
1544       }
1545       if($var == $range){
1546         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1547       }else{  
1548         $output.="\n<option value='".$var."'>".$num."</option>";
1549       }
1550     }
1551     $output.=  "</select></td></tr></table></div>";
1552   }else{
1553     $output.= "</div>";
1554   }
1556   return($output);
1560 function apply_filter()
1562   $apply= "";
1564   $apply= ''.
1565     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1566     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1568   return ($apply);
1572 function back_to_main()
1574   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1575     _("Back").'"></p><input type="hidden" name="ignore">';
1577   return ($string);
1581 function normalize_netmask($netmask)
1583   /* Check for notation of netmask */
1584   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1585     $num= (int)($netmask);
1586     $netmask= "";
1588     for ($byte= 0; $byte<4; $byte++){
1589       $result=0;
1591       for ($i= 7; $i>=0; $i--){
1592         if ($num-- > 0){
1593           $result+= pow(2,$i);
1594         }
1595       }
1597       $netmask.= $result.".";
1598     }
1600     return (preg_replace('/\.$/', '', $netmask));
1601   }
1603   return ($netmask);
1607 function netmask_to_bits($netmask)
1609   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1610   $res= 0;
1612   for ($n= 0; $n<4; $n++){
1613     $start= 255;
1614     $name= "nm$n";
1616     for ($i= 0; $i<8; $i++){
1617       if ($start == (int)($$name)){
1618         $res+= 8 - $i;
1619         break;
1620       }
1621       $start-= pow(2,$i);
1622     }
1623   }
1625   return ($res);
1629 function recurse($rule, $variables)
1631   $result= array();
1633   if (!count($variables)){
1634     return array($rule);
1635   }
1637   reset($variables);
1638   $key= key($variables);
1639   $val= current($variables);
1640   unset ($variables[$key]);
1642   foreach($val as $possibility){
1643     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1644     $result= array_merge($result, recurse($nrule, $variables));
1645   }
1647   return ($result);
1651 function expand_id($rule, $attributes)
1653   /* Check for id rule */
1654   if(preg_match('/^id(:|#)\d+$/',$rule)){
1655     return (array("\{$rule}"));
1656   }
1658   /* Check for clean attribute */
1659   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1660     $rule= preg_replace('/^%/', '', $rule);
1661     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1662     return (array($val));
1663   }
1665   /* Check for attribute with parameters */
1666   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1667     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1668     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1669     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1670     $start= preg_replace ('/-.*$/', '', $param);
1671     $stop = preg_replace ('/^[^-]+-/', '', $param);
1673     /* Assemble results */
1674     $result= array();
1675     for ($i= $start; $i<= $stop; $i++){
1676       $result[]= substr($val, 0, $i);
1677     }
1678     return ($result);
1679   }
1681   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1682   return (array($rule));
1686 function gen_uids($rule, $attributes)
1688   global $config;
1690   /* Search for keys and fill the variables array with all 
1691      possible values for that key. */
1692   $part= "";
1693   $trigger= false;
1694   $stripped= "";
1695   $variables= array();
1697   for ($pos= 0; $pos < strlen($rule); $pos++){
1699     if ($rule[$pos] == "{" ){
1700       $trigger= true;
1701       $part= "";
1702       continue;
1703     }
1705     if ($rule[$pos] == "}" ){
1706       $variables[$pos]= expand_id($part, $attributes);
1707       $stripped.= "{".$pos."}";
1708       $trigger= false;
1709       continue;
1710     }
1712     if ($trigger){
1713       $part.= $rule[$pos];
1714     } else {
1715       $stripped.= $rule[$pos];
1716     }
1717   }
1719   /* Recurse through all possible combinations */
1720   $proposed= recurse($stripped, $variables);
1722   /* Get list of used ID's */
1723   $used= array();
1724   $ldap= $config->get_ldap_link();
1725   $ldap->cd($config->current['BASE']);
1726   $ldap->search('(uid=*)');
1728   while($attrs= $ldap->fetch()){
1729     $used[]= $attrs['uid'][0];
1730   }
1732   /* Remove used uids and watch out for id tags */
1733   $ret= array();
1734   foreach($proposed as $uid){
1736     /* Check for id tag and modify uid if needed */
1737     if(preg_match('/\{id:\d+}/',$uid)){
1738       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1740       for ($i= 0; $i < pow(10,$size); $i++){
1741         $number= sprintf("%0".$size."d", $i);
1742         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1743         if (!in_array($res, $used)){
1744           $uid= $res;
1745           break;
1746         }
1747       }
1748     }
1750   if(preg_match('/\{id#\d+}/',$uid)){
1751     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1753     while (true){
1754       mt_srand((double) microtime()*1000000);
1755       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1756       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1757       if (!in_array($res, $used)){
1758         $uid= $res;
1759         break;
1760       }
1761     }
1762   }
1764 /* Don't assign used ones */
1765 if (!in_array($uid, $used)){
1766   $ret[]= $uid;
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   if (!is_array($items)){
1803     return (FALSE);
1804   }
1806   foreach ($items as $item){
1807     if (strcasecmp($item, $value) == 0) {
1808       return (TRUE);
1809     }
1810   }
1812   return (FALSE);
1813
1816 function generate_alphabet($count= 10)
1818   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1819   $alphabet= "";
1820   $c= 0;
1822   /* Fill cells with charaters */
1823   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1824     if ($c == 0){
1825       $alphabet.= "<tr>";
1826     }
1828     $ch = mb_substr($characters, $i, 1, "UTF8");
1829     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1830       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1832     if ($c++ == $count){
1833       $alphabet.= "</tr>";
1834       $c= 0;
1835     }
1836   }
1838   /* Fill remaining cells */
1839   while ($c++ <= $count){
1840     $alphabet.= "<td>&nbsp;</td>";
1841   }
1843   return ($alphabet);
1847 function validate($string)
1849   return (strip_tags(preg_replace('/\0/', '', $string)));
1853 function get_gosa_version()
1855   global $svn_revision, $svn_path;
1857   /* Extract informations */
1858   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1860   /* Release or development? */
1861   if (preg_match('%/gosa/trunk/%', $svn_path)){
1862     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1863   } else {
1864     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1865     return (sprintf(_("GOsa $release"), $revision));
1866   }
1870 function rmdirRecursive($path, $followLinks=false) {
1871   $dir= opendir($path);
1872   while($entry= readdir($dir)) {
1873     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1874       unlink($path."/".$entry);
1875     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1876       rmdirRecursive($path."/".$entry);
1877     }
1878   }
1879   closedir($dir);
1880   return rmdir($path);
1884 function scan_directory($path,$sort_desc=false)
1886   $ret = false;
1888   /* is this a dir ? */
1889   if(is_dir($path)) {
1891     /* is this path a readable one */
1892     if(is_readable($path)){
1894       /* Get contents and write it into an array */   
1895       $ret = array();    
1897       $dir = opendir($path);
1899       /* Is this a correct result ?*/
1900       if($dir){
1901         while($fp = readdir($dir))
1902           $ret[]= $fp;
1903       }
1904     }
1905   }
1906   /* Sort array ascending , like scandir */
1907   sort($ret);
1909   /* Sort descending if parameter is sort_desc is set */
1910   if($sort_desc) {
1911     $ret = array_reverse($ret);
1912   }
1914   return($ret);
1918 function clean_smarty_compile_dir($directory)
1920   global $svn_revision;
1922   if(is_dir($directory) && is_readable($directory)) {
1923     // Set revision filename to REVISION
1924     $revision_file= $directory."/REVISION";
1926     /* Is there a stamp containing the current revision? */
1927     if(!file_exists($revision_file)) {
1928       // create revision file
1929       create_revision($revision_file, $svn_revision);
1930     } else {
1931       # check for "$config->...['CONFIG']/revision" and the
1932       # contents should match the revision number
1933       if(!compare_revision($revision_file, $svn_revision)){
1934         // If revision differs, clean compile directory
1935         foreach(scan_directory($directory) as $file) {
1936           if(($file==".")||($file=="..")) continue;
1937           if( is_file($directory."/".$file) &&
1938               is_writable($directory."/".$file)) {
1939             // delete file
1940             if(!unlink($directory."/".$file)) {
1941               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1942               // This should never be reached
1943             }
1944           } elseif(is_dir($directory."/".$file) &&
1945               is_writable($directory."/".$file)) {
1946             // Just recursively delete it
1947             rmdirRecursive($directory."/".$file);
1948           }
1949         }
1950         // We should now create a fresh revision file
1951         clean_smarty_compile_dir($directory);
1952       } else {
1953         // Revision matches, nothing to do
1954       }
1955     }
1956   } else {
1957     // Smarty compile dir is not accessible
1958     // (Smarty will warn about this)
1959   }
1963 function create_revision($revision_file, $revision)
1965   $result= false;
1967   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1968     if($fh= fopen($revision_file, "w")) {
1969       if(fwrite($fh, $revision)) {
1970         $result= true;
1971       }
1972     }
1973     fclose($fh);
1974   } else {
1975     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1976   }
1978   return $result;
1982 function compare_revision($revision_file, $revision)
1984   // false means revision differs
1985   $result= false;
1987   if(file_exists($revision_file) && is_readable($revision_file)) {
1988     // Open file
1989     if($fh= fopen($revision_file, "r")) {
1990       // Compare File contents with current revision
1991       if($revision == fread($fh, filesize($revision_file))) {
1992         $result= true;
1993       }
1994     } else {
1995       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1996     }
1997     // Close file
1998     fclose($fh);
1999   }
2001   return $result;
2005 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2007   $str = ""; // Our return value will be saved in this var
2009   $color  = dechex($percentage+150);
2010   $color2 = dechex(150 - $percentage);
2011   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2013   $progress = (int)(($percentage /100)*$width);
2015   /* Abort printing out percentage, if divs are to small */
2018   /* If theres a better solution for this, use it... */
2019   $str = "
2020     <div style=\" width:".($width)."px; 
2021     height:".($height)."px;
2022   background-color:#000000;
2023 padding:1px;\">
2025           <div style=\" width:".($width)."px;
2026         background-color:#$bgcolor;
2027 height:".($height)."px;\">
2029          <div style=\" width:".$progress."px;
2030 height:".$height."px;
2031        background-color:#".$color2.$color2.$color."; \">";
2034        if(($height >10)&&($showvalue)){
2035          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2036            <b>".$percentage."%</b>
2037            </font>";
2038        }
2040        $str.= "</div></div></div>";
2042        return($str);
2046 function array_key_ics($ikey, $items)
2048   /* Gather keys, make them lowercase */
2049   $tmp= array();
2050   foreach ($items as $key => $value){
2051     $tmp[strtolower($key)]= $key;
2052   }
2054   if (isset($tmp[strtolower($ikey)])){
2055     return($tmp[strtolower($ikey)]);
2056   }
2058   return ("");
2062 function array_differs($src, $dst)
2064   /* If the count is differing, the arrays differ */
2065   if (count ($src) != count ($dst)){
2066     return (TRUE);
2067   }
2069   /* So the count is the same - lets check the contents */
2070   $differs= FALSE;
2071   foreach($src as $value){
2072     if (!in_array($value, $dst)){
2073       $differs= TRUE;
2074     }
2075   }
2077   return ($differs);
2081 function saveFilter($a_filter, $values)
2083   if (isset($_POST['regexit'])){
2084     $a_filter["regex"]= $_POST['regexit'];
2086     foreach($values as $type){
2087       if (isset($_POST[$type])) {
2088         $a_filter[$type]= "checked";
2089       } else {
2090         $a_filter[$type]= "";
2091       }
2092     }
2093   }
2095   /* React on alphabet links if needed */
2096   if (isset($_GET['search'])){
2097     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2098     if ($s == "**"){
2099       $s= "*";
2100     }
2101     $a_filter['regex']= $s;
2102   }
2104   return ($a_filter);
2108 /* Escape all preg_* relevant characters */
2109 function normalizePreg($input)
2111   return (addcslashes($input, '[]()|/.*+-'));
2115 /* Escape all LDAP filter relevant characters */
2116 function normalizeLdap($input)
2118   return (addcslashes($input, '()|'));
2122 /* Resturns the difference between to microtime() results in float  */
2123 function get_MicroTimeDiff($start , $stop)
2125   $a = split("\ ",$start);
2126   $b = split("\ ",$stop);
2128   $secs = $b[1] - $a[1];
2129   $msecs= $b[0] - $a[0]; 
2131   $ret = (float) ($secs+ $msecs);
2132   return($ret);
2136 function get_base_dir()
2138   global $BASE_DIR;
2140   return $BASE_DIR;
2144 function obj_is_readable($dn, $object, $attribute)
2146   global $ui;
2148   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2152 function obj_is_writable($dn, $object, $attribute)
2154   global $ui;
2156   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2160 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2162   /* Initialize variables */
2163   $ret  = array("count" => 0);  // Set count to 0
2164   $next = true;                 // if false, then skip next loops and return
2165   $cnt  = 0;                    // Current number of loops
2166   $max  = 100;                  // Just for security, prevent looops
2167   $ldap = NULL;                 // To check if created result a valid
2168   $keep = "";                   // save last failed parse string
2170   /* Check each parsed dn in ldap ? */
2171   if($config!==NULL && $verify_in_ldap){
2172     $ldap = $config->get_ldap_link();
2173   }
2175   /* Lets start */
2176   $called = false;
2177   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2179     $cnt ++;
2180     if(!preg_match("/,/",$dn)){
2181       $next = false;
2182     }
2183     $object = preg_replace("/[,].*$/","",$dn);
2184     $dn     = preg_replace("/^[^,]+,/","",$dn);
2186     $called = true;
2188     /* Check if current dn is valid */
2189     if($ldap!==NULL){
2190       $ldap->cd($dn);
2191       $ldap->cat($dn,array("dn"));
2192       if($ldap->count()){
2193         $ret[]  = $keep.$object;
2194         $keep   = "";
2195       }else{
2196         $keep  .= $object.",";
2197       }
2198     }else{
2199       $ret[]  = $keep.$object;
2200       $keep   = "";
2201     }
2202   }
2204   /* No dn was posted */
2205   if($cnt == 0 && !empty($dn)){
2206     $ret[] = $dn;
2207   }
2209   /* Append the rest */
2210   $test = $keep.$dn;
2211   if($called && !empty($test)){
2212     $ret[] = $keep.$dn;
2213   }
2214   $ret['count'] = count($ret) - 1;
2216   return($ret);
2220 function get_base_from_hook($dn, $attrib)
2222   global $config;
2224   if (isset($config->current['BASE_HOOK'])){
2225     
2226     /* Call hook script - if present */
2227     $command= $config->current['BASE_HOOK'];
2229     if ($command != ""){
2230       $command.= " '".LDAP::fix($dn)."' $attrib";
2231       if (check_command($command)){
2232         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2233         exec($command, $output);
2234         if (preg_match("/^[0-9]+$/", $output[0])){
2235           return ($output[0]);
2236         } else {
2237           msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2238           return ($config->current['UIDBASE']);
2239         }
2240       } else {
2241         msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2242         return ($config->current['UIDBASE']);
2243       }
2245     } else {
2247       msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2248       return ($config->current['UIDBASE']);
2250     }
2251   }
2255 function check_schema_version($class, $version)
2257   return preg_match("/\(v$version\)/", $class['DESC']);
2261 function check_schema($cfg,$rfc2307bis = FALSE)
2263   $messages= array();
2265   /* Get objectclasses */
2266   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2267   $objectclasses = $ldap->get_objectclasses();
2268   if(count($objectclasses) == 0){
2269     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2270   }
2272   /* This is the default block used for each entry.
2273    *  to avoid unset indexes.
2274    */
2275   $def_check = array("REQUIRED_VERSION" => "0",
2276       "SCHEMA_FILES"     => array(),
2277       "CLASSES_REQUIRED" => array(),
2278       "STATUS"           => FALSE,
2279       "IS_MUST_HAVE"     => FALSE,
2280       "MSG"              => "",
2281       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2283   /* The gosa base schema */
2284   $checks['gosaObject'] = $def_check;
2285   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2286   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2287   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2288   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2290   /* GOsa Account class */
2291   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2292   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2293   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2294   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2295   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2297   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2298   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2299   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2300   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2301   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2302   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2304   /* Some other checks */
2305   foreach(array(
2306         "gosaCacheEntry"        => array("version" => "2.4"),
2307         "gosaDepartment"        => array("version" => "2.4"),
2308         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2309         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2310         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2311         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2312         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2313         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2314         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2315         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2316         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2317         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2318         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2319         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2320         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2321         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2322         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2323         "goLdapServer"          => array("version" => "2.4"),
2324         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2325         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2326         "goKrbServer"           => array("version" => "2.4"),
2327         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2328         ) as $name => $values){
2330           $checks[$name] = $def_check;
2331           if(isset($values['version'])){
2332             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2333           }
2334           if(isset($values['file'])){
2335             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2336           }
2337           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2338         }
2339   foreach($checks as $name => $value){
2340     foreach($value['CLASSES_REQUIRED'] as $class){
2342       if(!isset($objectclasses[$name])){
2343         $checks[$name]['STATUS'] = FALSE;
2344         if($value['IS_MUST_HAVE']){
2345           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2346         }else{
2347           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2348         }
2349       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2350         $checks[$name]['STATUS'] = FALSE;
2352         if($value['IS_MUST_HAVE']){
2353           $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2354         }else{
2355           $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2356         }
2357       }else{
2358         $checks[$name]['STATUS'] = TRUE;
2359         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2360       }
2361     }
2362   }
2364   $tmp = $objectclasses;
2366   /* The gosa base schema */
2367   $checks['posixGroup'] = $def_check;
2368   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2369   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2370   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2371   $checks['posixGroup']['STATUS']           = TRUE;
2372   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2373   $checks['posixGroup']['MSG']              = "";
2374   $checks['posixGroup']['INFO']             = "";
2376   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2377   if(isset($tmp['posixGroup'])){
2379     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2380       $checks['posixGroup']['STATUS']           = FALSE;
2381       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2382       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2383     }
2384     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2385       $checks['posixGroup']['STATUS']           = FALSE;
2386       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2387       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2388     }
2389   }
2391   return($checks);
2395 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2397   $tmp = array(
2398         "de_DE" => "German",
2399         "fr_FR" => "French",
2400         "it_IT" => "Italian",
2401         "es_ES" => "Spanish",
2402         "en_US" => "English",
2403         "nl_NL" => "Dutch",
2404         "pl_PL" => "Polish",
2405         "sv_SE" => "Swedish",
2406         "zh_CN" => "Chinese",
2407         "ru_RU" => "Russian");
2408   
2409   $tmp2= array(
2410         "de_DE" => _("German"),
2411         "fr_FR" => _("French"),
2412         "it_IT" => _("Italian"),
2413         "es_ES" => _("Spanish"),
2414         "en_US" => _("English"),
2415         "nl_NL" => _("Dutch"),
2416         "pl_PL" => _("Polish"),
2417         "sv_SE" => _("Swedish"),
2418         "zh_CN" => _("Chinese"),
2419         "ru_RU" => _("Russian"));
2421   $ret = array();
2422   if($languages_in_own_language){
2424     $old_lang = setlocale(LC_ALL, 0);
2425     foreach($tmp as $key => $name){
2426       $lang = $key.".UTF-8";
2427       setlocale(LC_ALL, $lang);
2428       if($strip_region_tag){
2429         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2430       }else{
2431         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2432       }
2433     }
2434     setlocale(LC_ALL, $old_lang);
2435   }else{
2436     foreach($tmp as $key => $name){
2437       if($strip_region_tag){
2438         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2439       }else{
2440         $ret[$key] = _($name);
2441       }
2442     }
2443   }
2444   return($ret);
2448 /* Returns contents of the given POST variable and check magic quotes settings */
2449 function get_post($name)
2451   if(!isset($_POST[$name])){
2452     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2453     return(FALSE);
2454   }
2455   if(get_magic_quotes_gpc()){
2456     return(stripcslashes($_POST[$name]));
2457   }else{
2458     return($_POST[$name]);
2459   }
2463 /* Return class name in correct case */
2464 function get_correct_class_name($cls)
2466   global $class_mapping;
2467   if(isset($class_mapping) && is_array($class_mapping)){
2468     foreach($class_mapping as $class => $file){
2469       if(preg_match("/^".$cls."$/i",$class)){
2470         return($class);
2471       }
2472     }
2473   }
2474   return(FALSE);
2478 // change_password, changes the Password, of the given dn
2479 function change_password ($dn, $password, $mode=0, $hash= "")
2481   global $config;
2482   $newpass= "";
2484   /* Convert to lower. Methods are lowercase */
2485   $hash= strtolower($hash);
2487   // Get all available encryption Methods
2489   // NON STATIC CALL :)
2490   $tmp = new passwordMethod(session::get('config'));
2491   $available = $tmp->get_available_methods();
2493   // read current password entry for $dn, to detect the encryption Method
2494   $ldap       = $config->get_ldap_link();
2495   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2496   $attrs      = $ldap->fetch ();
2498   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2499   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2500     $deactivated = TRUE;
2501   }else{
2502     $deactivated = FALSE;
2503   }
2505   /* Is ensure that clear passwords will stay clear */
2506   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2507     $hash = "clear";
2508   }
2510   // Detect the encryption Method
2511   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2513     /* Check for supported algorithm */
2514     mt_srand((double) microtime()*1000000);
2516     /* Extract used hash */
2517     if ($hash == ""){
2518       $hash= strtolower($matches[1]);
2519     }
2521     $test = new  $available[$hash]($config);
2523   } else {
2524     // User MD5 by default
2525     $hash= "md5";
2526     $test = new  $available['md5']($config);
2527   }
2529   /* Feed password backends with information */
2530   $test->dn= $dn;
2531   $test->attrs= $attrs;
2532   $newpass= $test->generate_hash($password);
2534   // Update shadow timestamp?
2535   if (isset($attrs["shadowLastChange"][0])){
2536     $shadow= (int)(date("U") / 86400);
2537   } else {
2538     $shadow= 0;
2539   }
2541   // Write back modified entry
2542   $ldap->cd($dn);
2543   $attrs= array();
2545   // Not for groups
2546   if ($mode == 0){
2548     if ($shadow != 0){
2549       $attrs['shadowLastChange']= $shadow;
2550     }
2552     // Create SMB Password
2553     $attrs= generate_smb_nt_hash($password);
2554   }
2556  /* Readd ! if user was deactivated */
2557   if($deactivated){
2558     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2559   }
2561   $attrs['userPassword']= array();
2562   $attrs['userPassword']= $newpass;
2564   $ldap->modify($attrs);
2566   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2568   if ($ldap->error != 'Success') {
2569     msg_dialog::display(_("LDAP error"), sprintf(_('Setting the password failed!').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
2570   } else {
2572     /* Run backend method for change/create */
2573     $test->set_password($password);
2575     /* Find postmodify entries for this class */
2576     $command= $config->search("password", "POSTMODIFY",array('menu'));
2578     if ($command != ""){
2579       /* Walk through attribute list */
2580       $command= preg_replace("/%userPassword/", $password, $command);
2581       $command= preg_replace("/%dn/", $dn, $command);
2583       if (check_command($command)){
2584         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2585         exec($command);
2586       } else {
2587         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2588         msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2589       }
2590     }
2591   }
2595 // Return something like array['sambaLMPassword']= "lalla..."
2596 function generate_smb_nt_hash($password)
2598   global $config;
2600   # Try to use gosa-si?
2601   if (isset($config->current['GOSA_SI'])){
2602         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2603         $hash= $res['XML']['HASH'];
2604   } else {
2605           $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2606           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2608           exec($tmp, $ar);
2609           flush();
2610           reset($ar);
2611           $hash= current($ar);
2612   }
2614   if ($hash == "") {
2615           msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2616           return ("");
2617   }
2619   list($lm,$nt)= split (":", trim($hash));
2621   if ($config->current['SAMBAVERSION'] == 3) {
2622           $attrs['sambaLMPassword']= $lm;
2623           $attrs['sambaNTPassword']= $nt;
2624           $attrs['sambaPwdLastSet']= date('U');
2625           $attrs['sambaBadPasswordCount']= "0";
2626           $attrs['sambaBadPasswordTime']= "0";
2627   } else {
2628           $attrs['lmPassword']= $lm;
2629           $attrs['ntPassword']= $nt;
2630           $attrs['pwdLastSet']= date('U');
2631   }
2632   return($attrs);
2636 function crypt_single($string,$enc_type )
2638   return( passwordMethod::crypt_single_str($string,$enc_type));
2642 function getEntryCSN($dn)
2644   global $config;
2645   if(empty($dn) || !is_object($config)){
2646     return("");
2647   }
2649   /* Get attribute that we should use as serial number */
2650   if(isset($config->current['UNIQ_IDENTIFIER'])){
2651     $attr = $config->current['UNIQ_IDENTIFIER'];
2652   }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2653     $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2654   }
2655   if(!empty($attr)){
2656     $ldap = $config->get_ldap_link();
2657     $ldap->cat($dn,array($attr));
2658     $csn = $ldap->fetch();
2659     if(isset($csn[$attr][0])){
2660       return($csn[$attr][0]);
2661     }
2662   }
2663   return("");
2667 /* Add a given objectClass to an attrs entry */
2668 function add_objectClass($classes, &$attrs)
2670   if (is_array($classes)){
2671     $list= $classes;
2672   } else {
2673     $list= array($classes);
2674   }
2676   foreach ($list as $class){
2677     $attrs['objectClass'][]= $class;
2678   }
2682 /* Removes a given objectClass from the attrs entry */
2683 function remove_objectClass($classes, &$attrs)
2685   if (isset($attrs['objectClass'])){
2686     /* Array? */
2687     if (is_array($classes)){
2688       $list= $classes;
2689     } else {
2690       $list= array($classes);
2691     }
2693     $tmp= array();
2694     foreach ($attrs['objectClass'] as $oc) {
2695       foreach ($list as $class){
2696         if ($oc != $class){
2697           $tmp[]= $oc;
2698         }
2699       }
2700     }
2701     $attrs['objectClass']= $tmp;
2702   }
2705 /*! \brief  Initialize a file download with given content, name and data type. 
2706  *  @param  data  String The content to send.
2707  *  @param  name  String The name of the file.
2708  *  @param  type  String The content identifier, default value is "application/octet-stream";
2709  */
2710 function send_binary_content($data,$name,$type = "application/octet-stream")
2712   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2713   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2714   header("Cache-Control: no-cache");
2715   header("Pragma: no-cache");
2716   header("Cache-Control: post-check=0, pre-check=0");
2717   header("Content-type: ".$type."");
2719   /* force download dialog */
2720   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2721     header('Content-Disposition: filename="'.$name.'"');
2722   } else {
2723     header('Content-Disposition: attachment; filename="'.$name.'"');
2724   }
2726   echo $data;
2727   exit();
2730 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2731 ?>