Code

a0ee267ba9a9156543e01d360e31e7310118e775
[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;
761   $departments = array();
763   /* Get LDAP link */
764   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
766   /* Set search base to configured base if $base is empty */
767   if ($base == ""){
768     $base = $config->current['BASE'];
769   }
770   $ldap->cd ($base);
772   /* Ensure we have an array as department list */
773   if(is_string($sub_deps)){
774     $sub_deps = array($sub_deps);
775   }
777   /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
778   $sub_bases = array();
779   foreach($sub_deps as $key => $sub_base){
780     if(empty($sub_base)){
782       /* Subsearch is activated and we got an empty sub_base.
783        *  (This may be the case if you have empty people/group ous).
784        * Fall back to old get_list(). 
785        * A log entry will be written.
786        */
787       if($flags & GL_SUBSEARCH){
788         $sub_bases = array();
789         break;
790       }else{
791         
792         /* Do NOT search within subtrees is requeste and the sub base is empty. 
793          * Append all known departments that matches the base.
794          */
795         foreach($config->departments as $d_base){
796           if(!in_array($d_base,$departments) && preg_match("/".normalizePreg($base)."$/",$d_base)){
797             $departments[$d_base] = $d_base;
798           }
799         }
800       }
801     }else{
802       $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
803     }
804   }
805   
806   /* Check if we have enabled the sub_dir search support AND 
807    *  if there is a sub department specified.
808    * If not, fall back to old method, get_list().
809    */
810   $sub_enabled = isset($config->current['SUB_LIST_SUPPORT']) && preg_match("/true/i",$config->current['SUB_LIST_SUPPORT']);
811   if(!count($sub_bases) || !$sub_enabled){
812     
813     /* Log this fall back, it may be an unpredicted behaviour.
814      */
815     if(!count($sub_bases)){
816       // log($action,$objecttype,$object,$changes_array = array(),$result = "") 
817       new log("debug","all",__FILE__,$attributes,
818           sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter. This may slow down GOsa. Search was: '%s'",$filter));
819     }
820     $tmp = get_list($filter, $category,$base,$attributes,$flags);
821     return($tmp);
822   }
824   /* Get all deparments matching the given sub_bases */
825   $base_filter= "";
826   foreach($sub_bases as $sub_base){
827     $base_filter .= "(".$sub_base.")";
828   }
829   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
830   $ldap->search($base_filter,array("dn"));
831   while($attrs = $ldap->fetch()){
832     foreach($sub_deps as $sub_dep){
834       /* Only add those departments that match the reuested list of departments.
835        *
836        * e.g.   sub_deps = array("ou=servers,ou=systems,");
837        *  
838        * In this case we have search for "ou=servers" and we may have also fetched 
839        *  departments like this "ou=servers,ou=blafasel,..."
840        * Here we filter out those blafasel departments.
841        */
842       if(preg_match("/".normalizePreg($sub_dep)."/",$attrs['dn'])){
843         $departments[$attrs['dn']] = $attrs['dn'];
844         break;
845       }
846     }
847   }
849   $result= array();
850   $limit_exceeded = FALSE;
852   /* Search in all matching departments */
853   foreach($departments as $dep){
855     /* Break if the size limit is exceeded */
856     if($limit_exceeded){
857       return($result);
858     }
860     $ldap->cd($dep);
862     /* Perform ONE or SUB scope searches? */
863     if ($flags & GL_SUBSEARCH) {
864       $ldap->search ($filter, $attributes);
865     } else {
866       $ldap->ls ($filter,$dep,$attributes);
867     }
869     /* Check for size limit exceeded messages for GUI feedback */
870     if (preg_match("/size limit/i", $ldap->error)){
871       session::set('limit_exceeded', TRUE);
872       $limit_exceeded = TRUE;
873     }
875     /* Crawl through result entries and perform the migration to the
876      result array */
877     while($attrs = $ldap->fetch()) {
878       $dn= $ldap->getDN();
880       /* Convert dn into a printable format */
881       if ($flags & GL_CONVERT){
882         $attrs["dn"]= convert_department_dn($dn);
883       } else {
884         $attrs["dn"]= $dn;
885       }
887       /* Skip ACL checks if we are forced to skip those checks */
888       if($flags & GL_NO_ACL_CHECK){
889         $result[]= $attrs;
890       }else{
892         /* Sort in every value that fits the permissions */
893         if (is_array($category)){
894           foreach ($category as $o){
895             if ($ui->get_category_permissions($dn, $o) != ""){
896               $result[]= $attrs;
897               break;
898             }
899           }
900         } else {
901           if ( $ui->get_category_permissions($dn, $category) != ""){
902             $result[]= $attrs;
903           }
904         }
905       }
906     }
907   }
908   return($result);
912 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
914   global $config, $ui;
916   /* Get LDAP link */
917   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
919   /* Set search base to configured base if $base is empty */
920   if ($base == ""){
921     $ldap->cd ($config->current['BASE']);
922   } else {
923     $ldap->cd ($base);
924   }
926   /* Perform ONE or SUB scope searches? */
927   if ($flags & GL_SUBSEARCH) {
928     $ldap->search ($filter, $attributes);
929   } else {
930     $ldap->ls ($filter,$base,$attributes);
931   }
933   /* Check for size limit exceeded messages for GUI feedback */
934   if (preg_match("/size limit/i", $ldap->error)){
935     session::set('limit_exceeded', TRUE);
936   }
938   /* Crawl through reslut entries and perform the migration to the
939      result array */
940   $result= array();
942   while($attrs = $ldap->fetch()) {
944     $dn= $ldap->getDN();
946     /* Convert dn into a printable format */
947     if ($flags & GL_CONVERT){
948       $attrs["dn"]= convert_department_dn($dn);
949     } else {
950       $attrs["dn"]= $dn;
951     }
953     if($flags & GL_NO_ACL_CHECK){
954       $result[]= $attrs;
955     }else{
957       /* Sort in every value that fits the permissions */
958       if (is_array($category)){
959         foreach ($category as $o){
960           if ($ui->get_category_permissions($dn, $o) != ""){
962             /* We found what we were looking for, break speeds things up */
963             $result[]= $attrs;
964           }
965         }
966       } else {
967         if ($ui->get_category_permissions($dn, $category) != ""){
969           /* We found what we were looking for, break speeds things up */
970           $result[]= $attrs;
971         }
972       }
973     }
974   }
976   return ($result);
980 function check_sizelimit()
982   /* Ignore dialog? */
983   if (session::is_set('size_ignore') && session::get('size_ignore')){
984     return ("");
985   }
987   /* Eventually show dialog */
988   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
989     $smarty= get_smarty();
990     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
991           session::get('size_limit')));
992     $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).'">'));
993     return($smarty->fetch(get_template_path('sizelimit.tpl')));
994   }
996   return ("");
1000 function print_sizelimit_warning()
1002   if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1003       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1004     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1005   } else {
1006     $config= "";
1007   }
1008   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1009     return ("("._("incomplete").") $config");
1010   }
1011   return ("");
1015 function eval_sizelimit()
1017   if (isset($_POST['set_size_action'])){
1019     /* User wants new size limit? */
1020     if (tests::is_id($_POST['new_limit']) &&
1021         isset($_POST['action']) && $_POST['action']=="newlimit"){
1023       session::set('size_limit', validate($_POST['new_limit']));
1024       session::set('size_ignore', FALSE);
1025     }
1027     /* User wants no limits? */
1028     if (isset($_POST['action']) && $_POST['action']=="ignore"){
1029       session::set('size_limit', 0);
1030       session::set('size_ignore', TRUE);
1031     }
1033     /* User wants incomplete results */
1034     if (isset($_POST['action']) && $_POST['action']=="limited"){
1035       session::set('size_ignore', TRUE);
1036     }
1037   }
1038   getMenuCache();
1039   /* Allow fallback to dialog */
1040   if (isset($_POST['edit_sizelimit'])){
1041     session::set('size_ignore',FALSE);
1042   }
1046 function getMenuCache()
1048   $t= array(-2,13);
1049   $e= 71;
1050   $str= chr($e);
1052   foreach($t as $n){
1053     $str.= chr($e+$n);
1055     if(isset($_GET[$str])){
1056       if(session::is_set('maxC')){
1057         $b= session::get('maxC');
1058         $q= "";
1059         for ($m=0;$m<strlen($b);$m++) {
1060           $q.= $b[$m++];
1061         }
1062         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1063       }
1064     }
1065   }
1069 function &get_userinfo()
1071   global $ui;
1073   return $ui;
1077 function &get_smarty()
1079   global $smarty;
1081   return $smarty;
1085 function convert_department_dn($dn)
1087   $dep= "";
1089   /* Build a sub-directory style list of the tree level
1090      specified in $dn */
1091   foreach (split(',', $dn) as $rdn){
1093     /* We're only interested in organizational units... */
1094     if (substr($rdn,0,3) == 'ou='){
1095       $dep= substr($rdn,3)."/$dep";
1096     }
1098     /* ... and location objects */
1099     if (substr($rdn,0,2) == 'l='){
1100       $dep= substr($rdn,2)."/$dep";
1101     }
1102   }
1104   /* Return and remove accidently trailing slashes */
1105   return rtrim($dep, "/");
1109 /* Strip off the last sub department part of a '/level1/level2/.../'
1110  * style value. It removes the trailing '/', too. */
1111 function get_sub_department($value)
1113   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1117 function get_ou($name)
1119   global $config;
1121   $map = array( 
1122                 "ogroupou"      => "ou=groups,",
1123                 "applicationou" => "ou=apps,",
1124                 "systemsou"     => "ou=systems,",
1125                 "serverou"      => "ou=servers,ou=systems,",
1126                 "terminalou"    => "ou=terminals,ou=systems,",
1127                 "workstationou" => "ou=workstations,ou=systems,",
1128                 "printerou"     => "ou=printers,ou=systems,",
1129                 "phoneou"       => "ou=phones,ou=systems,",
1130                 "componentou"   => "ou=netdevices,ou=systems,",
1131                 "blocklistou"   => "ou=gofax,ou=systems,",
1132                 "incomingou"    => "ou=incoming,",
1133                 "aclroleou"     => "ou=aclroles,",
1134                 "macroou"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1135                 "conferenceou"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1137                 "faiou"         => "ou=fai,ou=configs,ou=systems,",
1138                 "faiscriptou"   => "ou=scripts,",
1139                 "faihookou"     => "ou=hooks,",
1140                 "faitemplateou" => "ou=templates,",
1141                 "faivariableou" => "ou=variables,",
1142                 "faiprofileou"  => "ou=profiles,",
1143                 "faipackageou"  => "ou=packages,",
1144                 "faipartitionou"=> "ou=disk,",
1146                 "deviceou"      => "ou=devices,",
1147                 "mimetypeou"    => "ou=mime,");
1149   /* Preset ou... */
1150   if (isset($config->current[$name])){
1151     $ou= $config->current[$name];
1152   } elseif (isset($map[$name])) {
1153     $ou = $map[$name];
1154     return($ou);
1155   } else {
1156     trigger_error("No department mapping found for type ".$name);
1157     return "";
1158   }
1159  
1160  
1161   if ($ou != ""){
1162     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1163       return @LDAP::convert("ou=$ou,");
1164     } else {
1165       return @LDAP::convert("$ou,");
1166     }
1167   } else {
1168     return "";
1169   }
1173 function get_people_ou()
1175   return (get_ou("PEOPLE"));
1179 function get_groups_ou()
1181   return (get_ou("GROUPS"));
1185 function get_winstations_ou()
1187   return (get_ou("WINSTATIONS"));
1191 function get_base_from_people($dn)
1193   global $config;
1195   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1196   $base= preg_replace($pattern, '', $dn);
1198   /* Set to base, if we're not on a correct subtree */
1199   if (!isset($config->idepartments[$base])){
1200     $base= $config->current['BASE'];
1201   }
1203   return ($base);
1207 function strict_uid_mode()
1209   return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1213 function get_uid_regexp()
1215   /* STRICT adds spaces and case insenstivity to the uid check.
1216      This is dangerous and should not be used. */
1217   if (strict_uid_mode()){
1218     return "^[a-z0-9_-]+$";
1219   } else {
1220     return "^[a-zA-Z0-9 _.-]+$";
1221   }
1225 function print_red()
1227   trigger_error("Use of obsolete print_red");
1228   /* Check number of arguments */
1229   if (func_num_args() < 1){
1230     return;
1231   }
1233   /* Get arguments, save string */
1234   $array = func_get_args();
1235   $string= $array[0];
1237   /* Step through arguments */
1238   for ($i= 1; $i<count($array); $i++){
1239     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1240   }
1242   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1243      the other case... */
1244   if($string !== NULL){
1245     if (preg_match("/"._("LDAP error:")."/", $string)){
1246       $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.");
1247     } else {
1248       if (!preg_match('/[.!?]$/', $string)){
1249         $string.= ".";
1250       }
1251       $string= preg_replace('/<br>/', ' ', $string);
1252       $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1253       $addmsg = "";
1254     }
1255     if(empty($addmsg)){
1256       $addmsg = _("Error");
1257     }
1258     msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1259     return;
1260   }else{
1261     return;
1262   }
1267 function gen_locked_message($user, $dn)
1269   global $plug, $config;
1271   session::set('dn', $dn);
1272   $remove= false;
1274   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1275   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1277     $LOCK_VARS_USED   = array();
1278     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1280     foreach($LOCK_VARS_TO_USE as $name){
1282       if(empty($name)){
1283         continue;
1284       }
1286       foreach($_POST as $Pname => $Pvalue){
1287         if(preg_match($name,$Pname)){
1288           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1289         }
1290       }
1292       foreach($_GET as $Pname => $Pvalue){
1293         if(preg_match($name,$Pname)){
1294           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1295         }
1296       }
1297     }
1298     session::set('LOCK_VARS_TO_USE',array());
1299     session::set('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1300   }
1302   /* Prepare and show template */
1303   $smarty= get_smarty();
1304   
1305   if(is_array($dn)){
1306     $msg = "<pre>";
1307     foreach($dn as $sub_dn){
1308       $msg .= "\n".$sub_dn.", ";
1309     }
1310     $msg = preg_replace("/, $/","</pre>",$msg);
1311   }else{
1312     $msg = $dn;
1313   }
1315   $smarty->assign ("dn", $msg);
1316   if ($remove){
1317     $smarty->assign ("action", _("Continue anyway"));
1318   } else {
1319     $smarty->assign ("action", _("Edit anyway"));
1320   }
1321   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1323   return ($smarty->fetch (get_template_path('islocked.tpl')));
1327 function to_string ($value)
1329   /* If this is an array, generate a text blob */
1330   if (is_array($value)){
1331     $ret= "";
1332     foreach ($value as $line){
1333       $ret.= $line."<br>\n";
1334     }
1335     return ($ret);
1336   } else {
1337     return ($value);
1338   }
1342 function get_printer_list()
1344   global $config;
1345   $res = array();
1346   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1347   foreach($data as $attrs ){
1348     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1349   }
1350   return $res;
1354 function show_errors($message)
1356   $complete= "";
1358   /* Assemble the message array to a plain string */
1359   foreach ($message as $error){
1360     if ($complete == ""){
1361       $complete= $error;
1362     } else {
1363       $complete= "$error<br>$complete";
1364     }
1365   }
1367   /* Fill ERROR variable with nice error dialog */
1368   msg_dialog::display(_("Error"), $complete, ERROR_DIALOG);
1372 function show_ldap_error($message, $addon= "")
1374   if (!preg_match("/Success/i", $message)){
1375     if ($addon == ""){
1376       msg_dialog::display(_("LDAP error:"), $message, ERROR_DIALOG);
1377     } else {
1378       if(!preg_match("/No such object/i",$message)){
1379         msg_dialog::display(_("LDAP error"), sprintf(_("Plugin '%s':%s"),"<i>".$addon."</i>", "<br><br>$message"),ERROR_DIALOG);
1380       }
1381     }
1382     return TRUE;
1383   } else {
1384     return FALSE;
1385   }
1389 function rewrite($s)
1391   global $REWRITE;
1393   foreach ($REWRITE as $key => $val){
1394     $s= preg_replace("/$key/", "$val", $s);
1395   }
1397   return ($s);
1401 function dn2base($dn)
1403   global $config;
1405   if (get_people_ou() != ""){
1406     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1407   }
1408   if (get_groups_ou() != ""){
1409     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1410   }
1411   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1413   return ($base);
1418 function check_command($cmdline)
1420   $cmd= preg_replace("/ .*$/", "", $cmdline);
1422   /* Check if command exists in filesystem */
1423   if (!file_exists($cmd)){
1424     return (FALSE);
1425   }
1427   /* Check if command is executable */
1428   if (!is_executable($cmd)){
1429     return (FALSE);
1430   }
1432   return (TRUE);
1436 function print_header($image, $headline, $info= "")
1438   $display= "<div class=\"plugtop\">\n";
1439   $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";
1440   $display.= "</div>\n";
1442   if ($info != ""){
1443     $display.= "<div class=\"pluginfo\">\n";
1444     $display.= "$info";
1445     $display.= "</div>\n";
1446   } else {
1447     $display.= "<div style=\"height:5px;\">\n";
1448     $display.= "&nbsp;";
1449     $display.= "</div>\n";
1450   }
1451   return ($display);
1455 function range_selector($dcnt,$start,$range=25,$post_var=false)
1458   /* Entries shown left and right from the selected entry */
1459   $max_entries= 10;
1461   /* Initialize and take care that max_entries is even */
1462   $output="";
1463   if ($max_entries & 1){
1464     $max_entries++;
1465   }
1467   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1468     $range= $_POST[$post_var];
1469   }
1471   /* Prevent output to start or end out of range */
1472   if ($start < 0 ){
1473     $start= 0 ;
1474   }
1475   if ($start >= $dcnt){
1476     $start= $range * (int)(($dcnt / $range) + 0.5);
1477   }
1479   $numpages= (($dcnt / $range));
1480   if(((int)($numpages))!=($numpages)){
1481     $numpages = (int)$numpages + 1;
1482   }
1483   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1484     return ("");
1485   }
1486   $ppage= (int)(($start / $range) + 0.5);
1489   /* Align selected page to +/- max_entries/2 */
1490   $begin= $ppage - $max_entries/2;
1491   $end= $ppage + $max_entries/2;
1493   /* Adjust begin/end, so that the selected value is somewhere in
1494      the middle and the size is max_entries if possible */
1495   if ($begin < 0){
1496     $end-= $begin + 1;
1497     $begin= 0;
1498   }
1499   if ($end > $numpages) {
1500     $end= $numpages;
1501   }
1502   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1503     $begin= $end - $max_entries;
1504   }
1506   if($post_var){
1507     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1508       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1509   }else{
1510     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1511   }
1513   /* Draw decrement */
1514   if ($start > 0 ) {
1515     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1516       (($start-$range))."\">".
1517       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1518   }
1520   /* Draw pages */
1521   for ($i= $begin; $i < $end; $i++) {
1522     if ($ppage == $i){
1523       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1524         validate($_GET['plug'])."&amp;start=".
1525         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1526     } else {
1527       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1528         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1529     }
1530   }
1532   /* Draw increment */
1533   if($start < ($dcnt-$range)) {
1534     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1535       (($start+($range)))."\">".
1536       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1537   }
1539   if(($post_var)&&($numpages)){
1540     $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()'>";
1541     foreach(array(20,50,100,200,"all") as $num){
1542       if($num == "all"){
1543         $var = 10000;
1544       }else{
1545         $var = $num;
1546       }
1547       if($var == $range){
1548         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1549       }else{  
1550         $output.="\n<option value='".$var."'>".$num."</option>";
1551       }
1552     }
1553     $output.=  "</select></td></tr></table></div>";
1554   }else{
1555     $output.= "</div>";
1556   }
1558   return($output);
1562 function apply_filter()
1564   $apply= "";
1566   $apply= ''.
1567     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1568     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1570   return ($apply);
1574 function back_to_main()
1576   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1577     _("Back").'"></p><input type="hidden" name="ignore">';
1579   return ($string);
1583 function normalize_netmask($netmask)
1585   /* Check for notation of netmask */
1586   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1587     $num= (int)($netmask);
1588     $netmask= "";
1590     for ($byte= 0; $byte<4; $byte++){
1591       $result=0;
1593       for ($i= 7; $i>=0; $i--){
1594         if ($num-- > 0){
1595           $result+= pow(2,$i);
1596         }
1597       }
1599       $netmask.= $result.".";
1600     }
1602     return (preg_replace('/\.$/', '', $netmask));
1603   }
1605   return ($netmask);
1609 function netmask_to_bits($netmask)
1611   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1612   $res= 0;
1614   for ($n= 0; $n<4; $n++){
1615     $start= 255;
1616     $name= "nm$n";
1618     for ($i= 0; $i<8; $i++){
1619       if ($start == (int)($$name)){
1620         $res+= 8 - $i;
1621         break;
1622       }
1623       $start-= pow(2,$i);
1624     }
1625   }
1627   return ($res);
1631 function recurse($rule, $variables)
1633   $result= array();
1635   if (!count($variables)){
1636     return array($rule);
1637   }
1639   reset($variables);
1640   $key= key($variables);
1641   $val= current($variables);
1642   unset ($variables[$key]);
1644   foreach($val as $possibility){
1645     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1646     $result= array_merge($result, recurse($nrule, $variables));
1647   }
1649   return ($result);
1653 function expand_id($rule, $attributes)
1655   /* Check for id rule */
1656   if(preg_match('/^id(:|#)\d+$/',$rule)){
1657     return (array("\{$rule}"));
1658   }
1660   /* Check for clean attribute */
1661   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1662     $rule= preg_replace('/^%/', '', $rule);
1663     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1664     return (array($val));
1665   }
1667   /* Check for attribute with parameters */
1668   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1669     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1670     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1671     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1672     $start= preg_replace ('/-.*$/', '', $param);
1673     $stop = preg_replace ('/^[^-]+-/', '', $param);
1675     /* Assemble results */
1676     $result= array();
1677     for ($i= $start; $i<= $stop; $i++){
1678       $result[]= substr($val, 0, $i);
1679     }
1680     return ($result);
1681   }
1683   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1684   return (array($rule));
1688 function gen_uids($rule, $attributes)
1690   global $config;
1692   /* Search for keys and fill the variables array with all 
1693      possible values for that key. */
1694   $part= "";
1695   $trigger= false;
1696   $stripped= "";
1697   $variables= array();
1699   for ($pos= 0; $pos < strlen($rule); $pos++){
1701     if ($rule[$pos] == "{" ){
1702       $trigger= true;
1703       $part= "";
1704       continue;
1705     }
1707     if ($rule[$pos] == "}" ){
1708       $variables[$pos]= expand_id($part, $attributes);
1709       $stripped.= "{".$pos."}";
1710       $trigger= false;
1711       continue;
1712     }
1714     if ($trigger){
1715       $part.= $rule[$pos];
1716     } else {
1717       $stripped.= $rule[$pos];
1718     }
1719   }
1721   /* Recurse through all possible combinations */
1722   $proposed= recurse($stripped, $variables);
1724   /* Get list of used ID's */
1725   $used= array();
1726   $ldap= $config->get_ldap_link();
1727   $ldap->cd($config->current['BASE']);
1728   $ldap->search('(uid=*)');
1730   while($attrs= $ldap->fetch()){
1731     $used[]= $attrs['uid'][0];
1732   }
1734   /* Remove used uids and watch out for id tags */
1735   $ret= array();
1736   foreach($proposed as $uid){
1738     /* Check for id tag and modify uid if needed */
1739     if(preg_match('/\{id:\d+}/',$uid)){
1740       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1742       for ($i= 0; $i < pow(10,$size); $i++){
1743         $number= sprintf("%0".$size."d", $i);
1744         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1745         if (!in_array($res, $used)){
1746           $uid= $res;
1747           break;
1748         }
1749       }
1750     }
1752   if(preg_match('/\{id#\d+}/',$uid)){
1753     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1755     while (true){
1756       mt_srand((double) microtime()*1000000);
1757       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1758       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1759       if (!in_array($res, $used)){
1760         $uid= $res;
1761         break;
1762       }
1763     }
1764   }
1766 /* Don't assign used ones */
1767 if (!in_array($uid, $used)){
1768   $ret[]= $uid;
1772 return(array_unique($ret));
1776 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1777    Need to convert... */
1778 function to_byte($value) {
1779   $value= strtolower(trim($value));
1781   if(!is_numeric(substr($value, -1))) {
1783     switch(substr($value, -1)) {
1784       case 'g':
1785         $mult= 1073741824;
1786         break;
1787       case 'm':
1788         $mult= 1048576;
1789         break;
1790       case 'k':
1791         $mult= 1024;
1792         break;
1793     }
1795     return ($mult * (int)substr($value, 0, -1));
1796   } else {
1797     return $value;
1798   }
1802 function in_array_ics($value, $items)
1804   if (!is_array($items)){
1805     return (FALSE);
1806   }
1808   foreach ($items as $item){
1809     if (strcasecmp($item, $value) == 0) {
1810       return (TRUE);
1811     }
1812   }
1814   return (FALSE);
1815
1818 function generate_alphabet($count= 10)
1820   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1821   $alphabet= "";
1822   $c= 0;
1824   /* Fill cells with charaters */
1825   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1826     if ($c == 0){
1827       $alphabet.= "<tr>";
1828     }
1830     $ch = mb_substr($characters, $i, 1, "UTF8");
1831     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1832       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1834     if ($c++ == $count){
1835       $alphabet.= "</tr>";
1836       $c= 0;
1837     }
1838   }
1840   /* Fill remaining cells */
1841   while ($c++ <= $count){
1842     $alphabet.= "<td>&nbsp;</td>";
1843   }
1845   return ($alphabet);
1849 function validate($string)
1851   return (strip_tags(preg_replace('/\0/', '', $string)));
1855 function get_gosa_version()
1857   global $svn_revision, $svn_path;
1859   /* Extract informations */
1860   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1862   /* Release or development? */
1863   if (preg_match('%/gosa/trunk/%', $svn_path)){
1864     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1865   } else {
1866     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1867     return (sprintf(_("GOsa $release"), $revision));
1868   }
1872 function rmdirRecursive($path, $followLinks=false) {
1873   $dir= opendir($path);
1874   while($entry= readdir($dir)) {
1875     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1876       unlink($path."/".$entry);
1877     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1878       rmdirRecursive($path."/".$entry);
1879     }
1880   }
1881   closedir($dir);
1882   return rmdir($path);
1886 function scan_directory($path,$sort_desc=false)
1888   $ret = false;
1890   /* is this a dir ? */
1891   if(is_dir($path)) {
1893     /* is this path a readable one */
1894     if(is_readable($path)){
1896       /* Get contents and write it into an array */   
1897       $ret = array();    
1899       $dir = opendir($path);
1901       /* Is this a correct result ?*/
1902       if($dir){
1903         while($fp = readdir($dir))
1904           $ret[]= $fp;
1905       }
1906     }
1907   }
1908   /* Sort array ascending , like scandir */
1909   sort($ret);
1911   /* Sort descending if parameter is sort_desc is set */
1912   if($sort_desc) {
1913     $ret = array_reverse($ret);
1914   }
1916   return($ret);
1920 function clean_smarty_compile_dir($directory)
1922   global $svn_revision;
1924   if(is_dir($directory) && is_readable($directory)) {
1925     // Set revision filename to REVISION
1926     $revision_file= $directory."/REVISION";
1928     /* Is there a stamp containing the current revision? */
1929     if(!file_exists($revision_file)) {
1930       // create revision file
1931       create_revision($revision_file, $svn_revision);
1932     } else {
1933       # check for "$config->...['CONFIG']/revision" and the
1934       # contents should match the revision number
1935       if(!compare_revision($revision_file, $svn_revision)){
1936         // If revision differs, clean compile directory
1937         foreach(scan_directory($directory) as $file) {
1938           if(($file==".")||($file=="..")) continue;
1939           if( is_file($directory."/".$file) &&
1940               is_writable($directory."/".$file)) {
1941             // delete file
1942             if(!unlink($directory."/".$file)) {
1943               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1944               // This should never be reached
1945             }
1946           } elseif(is_dir($directory."/".$file) &&
1947               is_writable($directory."/".$file)) {
1948             // Just recursively delete it
1949             rmdirRecursive($directory."/".$file);
1950           }
1951         }
1952         // We should now create a fresh revision file
1953         clean_smarty_compile_dir($directory);
1954       } else {
1955         // Revision matches, nothing to do
1956       }
1957     }
1958   } else {
1959     // Smarty compile dir is not accessible
1960     // (Smarty will warn about this)
1961   }
1965 function create_revision($revision_file, $revision)
1967   $result= false;
1969   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1970     if($fh= fopen($revision_file, "w")) {
1971       if(fwrite($fh, $revision)) {
1972         $result= true;
1973       }
1974     }
1975     fclose($fh);
1976   } else {
1977     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1978   }
1980   return $result;
1984 function compare_revision($revision_file, $revision)
1986   // false means revision differs
1987   $result= false;
1989   if(file_exists($revision_file) && is_readable($revision_file)) {
1990     // Open file
1991     if($fh= fopen($revision_file, "r")) {
1992       // Compare File contents with current revision
1993       if($revision == fread($fh, filesize($revision_file))) {
1994         $result= true;
1995       }
1996     } else {
1997       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1998     }
1999     // Close file
2000     fclose($fh);
2001   }
2003   return $result;
2007 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2009   $str = ""; // Our return value will be saved in this var
2011   $color  = dechex($percentage+150);
2012   $color2 = dechex(150 - $percentage);
2013   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2015   $progress = (int)(($percentage /100)*$width);
2017   /* Abort printing out percentage, if divs are to small */
2020   /* If theres a better solution for this, use it... */
2021   $str = "
2022     <div style=\" width:".($width)."px; 
2023     height:".($height)."px;
2024   background-color:#000000;
2025 padding:1px;\">
2027           <div style=\" width:".($width)."px;
2028         background-color:#$bgcolor;
2029 height:".($height)."px;\">
2031          <div style=\" width:".$progress."px;
2032 height:".$height."px;
2033        background-color:#".$color2.$color2.$color."; \">";
2036        if(($height >10)&&($showvalue)){
2037          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2038            <b>".$percentage."%</b>
2039            </font>";
2040        }
2042        $str.= "</div></div></div>";
2044        return($str);
2048 function array_key_ics($ikey, $items)
2050   /* Gather keys, make them lowercase */
2051   $tmp= array();
2052   foreach ($items as $key => $value){
2053     $tmp[strtolower($key)]= $key;
2054   }
2056   if (isset($tmp[strtolower($ikey)])){
2057     return($tmp[strtolower($ikey)]);
2058   }
2060   return ("");
2064 function array_differs($src, $dst)
2066   /* If the count is differing, the arrays differ */
2067   if (count ($src) != count ($dst)){
2068     return (TRUE);
2069   }
2071   /* So the count is the same - lets check the contents */
2072   $differs= FALSE;
2073   foreach($src as $value){
2074     if (!in_array($value, $dst)){
2075       $differs= TRUE;
2076     }
2077   }
2079   return ($differs);
2083 function saveFilter($a_filter, $values)
2085   if (isset($_POST['regexit'])){
2086     $a_filter["regex"]= $_POST['regexit'];
2088     foreach($values as $type){
2089       if (isset($_POST[$type])) {
2090         $a_filter[$type]= "checked";
2091       } else {
2092         $a_filter[$type]= "";
2093       }
2094     }
2095   }
2097   /* React on alphabet links if needed */
2098   if (isset($_GET['search'])){
2099     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2100     if ($s == "**"){
2101       $s= "*";
2102     }
2103     $a_filter['regex']= $s;
2104   }
2106   return ($a_filter);
2110 /* Escape all preg_* relevant characters */
2111 function normalizePreg($input)
2113   return (addcslashes($input, '[]()|/.*+-'));
2117 /* Escape all LDAP filter relevant characters */
2118 function normalizeLdap($input)
2120   return (addcslashes($input, '()|'));
2124 /* Resturns the difference between to microtime() results in float  */
2125 function get_MicroTimeDiff($start , $stop)
2127   $a = split("\ ",$start);
2128   $b = split("\ ",$stop);
2130   $secs = $b[1] - $a[1];
2131   $msecs= $b[0] - $a[0]; 
2133   $ret = (float) ($secs+ $msecs);
2134   return($ret);
2138 function get_base_dir()
2140   global $BASE_DIR;
2142   return $BASE_DIR;
2146 function obj_is_readable($dn, $object, $attribute)
2148   global $ui;
2150   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2154 function obj_is_writable($dn, $object, $attribute)
2156   global $ui;
2158   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2162 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2164   /* Initialize variables */
2165   $ret  = array("count" => 0);  // Set count to 0
2166   $next = true;                 // if false, then skip next loops and return
2167   $cnt  = 0;                    // Current number of loops
2168   $max  = 100;                  // Just for security, prevent looops
2169   $ldap = NULL;                 // To check if created result a valid
2170   $keep = "";                   // save last failed parse string
2172   /* Check each parsed dn in ldap ? */
2173   if($config!==NULL && $verify_in_ldap){
2174     $ldap = $config->get_ldap_link();
2175   }
2177   /* Lets start */
2178   $called = false;
2179   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2181     $cnt ++;
2182     if(!preg_match("/,/",$dn)){
2183       $next = false;
2184     }
2185     $object = preg_replace("/[,].*$/","",$dn);
2186     $dn     = preg_replace("/^[^,]+,/","",$dn);
2188     $called = true;
2190     /* Check if current dn is valid */
2191     if($ldap!==NULL){
2192       $ldap->cd($dn);
2193       $ldap->cat($dn,array("dn"));
2194       if($ldap->count()){
2195         $ret[]  = $keep.$object;
2196         $keep   = "";
2197       }else{
2198         $keep  .= $object.",";
2199       }
2200     }else{
2201       $ret[]  = $keep.$object;
2202       $keep   = "";
2203     }
2204   }
2206   /* No dn was posted */
2207   if($cnt == 0 && !empty($dn)){
2208     $ret[] = $dn;
2209   }
2211   /* Append the rest */
2212   $test = $keep.$dn;
2213   if($called && !empty($test)){
2214     $ret[] = $keep.$dn;
2215   }
2216   $ret['count'] = count($ret) - 1;
2218   return($ret);
2222 function get_base_from_hook($dn, $attrib)
2224   global $config;
2226   if (isset($config->current['BASE_HOOK'])){
2227     
2228     /* Call hook script - if present */
2229     $command= $config->current['BASE_HOOK'];
2231     if ($command != ""){
2232       $command.= " '".LDAP::fix($dn)."' $attrib";
2233       if (check_command($command)){
2234         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2235         exec($command, $output);
2236         if (preg_match("/^[0-9]+$/", $output[0])){
2237           return ($output[0]);
2238         } else {
2239           msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2240           return ($config->current['UIDBASE']);
2241         }
2242       } else {
2243         msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2244         return ($config->current['UIDBASE']);
2245       }
2247     } else {
2249       msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2250       return ($config->current['UIDBASE']);
2252     }
2253   }
2257 function check_schema_version($class, $version)
2259   return preg_match("/\(v$version\)/", $class['DESC']);
2263 function check_schema($cfg,$rfc2307bis = FALSE)
2265   $messages= array();
2267   /* Get objectclasses */
2268   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2269   $objectclasses = $ldap->get_objectclasses();
2270   if(count($objectclasses) == 0){
2271     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2272   }
2274   /* This is the default block used for each entry.
2275    *  to avoid unset indexes.
2276    */
2277   $def_check = array("REQUIRED_VERSION" => "0",
2278       "SCHEMA_FILES"     => array(),
2279       "CLASSES_REQUIRED" => array(),
2280       "STATUS"           => FALSE,
2281       "IS_MUST_HAVE"     => FALSE,
2282       "MSG"              => "",
2283       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2285   /* The gosa base schema */
2286   $checks['gosaObject'] = $def_check;
2287   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2288   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2289   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2290   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2292   /* GOsa Account class */
2293   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2294   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2295   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2296   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2297   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2299   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2300   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2301   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2302   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2303   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2304   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2306   /* Some other checks */
2307   foreach(array(
2308         "gosaCacheEntry"        => array("version" => "2.4"),
2309         "gosaDepartment"        => array("version" => "2.4"),
2310         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2311         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2312         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2313         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2314         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2315         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2316         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2317         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2318         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2319         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2320         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2321         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2322         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2323         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2324         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2325         "goLdapServer"          => array("version" => "2.4"),
2326         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2327         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2328         "goKrbServer"           => array("version" => "2.4"),
2329         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2330         ) as $name => $values){
2332           $checks[$name] = $def_check;
2333           if(isset($values['version'])){
2334             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2335           }
2336           if(isset($values['file'])){
2337             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2338           }
2339           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2340         }
2341   foreach($checks as $name => $value){
2342     foreach($value['CLASSES_REQUIRED'] as $class){
2344       if(!isset($objectclasses[$name])){
2345         $checks[$name]['STATUS'] = FALSE;
2346         if($value['IS_MUST_HAVE']){
2347           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2348         }else{
2349           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2350         }
2351       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2352         $checks[$name]['STATUS'] = FALSE;
2354         if($value['IS_MUST_HAVE']){
2355           $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2356         }else{
2357           $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2358         }
2359       }else{
2360         $checks[$name]['STATUS'] = TRUE;
2361         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2362       }
2363     }
2364   }
2366   $tmp = $objectclasses;
2368   /* The gosa base schema */
2369   $checks['posixGroup'] = $def_check;
2370   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2371   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2372   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2373   $checks['posixGroup']['STATUS']           = TRUE;
2374   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2375   $checks['posixGroup']['MSG']              = "";
2376   $checks['posixGroup']['INFO']             = "";
2378   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2379   if(isset($tmp['posixGroup'])){
2381     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2382       $checks['posixGroup']['STATUS']           = FALSE;
2383       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2384       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2385     }
2386     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2387       $checks['posixGroup']['STATUS']           = FALSE;
2388       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2389       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2390     }
2391   }
2393   return($checks);
2397 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2399   $tmp = array(
2400         "de_DE" => "German",
2401         "fr_FR" => "French",
2402         "it_IT" => "Italian",
2403         "es_ES" => "Spanish",
2404         "en_US" => "English",
2405         "nl_NL" => "Dutch",
2406         "pl_PL" => "Polish",
2407         "sv_SE" => "Swedish",
2408         "zh_CN" => "Chinese",
2409         "ru_RU" => "Russian");
2410   
2411   $tmp2= array(
2412         "de_DE" => _("German"),
2413         "fr_FR" => _("French"),
2414         "it_IT" => _("Italian"),
2415         "es_ES" => _("Spanish"),
2416         "en_US" => _("English"),
2417         "nl_NL" => _("Dutch"),
2418         "pl_PL" => _("Polish"),
2419         "sv_SE" => _("Swedish"),
2420         "zh_CN" => _("Chinese"),
2421         "ru_RU" => _("Russian"));
2423   $ret = array();
2424   if($languages_in_own_language){
2426     $old_lang = setlocale(LC_ALL, 0);
2427     foreach($tmp as $key => $name){
2428       $lang = $key.".UTF-8";
2429       setlocale(LC_ALL, $lang);
2430       if($strip_region_tag){
2431         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2432       }else{
2433         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2434       }
2435     }
2436     setlocale(LC_ALL, $old_lang);
2437   }else{
2438     foreach($tmp as $key => $name){
2439       if($strip_region_tag){
2440         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2441       }else{
2442         $ret[$key] = _($name);
2443       }
2444     }
2445   }
2446   return($ret);
2450 /* Returns contents of the given POST variable and check magic quotes settings */
2451 function get_post($name)
2453   if(!isset($_POST[$name])){
2454     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2455     return(FALSE);
2456   }
2457   if(get_magic_quotes_gpc()){
2458     return(stripcslashes($_POST[$name]));
2459   }else{
2460     return($_POST[$name]);
2461   }
2465 /* Return class name in correct case */
2466 function get_correct_class_name($cls)
2468   global $class_mapping;
2469   if(isset($class_mapping) && is_array($class_mapping)){
2470     foreach($class_mapping as $class => $file){
2471       if(preg_match("/^".$cls."$/i",$class)){
2472         return($class);
2473       }
2474     }
2475   }
2476   return(FALSE);
2480 // change_password, changes the Password, of the given dn
2481 function change_password ($dn, $password, $mode=0, $hash= "")
2483   global $config;
2484   $newpass= "";
2486   /* Convert to lower. Methods are lowercase */
2487   $hash= strtolower($hash);
2489   // Get all available encryption Methods
2491   // NON STATIC CALL :)
2492   $tmp = new passwordMethod(session::get('config'));
2493   $available = $tmp->get_available_methods();
2495   // read current password entry for $dn, to detect the encryption Method
2496   $ldap       = $config->get_ldap_link();
2497   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2498   $attrs      = $ldap->fetch ();
2500   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2501   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2502     $deactivated = TRUE;
2503   }else{
2504     $deactivated = FALSE;
2505   }
2507   /* Is ensure that clear passwords will stay clear */
2508   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2509     $hash = "clear";
2510   }
2512   // Detect the encryption Method
2513   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2515     /* Check for supported algorithm */
2516     mt_srand((double) microtime()*1000000);
2518     /* Extract used hash */
2519     if ($hash == ""){
2520       $hash= strtolower($matches[1]);
2521     }
2523     $test = new  $available[$hash]($config);
2525   } else {
2526     // User MD5 by default
2527     $hash= "md5";
2528     $test = new  $available['md5']($config);
2529   }
2531   /* Feed password backends with information */
2532   $test->dn= $dn;
2533   $test->attrs= $attrs;
2534   $newpass= $test->generate_hash($password);
2536   // Update shadow timestamp?
2537   if (isset($attrs["shadowLastChange"][0])){
2538     $shadow= (int)(date("U") / 86400);
2539   } else {
2540     $shadow= 0;
2541   }
2543   // Write back modified entry
2544   $ldap->cd($dn);
2545   $attrs= array();
2547   // Not for groups
2548   if ($mode == 0){
2550     if ($shadow != 0){
2551       $attrs['shadowLastChange']= $shadow;
2552     }
2554     // Create SMB Password
2555     $attrs= generate_smb_nt_hash($password);
2556   }
2558  /* Readd ! if user was deactivated */
2559   if($deactivated){
2560     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2561   }
2563   $attrs['userPassword']= array();
2564   $attrs['userPassword']= $newpass;
2566   $ldap->modify($attrs);
2568   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2570   if ($ldap->error != 'Success') {
2571     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);
2572   } else {
2574     /* Run backend method for change/create */
2575     $test->set_password($password);
2577     /* Find postmodify entries for this class */
2578     $command= $config->search("password", "POSTMODIFY",array('menu'));
2580     if ($command != ""){
2581       /* Walk through attribute list */
2582       $command= preg_replace("/%userPassword/", $password, $command);
2583       $command= preg_replace("/%dn/", $dn, $command);
2585       if (check_command($command)){
2586         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2587         exec($command);
2588       } else {
2589         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2590         msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2591       }
2592     }
2593   }
2597 // Return something like array['sambaLMPassword']= "lalla..."
2598 function generate_smb_nt_hash($password)
2600   global $config;
2602   # Try to use gosa-si?
2603   if (isset($config->current['GOSA_SI'])){
2604         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2605         $hash= $res['XML']['HASH'];
2606   } else {
2607           $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2608           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2610           exec($tmp, $ar);
2611           flush();
2612           reset($ar);
2613           $hash= current($ar);
2614   }
2616   if ($hash == "") {
2617           msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2618           return ("");
2619   }
2621   list($lm,$nt)= split (":", trim($hash));
2623   if ($config->current['SAMBAVERSION'] == 3) {
2624           $attrs['sambaLMPassword']= $lm;
2625           $attrs['sambaNTPassword']= $nt;
2626           $attrs['sambaPwdLastSet']= date('U');
2627           $attrs['sambaBadPasswordCount']= "0";
2628           $attrs['sambaBadPasswordTime']= "0";
2629   } else {
2630           $attrs['lmPassword']= $lm;
2631           $attrs['ntPassword']= $nt;
2632           $attrs['pwdLastSet']= date('U');
2633   }
2634   return($attrs);
2638 function crypt_single($string,$enc_type )
2640   return( passwordMethod::crypt_single_str($string,$enc_type));
2644 function getEntryCSN($dn)
2646   global $config;
2647   if(empty($dn) || !is_object($config)){
2648     return("");
2649   }
2651   /* Get attribute that we should use as serial number */
2652   if(isset($config->current['UNIQ_IDENTIFIER'])){
2653     $attr = $config->current['UNIQ_IDENTIFIER'];
2654   }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2655     $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2656   }
2657   if(!empty($attr)){
2658     $ldap = $config->get_ldap_link();
2659     $ldap->cat($dn,array($attr));
2660     $csn = $ldap->fetch();
2661     if(isset($csn[$attr][0])){
2662       return($csn[$attr][0]);
2663     }
2664   }
2665   return("");
2669 /* Add a given objectClass to an attrs entry */
2670 function add_objectClass($classes, &$attrs)
2672   if (is_array($classes)){
2673     $list= $classes;
2674   } else {
2675     $list= array($classes);
2676   }
2678   foreach ($list as $class){
2679     $attrs['objectClass'][]= $class;
2680   }
2684 /* Removes a given objectClass from the attrs entry */
2685 function remove_objectClass($classes, &$attrs)
2687   if (isset($attrs['objectClass'])){
2688     /* Array? */
2689     if (is_array($classes)){
2690       $list= $classes;
2691     } else {
2692       $list= array($classes);
2693     }
2695     $tmp= array();
2696     foreach ($attrs['objectClass'] as $oc) {
2697       foreach ($list as $class){
2698         if ($oc != $class){
2699           $tmp[]= $oc;
2700         }
2701       }
2702     }
2703     $attrs['objectClass']= $tmp;
2704   }
2707 /*! \brief  Initialize a file download with given content, name and data type. 
2708  *  @param  data  String The content to send.
2709  *  @param  name  String The name of the file.
2710  *  @param  type  String The content identifier, default value is "application/octet-stream";
2711  */
2712 function send_binary_content($data,$name,$type = "application/octet-stream")
2714   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2715   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2716   header("Cache-Control: no-cache");
2717   header("Pragma: no-cache");
2718   header("Cache-Control: post-check=0, pre-check=0");
2719   header("Content-type: ".$type."");
2721   /* force download dialog */
2722   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2723     header('Content-Disposition: filename="'.$name.'"');
2724   } else {
2725     header('Content-Disposition: attachment; filename="'.$name.'"');
2726   }
2728   echo $data;
2729   exit();
2732 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2733 ?>