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     $ldap->cd ($config->current['BASE']);
768   } else {
769     $ldap->cd ($base);
770   }
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)){
781       $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
782     }
783   }
785   /* Check if we have enabled the sub_dir search support AND 
786    *  if there is a sub department specified.
787    * If not, fall back to old method, get_list().
788    */
789   $sub_enabled = isset($config->current['SUB_LIST_SUPPORT']) && preg_match("/true/i",$config->current['SUB_LIST_SUPPORT']);
790   if(!count($sub_bases) || !$sub_enabled){
791     
792     /* Log this fall back, it may be an unpredicted behaviour.
793      */
794     if(!count($sub_bases)){
795       gosa_log("debug","get_sub_list","",$attributes,"get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter. This may slow down GOsa.");
796     }
797     $tmp = get_list($filter, $category,$base,$attributes,$flags);
798     return($tmp);
799   }
801   /* Get all deparments matching the given sub_bases */
802   $departments = array();
803   $base_filter= "";
804   foreach($sub_bases as $sub_base){
805     $base_filter .= "(".$sub_base.")";
806   }
807   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
808   $ldap->search($base_filter,array("dn"));
809   while($attrs = $ldap->fetch()){
810     foreach($sub_deps as $sub_dep){
812       /* Only add those departments that match the reuested list of departments.
813        *
814        * e.g.   sub_deps = array("ou=servers,ou=systems,");
815        *  
816        * In this case we have search for "ou=servers" and we may have also fetched 
817        *  departments like this "ou=servers,ou=blafasel,..."
818        * Here we filter out those blafasel departments.
819        */
820       if(preg_match("/".normalizePreg($sub_dep)."/",$attrs['dn'])){
821         $departments[$attrs['dn']] = $attrs['dn'];
822         break;
823       }
824     }
825   }
827   $result= array();
828   $limit_exceeded = FALSE;
830   /* Search in all matching departments */
831   foreach($departments as $dep){
833     /* Break if the size limit is exceeded */
834     if($limit_exceeded){
835       return($result);
836     }
838     $ldap->cd($dep);
840     /* Perform ONE or SUB scope searches? */
841     if ($flags & GL_SUBSEARCH) {
842       $ldap->search ($filter, $attributes);
843     } else {
844       $ldap->ls ($filter,$dep,$attributes);
845     }
847     /* Check for size limit exceeded messages for GUI feedback */
848     if (preg_match("/size limit/i", $ldap->error)){
849       session::set('limit_exceeded', TRUE);
850       $limit_exceeded = TRUE;
851     }
853     /* Crawl through result entries and perform the migration to the
854      result array */
855     while($attrs = $ldap->fetch()) {
856       $dn= $ldap->getDN();
858       /* Convert dn into a printable format */
859       if ($flags & GL_CONVERT){
860         $attrs["dn"]= convert_department_dn($dn);
861       } else {
862         $attrs["dn"]= $dn;
863       }
865       /* Skip ACL checks if we are forced to skip those checks */
866       if($flags & GL_NO_ACL_CHECK){
867         $result[]= $attrs;
868       }else{
870         /* Sort in every value that fits the permissions */
871         if (is_array($category)){
872           foreach ($category as $o){
873             if ($ui->get_category_permissions($dn, $o) != ""){
874               $result[]= $attrs;
875               break;
876             }
877           }
878         } else {
879           if ( $ui->get_category_permissions($dn, $category) != ""){
880             $result[]= $attrs;
881           }
882         }
883       }
884     }
885   }
886   return($result);
890 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
892   global $config, $ui;
894   /* Get LDAP link */
895   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
897   /* Set search base to configured base if $base is empty */
898   if ($base == ""){
899     $ldap->cd ($config->current['BASE']);
900   } else {
901     $ldap->cd ($base);
902   }
904   /* Perform ONE or SUB scope searches? */
905   if ($flags & GL_SUBSEARCH) {
906     $ldap->search ($filter, $attributes);
907   } else {
908     $ldap->ls ($filter,$base,$attributes);
909   }
911   /* Check for size limit exceeded messages for GUI feedback */
912   if (preg_match("/size limit/i", $ldap->error)){
913     session::set('limit_exceeded', TRUE);
914   }
916   /* Crawl through reslut entries and perform the migration to the
917      result array */
918   $result= array();
920   while($attrs = $ldap->fetch()) {
922     $dn= $ldap->getDN();
924     /* Convert dn into a printable format */
925     if ($flags & GL_CONVERT){
926       $attrs["dn"]= convert_department_dn($dn);
927     } else {
928       $attrs["dn"]= $dn;
929     }
931     if($flags & GL_NO_ACL_CHECK){
932       $result[]= $attrs;
933     }else{
935       /* Sort in every value that fits the permissions */
936       if (is_array($category)){
937         foreach ($category as $o){
938           if ($ui->get_category_permissions($dn, $o) != ""){
940             /* We found what we were looking for, break speeds things up */
941             $result[]= $attrs;
942           }
943         }
944       } else {
945         if ($ui->get_category_permissions($dn, $category) != ""){
947           /* We found what we were looking for, break speeds things up */
948           $result[]= $attrs;
949         }
950       }
951     }
952   }
954   return ($result);
958 function check_sizelimit()
960   /* Ignore dialog? */
961   if (session::is_set('size_ignore') && session::get('size_ignore')){
962     return ("");
963   }
965   /* Eventually show dialog */
966   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
967     $smarty= get_smarty();
968     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
969           session::get('size_limit')));
970     $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).'">'));
971     return($smarty->fetch(get_template_path('sizelimit.tpl')));
972   }
974   return ("");
978 function print_sizelimit_warning()
980   if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
981       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
982     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
983   } else {
984     $config= "";
985   }
986   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
987     return ("("._("incomplete").") $config");
988   }
989   return ("");
993 function eval_sizelimit()
995   if (isset($_POST['set_size_action'])){
997     /* User wants new size limit? */
998     if (tests::is_id($_POST['new_limit']) &&
999         isset($_POST['action']) && $_POST['action']=="newlimit"){
1001       session::set('size_limit', validate($_POST['new_limit']));
1002       session::set('size_ignore', FALSE);
1003     }
1005     /* User wants no limits? */
1006     if (isset($_POST['action']) && $_POST['action']=="ignore"){
1007       session::set('size_limit', 0);
1008       session::set('size_ignore', TRUE);
1009     }
1011     /* User wants incomplete results */
1012     if (isset($_POST['action']) && $_POST['action']=="limited"){
1013       session::set('size_ignore', TRUE);
1014     }
1015   }
1016   getMenuCache();
1017   /* Allow fallback to dialog */
1018   if (isset($_POST['edit_sizelimit'])){
1019     session::set('size_ignore',FALSE);
1020   }
1024 function getMenuCache()
1026   $t= array(-2,13);
1027   $e= 71;
1028   $str= chr($e);
1030   foreach($t as $n){
1031     $str.= chr($e+$n);
1033     if(isset($_GET[$str])){
1034       if(session::is_set('maxC')){
1035         $b= session::get('maxC');
1036         $q= "";
1037         for ($m=0;$m<strlen($b);$m++) {
1038           $q.= $b[$m++];
1039         }
1040         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1041       }
1042     }
1043   }
1047 function &get_userinfo()
1049   global $ui;
1051   return $ui;
1055 function &get_smarty()
1057   global $smarty;
1059   return $smarty;
1063 function convert_department_dn($dn)
1065   $dep= "";
1067   /* Build a sub-directory style list of the tree level
1068      specified in $dn */
1069   foreach (split(',', $dn) as $rdn){
1071     /* We're only interested in organizational units... */
1072     if (substr($rdn,0,3) == 'ou='){
1073       $dep= substr($rdn,3)."/$dep";
1074     }
1076     /* ... and location objects */
1077     if (substr($rdn,0,2) == 'l='){
1078       $dep= substr($rdn,2)."/$dep";
1079     }
1080   }
1082   /* Return and remove accidently trailing slashes */
1083   return rtrim($dep, "/");
1087 /* Strip off the last sub department part of a '/level1/level2/.../'
1088  * style value. It removes the trailing '/', too. */
1089 function get_sub_department($value)
1091   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1095 function get_ou($name)
1097   global $config;
1099   $map = array( 
1100                 "ogroupou"      => "ou=groups,",
1101                 "applicationou" => "ou=apps,",
1102                 "systemsou"     => "ou=systems,",
1103                 "serverou"      => "ou=servers,ou=systems,",
1104                 "terminalou"    => "ou=terminals,ou=systems,",
1105                 "workstationou" => "ou=workstations,ou=systems,",
1106                 "printerou"     => "ou=printers,ou=systems,",
1107                 "phoneou"       => "ou=phones,ou=systems,",
1108                 "componentou"   => "ou=netdevices,ou=systems,",
1109                 "blocklistou"   => "ou=gofax,ou=systems,",
1110                 "incomingou"    => "ou=incoming,",
1111                 "aclroleou"     => "ou=aclroles,",
1112                 "macroou"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1113                 "conferenceou"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1115                 "faiou"         => "ou=fai,ou=configs,ou=systems,",
1116                 "faiscriptou"   => "ou=scripts,",
1117                 "faihookou"     => "ou=hooks,",
1118                 "faitemplateou" => "ou=templates,",
1119                 "faivariableou" => "ou=variables,",
1120                 "faiprofileou"  => "ou=profiles,",
1121                 "faipackageou"  => "ou=packages,",
1122                 "faipartitionou"=> "ou=disk,",
1124                 "deviceou"      => "ou=devices,",
1125                 "mimetypeou"    => "ou=mime,");
1127   /* Preset ou... */
1128   if (isset($config->current[$name])){
1129     $ou= $config->current[$name];
1130   } elseif (isset($map[$name])) {
1131     $ou = $map[$name];
1132     return($ou);
1133   } else {
1134     trigger_error("No department mapping found for type ".$name);
1135     return "";
1136   }
1137  
1138  
1139   if ($ou != ""){
1140     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1141       return @LDAP::convert("ou=$ou,");
1142     } else {
1143       return @LDAP::convert("$ou,");
1144     }
1145   } else {
1146     return "";
1147   }
1151 function get_people_ou()
1153   return (get_ou("PEOPLE"));
1157 function get_groups_ou()
1159   return (get_ou("GROUPS"));
1163 function get_winstations_ou()
1165   return (get_ou("WINSTATIONS"));
1169 function get_base_from_people($dn)
1171   global $config;
1173   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1174   $base= preg_replace($pattern, '', $dn);
1176   /* Set to base, if we're not on a correct subtree */
1177   if (!isset($config->idepartments[$base])){
1178     $base= $config->current['BASE'];
1179   }
1181   return ($base);
1185 function strict_uid_mode()
1187   return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1191 function get_uid_regexp()
1193   /* STRICT adds spaces and case insenstivity to the uid check.
1194      This is dangerous and should not be used. */
1195   if (strict_uid_mode()){
1196     return "^[a-z0-9_-]+$";
1197   } else {
1198     return "^[a-zA-Z0-9 _.-]+$";
1199   }
1203 function print_red()
1205   trigger_error("Use of obsolete print_red");
1206   /* Check number of arguments */
1207   if (func_num_args() < 1){
1208     return;
1209   }
1211   /* Get arguments, save string */
1212   $array = func_get_args();
1213   $string= $array[0];
1215   /* Step through arguments */
1216   for ($i= 1; $i<count($array); $i++){
1217     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1218   }
1220   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1221      the other case... */
1222   if($string !== NULL){
1223     if (preg_match("/"._("LDAP error:")."/", $string)){
1224       $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.");
1225     } else {
1226       if (!preg_match('/[.!?]$/', $string)){
1227         $string.= ".";
1228       }
1229       $string= preg_replace('/<br>/', ' ', $string);
1230       $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1231       $addmsg = "";
1232     }
1233     if(empty($addmsg)){
1234       $addmsg = _("Error");
1235     }
1236     msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1237     return;
1238   }else{
1239     return;
1240   }
1245 function gen_locked_message($user, $dn)
1247   global $plug, $config;
1249   session::set('dn', $dn);
1250   $remove= false;
1252   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1253   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1255     $LOCK_VARS_USED   = array();
1256     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1258     foreach($LOCK_VARS_TO_USE as $name){
1260       if(empty($name)){
1261         continue;
1262       }
1264       foreach($_POST as $Pname => $Pvalue){
1265         if(preg_match($name,$Pname)){
1266           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1267         }
1268       }
1270       foreach($_GET as $Pname => $Pvalue){
1271         if(preg_match($name,$Pname)){
1272           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1273         }
1274       }
1275     }
1276     session::set('LOCK_VARS_TO_USE',array());
1277     session::set('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1278   }
1280   /* Prepare and show template */
1281   $smarty= get_smarty();
1282   
1283   if(is_array($dn)){
1284     $msg = "<pre>";
1285     foreach($dn as $sub_dn){
1286       $msg .= "\n".$sub_dn.", ";
1287     }
1288     $msg = preg_replace("/, $/","</pre>",$msg);
1289   }else{
1290     $msg = $dn;
1291   }
1293   $smarty->assign ("dn", $msg);
1294   if ($remove){
1295     $smarty->assign ("action", _("Continue anyway"));
1296   } else {
1297     $smarty->assign ("action", _("Edit anyway"));
1298   }
1299   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1301   return ($smarty->fetch (get_template_path('islocked.tpl')));
1305 function to_string ($value)
1307   /* If this is an array, generate a text blob */
1308   if (is_array($value)){
1309     $ret= "";
1310     foreach ($value as $line){
1311       $ret.= $line."<br>\n";
1312     }
1313     return ($ret);
1314   } else {
1315     return ($value);
1316   }
1320 function get_printer_list()
1322   global $config;
1323   $res = array();
1324   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1325   foreach($data as $attrs ){
1326     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1327   }
1328   return $res;
1332 function show_errors($message)
1334   $complete= "";
1336   /* Assemble the message array to a plain string */
1337   foreach ($message as $error){
1338     if ($complete == ""){
1339       $complete= $error;
1340     } else {
1341       $complete= "$error<br>$complete";
1342     }
1343   }
1345   /* Fill ERROR variable with nice error dialog */
1346   msg_dialog::display(_("Error"), $complete, ERROR_DIALOG);
1350 function show_ldap_error($message, $addon= "")
1352   if (!preg_match("/Success/i", $message)){
1353     if ($addon == ""){
1354       msg_dialog::display(_("LDAP error:"), $message, ERROR_DIALOG);
1355     } else {
1356       if(!preg_match("/No such object/i",$message)){
1357         msg_dialog::display(_("LDAP error"), sprintf(_("Plugin '%s':%s"),"<i>".$addon."</i>", "<br><br>$message"),ERROR_DIALOG);
1358       }
1359     }
1360     return TRUE;
1361   } else {
1362     return FALSE;
1363   }
1367 function rewrite($s)
1369   global $REWRITE;
1371   foreach ($REWRITE as $key => $val){
1372     $s= preg_replace("/$key/", "$val", $s);
1373   }
1375   return ($s);
1379 function dn2base($dn)
1381   global $config;
1383   if (get_people_ou() != ""){
1384     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1385   }
1386   if (get_groups_ou() != ""){
1387     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1388   }
1389   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1391   return ($base);
1396 function check_command($cmdline)
1398   $cmd= preg_replace("/ .*$/", "", $cmdline);
1400   /* Check if command exists in filesystem */
1401   if (!file_exists($cmd)){
1402     return (FALSE);
1403   }
1405   /* Check if command is executable */
1406   if (!is_executable($cmd)){
1407     return (FALSE);
1408   }
1410   return (TRUE);
1414 function print_header($image, $headline, $info= "")
1416   $display= "<div class=\"plugtop\">\n";
1417   $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";
1418   $display.= "</div>\n";
1420   if ($info != ""){
1421     $display.= "<div class=\"pluginfo\">\n";
1422     $display.= "$info";
1423     $display.= "</div>\n";
1424   } else {
1425     $display.= "<div style=\"height:5px;\">\n";
1426     $display.= "&nbsp;";
1427     $display.= "</div>\n";
1428   }
1429   return ($display);
1433 function range_selector($dcnt,$start,$range=25,$post_var=false)
1436   /* Entries shown left and right from the selected entry */
1437   $max_entries= 10;
1439   /* Initialize and take care that max_entries is even */
1440   $output="";
1441   if ($max_entries & 1){
1442     $max_entries++;
1443   }
1445   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1446     $range= $_POST[$post_var];
1447   }
1449   /* Prevent output to start or end out of range */
1450   if ($start < 0 ){
1451     $start= 0 ;
1452   }
1453   if ($start >= $dcnt){
1454     $start= $range * (int)(($dcnt / $range) + 0.5);
1455   }
1457   $numpages= (($dcnt / $range));
1458   if(((int)($numpages))!=($numpages)){
1459     $numpages = (int)$numpages + 1;
1460   }
1461   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1462     return ("");
1463   }
1464   $ppage= (int)(($start / $range) + 0.5);
1467   /* Align selected page to +/- max_entries/2 */
1468   $begin= $ppage - $max_entries/2;
1469   $end= $ppage + $max_entries/2;
1471   /* Adjust begin/end, so that the selected value is somewhere in
1472      the middle and the size is max_entries if possible */
1473   if ($begin < 0){
1474     $end-= $begin + 1;
1475     $begin= 0;
1476   }
1477   if ($end > $numpages) {
1478     $end= $numpages;
1479   }
1480   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1481     $begin= $end - $max_entries;
1482   }
1484   if($post_var){
1485     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1486       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1487   }else{
1488     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1489   }
1491   /* Draw decrement */
1492   if ($start > 0 ) {
1493     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1494       (($start-$range))."\">".
1495       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1496   }
1498   /* Draw pages */
1499   for ($i= $begin; $i < $end; $i++) {
1500     if ($ppage == $i){
1501       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1502         validate($_GET['plug'])."&amp;start=".
1503         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1504     } else {
1505       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1506         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1507     }
1508   }
1510   /* Draw increment */
1511   if($start < ($dcnt-$range)) {
1512     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1513       (($start+($range)))."\">".
1514       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1515   }
1517   if(($post_var)&&($numpages)){
1518     $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()'>";
1519     foreach(array(20,50,100,200,"all") as $num){
1520       if($num == "all"){
1521         $var = 10000;
1522       }else{
1523         $var = $num;
1524       }
1525       if($var == $range){
1526         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1527       }else{  
1528         $output.="\n<option value='".$var."'>".$num."</option>";
1529       }
1530     }
1531     $output.=  "</select></td></tr></table></div>";
1532   }else{
1533     $output.= "</div>";
1534   }
1536   return($output);
1540 function apply_filter()
1542   $apply= "";
1544   $apply= ''.
1545     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1546     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1548   return ($apply);
1552 function back_to_main()
1554   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1555     _("Back").'"></p><input type="hidden" name="ignore">';
1557   return ($string);
1561 function normalize_netmask($netmask)
1563   /* Check for notation of netmask */
1564   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1565     $num= (int)($netmask);
1566     $netmask= "";
1568     for ($byte= 0; $byte<4; $byte++){
1569       $result=0;
1571       for ($i= 7; $i>=0; $i--){
1572         if ($num-- > 0){
1573           $result+= pow(2,$i);
1574         }
1575       }
1577       $netmask.= $result.".";
1578     }
1580     return (preg_replace('/\.$/', '', $netmask));
1581   }
1583   return ($netmask);
1587 function netmask_to_bits($netmask)
1589   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1590   $res= 0;
1592   for ($n= 0; $n<4; $n++){
1593     $start= 255;
1594     $name= "nm$n";
1596     for ($i= 0; $i<8; $i++){
1597       if ($start == (int)($$name)){
1598         $res+= 8 - $i;
1599         break;
1600       }
1601       $start-= pow(2,$i);
1602     }
1603   }
1605   return ($res);
1609 function recurse($rule, $variables)
1611   $result= array();
1613   if (!count($variables)){
1614     return array($rule);
1615   }
1617   reset($variables);
1618   $key= key($variables);
1619   $val= current($variables);
1620   unset ($variables[$key]);
1622   foreach($val as $possibility){
1623     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1624     $result= array_merge($result, recurse($nrule, $variables));
1625   }
1627   return ($result);
1631 function expand_id($rule, $attributes)
1633   /* Check for id rule */
1634   if(preg_match('/^id(:|#)\d+$/',$rule)){
1635     return (array("\{$rule}"));
1636   }
1638   /* Check for clean attribute */
1639   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1640     $rule= preg_replace('/^%/', '', $rule);
1641     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1642     return (array($val));
1643   }
1645   /* Check for attribute with parameters */
1646   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1647     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1648     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1649     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1650     $start= preg_replace ('/-.*$/', '', $param);
1651     $stop = preg_replace ('/^[^-]+-/', '', $param);
1653     /* Assemble results */
1654     $result= array();
1655     for ($i= $start; $i<= $stop; $i++){
1656       $result[]= substr($val, 0, $i);
1657     }
1658     return ($result);
1659   }
1661   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1662   return (array($rule));
1666 function gen_uids($rule, $attributes)
1668   global $config;
1670   /* Search for keys and fill the variables array with all 
1671      possible values for that key. */
1672   $part= "";
1673   $trigger= false;
1674   $stripped= "";
1675   $variables= array();
1677   for ($pos= 0; $pos < strlen($rule); $pos++){
1679     if ($rule[$pos] == "{" ){
1680       $trigger= true;
1681       $part= "";
1682       continue;
1683     }
1685     if ($rule[$pos] == "}" ){
1686       $variables[$pos]= expand_id($part, $attributes);
1687       $stripped.= "{".$pos."}";
1688       $trigger= false;
1689       continue;
1690     }
1692     if ($trigger){
1693       $part.= $rule[$pos];
1694     } else {
1695       $stripped.= $rule[$pos];
1696     }
1697   }
1699   /* Recurse through all possible combinations */
1700   $proposed= recurse($stripped, $variables);
1702   /* Get list of used ID's */
1703   $used= array();
1704   $ldap= $config->get_ldap_link();
1705   $ldap->cd($config->current['BASE']);
1706   $ldap->search('(uid=*)');
1708   while($attrs= $ldap->fetch()){
1709     $used[]= $attrs['uid'][0];
1710   }
1712   /* Remove used uids and watch out for id tags */
1713   $ret= array();
1714   foreach($proposed as $uid){
1716     /* Check for id tag and modify uid if needed */
1717     if(preg_match('/\{id:\d+}/',$uid)){
1718       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1720       for ($i= 0; $i < pow(10,$size); $i++){
1721         $number= sprintf("%0".$size."d", $i);
1722         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1723         if (!in_array($res, $used)){
1724           $uid= $res;
1725           break;
1726         }
1727       }
1728     }
1730   if(preg_match('/\{id#\d+}/',$uid)){
1731     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1733     while (true){
1734       mt_srand((double) microtime()*1000000);
1735       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1736       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1737       if (!in_array($res, $used)){
1738         $uid= $res;
1739         break;
1740       }
1741     }
1742   }
1744 /* Don't assign used ones */
1745 if (!in_array($uid, $used)){
1746   $ret[]= $uid;
1750 return(array_unique($ret));
1754 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1755    Need to convert... */
1756 function to_byte($value) {
1757   $value= strtolower(trim($value));
1759   if(!is_numeric(substr($value, -1))) {
1761     switch(substr($value, -1)) {
1762       case 'g':
1763         $mult= 1073741824;
1764         break;
1765       case 'm':
1766         $mult= 1048576;
1767         break;
1768       case 'k':
1769         $mult= 1024;
1770         break;
1771     }
1773     return ($mult * (int)substr($value, 0, -1));
1774   } else {
1775     return $value;
1776   }
1780 function in_array_ics($value, $items)
1782   if (!is_array($items)){
1783     return (FALSE);
1784   }
1786   foreach ($items as $item){
1787     if (strcasecmp($item, $value) == 0) {
1788       return (TRUE);
1789     }
1790   }
1792   return (FALSE);
1793
1796 function generate_alphabet($count= 10)
1798   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1799   $alphabet= "";
1800   $c= 0;
1802   /* Fill cells with charaters */
1803   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1804     if ($c == 0){
1805       $alphabet.= "<tr>";
1806     }
1808     $ch = mb_substr($characters, $i, 1, "UTF8");
1809     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1810       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1812     if ($c++ == $count){
1813       $alphabet.= "</tr>";
1814       $c= 0;
1815     }
1816   }
1818   /* Fill remaining cells */
1819   while ($c++ <= $count){
1820     $alphabet.= "<td>&nbsp;</td>";
1821   }
1823   return ($alphabet);
1827 function validate($string)
1829   return (strip_tags(preg_replace('/\0/', '', $string)));
1833 function get_gosa_version()
1835   global $svn_revision, $svn_path;
1837   /* Extract informations */
1838   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1840   /* Release or development? */
1841   if (preg_match('%/gosa/trunk/%', $svn_path)){
1842     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1843   } else {
1844     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1845     return (sprintf(_("GOsa $release"), $revision));
1846   }
1850 function rmdirRecursive($path, $followLinks=false) {
1851   $dir= opendir($path);
1852   while($entry= readdir($dir)) {
1853     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1854       unlink($path."/".$entry);
1855     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1856       rmdirRecursive($path."/".$entry);
1857     }
1858   }
1859   closedir($dir);
1860   return rmdir($path);
1864 function scan_directory($path,$sort_desc=false)
1866   $ret = false;
1868   /* is this a dir ? */
1869   if(is_dir($path)) {
1871     /* is this path a readable one */
1872     if(is_readable($path)){
1874       /* Get contents and write it into an array */   
1875       $ret = array();    
1877       $dir = opendir($path);
1879       /* Is this a correct result ?*/
1880       if($dir){
1881         while($fp = readdir($dir))
1882           $ret[]= $fp;
1883       }
1884     }
1885   }
1886   /* Sort array ascending , like scandir */
1887   sort($ret);
1889   /* Sort descending if parameter is sort_desc is set */
1890   if($sort_desc) {
1891     $ret = array_reverse($ret);
1892   }
1894   return($ret);
1898 function clean_smarty_compile_dir($directory)
1900   global $svn_revision;
1902   if(is_dir($directory) && is_readable($directory)) {
1903     // Set revision filename to REVISION
1904     $revision_file= $directory."/REVISION";
1906     /* Is there a stamp containing the current revision? */
1907     if(!file_exists($revision_file)) {
1908       // create revision file
1909       create_revision($revision_file, $svn_revision);
1910     } else {
1911       # check for "$config->...['CONFIG']/revision" and the
1912       # contents should match the revision number
1913       if(!compare_revision($revision_file, $svn_revision)){
1914         // If revision differs, clean compile directory
1915         foreach(scan_directory($directory) as $file) {
1916           if(($file==".")||($file=="..")) continue;
1917           if( is_file($directory."/".$file) &&
1918               is_writable($directory."/".$file)) {
1919             // delete file
1920             if(!unlink($directory."/".$file)) {
1921               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1922               // This should never be reached
1923             }
1924           } elseif(is_dir($directory."/".$file) &&
1925               is_writable($directory."/".$file)) {
1926             // Just recursively delete it
1927             rmdirRecursive($directory."/".$file);
1928           }
1929         }
1930         // We should now create a fresh revision file
1931         clean_smarty_compile_dir($directory);
1932       } else {
1933         // Revision matches, nothing to do
1934       }
1935     }
1936   } else {
1937     // Smarty compile dir is not accessible
1938     // (Smarty will warn about this)
1939   }
1943 function create_revision($revision_file, $revision)
1945   $result= false;
1947   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1948     if($fh= fopen($revision_file, "w")) {
1949       if(fwrite($fh, $revision)) {
1950         $result= true;
1951       }
1952     }
1953     fclose($fh);
1954   } else {
1955     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1956   }
1958   return $result;
1962 function compare_revision($revision_file, $revision)
1964   // false means revision differs
1965   $result= false;
1967   if(file_exists($revision_file) && is_readable($revision_file)) {
1968     // Open file
1969     if($fh= fopen($revision_file, "r")) {
1970       // Compare File contents with current revision
1971       if($revision == fread($fh, filesize($revision_file))) {
1972         $result= true;
1973       }
1974     } else {
1975       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1976     }
1977     // Close file
1978     fclose($fh);
1979   }
1981   return $result;
1985 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1987   $str = ""; // Our return value will be saved in this var
1989   $color  = dechex($percentage+150);
1990   $color2 = dechex(150 - $percentage);
1991   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1993   $progress = (int)(($percentage /100)*$width);
1995   /* Abort printing out percentage, if divs are to small */
1998   /* If theres a better solution for this, use it... */
1999   $str = "
2000     <div style=\" width:".($width)."px; 
2001     height:".($height)."px;
2002   background-color:#000000;
2003 padding:1px;\">
2005           <div style=\" width:".($width)."px;
2006         background-color:#$bgcolor;
2007 height:".($height)."px;\">
2009          <div style=\" width:".$progress."px;
2010 height:".$height."px;
2011        background-color:#".$color2.$color2.$color."; \">";
2014        if(($height >10)&&($showvalue)){
2015          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2016            <b>".$percentage."%</b>
2017            </font>";
2018        }
2020        $str.= "</div></div></div>";
2022        return($str);
2026 function array_key_ics($ikey, $items)
2028   /* Gather keys, make them lowercase */
2029   $tmp= array();
2030   foreach ($items as $key => $value){
2031     $tmp[strtolower($key)]= $key;
2032   }
2034   if (isset($tmp[strtolower($ikey)])){
2035     return($tmp[strtolower($ikey)]);
2036   }
2038   return ("");
2042 function array_differs($src, $dst)
2044   /* If the count is differing, the arrays differ */
2045   if (count ($src) != count ($dst)){
2046     return (TRUE);
2047   }
2049   /* So the count is the same - lets check the contents */
2050   $differs= FALSE;
2051   foreach($src as $value){
2052     if (!in_array($value, $dst)){
2053       $differs= TRUE;
2054     }
2055   }
2057   return ($differs);
2061 function saveFilter($a_filter, $values)
2063   if (isset($_POST['regexit'])){
2064     $a_filter["regex"]= $_POST['regexit'];
2066     foreach($values as $type){
2067       if (isset($_POST[$type])) {
2068         $a_filter[$type]= "checked";
2069       } else {
2070         $a_filter[$type]= "";
2071       }
2072     }
2073   }
2075   /* React on alphabet links if needed */
2076   if (isset($_GET['search'])){
2077     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2078     if ($s == "**"){
2079       $s= "*";
2080     }
2081     $a_filter['regex']= $s;
2082   }
2084   return ($a_filter);
2088 /* Escape all preg_* relevant characters */
2089 function normalizePreg($input)
2091   return (addcslashes($input, '[]()|/.*+-'));
2095 /* Escape all LDAP filter relevant characters */
2096 function normalizeLdap($input)
2098   return (addcslashes($input, '()|'));
2102 /* Resturns the difference between to microtime() results in float  */
2103 function get_MicroTimeDiff($start , $stop)
2105   $a = split("\ ",$start);
2106   $b = split("\ ",$stop);
2108   $secs = $b[1] - $a[1];
2109   $msecs= $b[0] - $a[0]; 
2111   $ret = (float) ($secs+ $msecs);
2112   return($ret);
2116 function get_base_dir()
2118   global $BASE_DIR;
2120   return $BASE_DIR;
2124 function obj_is_readable($dn, $object, $attribute)
2126   global $ui;
2128   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2132 function obj_is_writable($dn, $object, $attribute)
2134   global $ui;
2136   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2140 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2142   /* Initialize variables */
2143   $ret  = array("count" => 0);  // Set count to 0
2144   $next = true;                 // if false, then skip next loops and return
2145   $cnt  = 0;                    // Current number of loops
2146   $max  = 100;                  // Just for security, prevent looops
2147   $ldap = NULL;                 // To check if created result a valid
2148   $keep = "";                   // save last failed parse string
2150   /* Check each parsed dn in ldap ? */
2151   if($config!==NULL && $verify_in_ldap){
2152     $ldap = $config->get_ldap_link();
2153   }
2155   /* Lets start */
2156   $called = false;
2157   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2159     $cnt ++;
2160     if(!preg_match("/,/",$dn)){
2161       $next = false;
2162     }
2163     $object = preg_replace("/[,].*$/","",$dn);
2164     $dn     = preg_replace("/^[^,]+,/","",$dn);
2166     $called = true;
2168     /* Check if current dn is valid */
2169     if($ldap!==NULL){
2170       $ldap->cd($dn);
2171       $ldap->cat($dn,array("dn"));
2172       if($ldap->count()){
2173         $ret[]  = $keep.$object;
2174         $keep   = "";
2175       }else{
2176         $keep  .= $object.",";
2177       }
2178     }else{
2179       $ret[]  = $keep.$object;
2180       $keep   = "";
2181     }
2182   }
2184   /* No dn was posted */
2185   if($cnt == 0 && !empty($dn)){
2186     $ret[] = $dn;
2187   }
2189   /* Append the rest */
2190   $test = $keep.$dn;
2191   if($called && !empty($test)){
2192     $ret[] = $keep.$dn;
2193   }
2194   $ret['count'] = count($ret) - 1;
2196   return($ret);
2200 function get_base_from_hook($dn, $attrib)
2202   global $config;
2204   if (isset($config->current['BASE_HOOK'])){
2205     
2206     /* Call hook script - if present */
2207     $command= $config->current['BASE_HOOK'];
2209     if ($command != ""){
2210       $command.= " '".LDAP::fix($dn)."' $attrib";
2211       if (check_command($command)){
2212         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2213         exec($command, $output);
2214         if (preg_match("/^[0-9]+$/", $output[0])){
2215           return ($output[0]);
2216         } else {
2217           msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2218           return ($config->current['UIDBASE']);
2219         }
2220       } else {
2221         msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2222         return ($config->current['UIDBASE']);
2223       }
2225     } else {
2227       msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2228       return ($config->current['UIDBASE']);
2230     }
2231   }
2235 function check_schema_version($class, $version)
2237   return preg_match("/\(v$version\)/", $class['DESC']);
2241 function check_schema($cfg,$rfc2307bis = FALSE)
2243   $messages= array();
2245   /* Get objectclasses */
2246   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2247   $objectclasses = $ldap->get_objectclasses();
2248   if(count($objectclasses) == 0){
2249     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2250   }
2252   /* This is the default block used for each entry.
2253    *  to avoid unset indexes.
2254    */
2255   $def_check = array("REQUIRED_VERSION" => "0",
2256       "SCHEMA_FILES"     => array(),
2257       "CLASSES_REQUIRED" => array(),
2258       "STATUS"           => FALSE,
2259       "IS_MUST_HAVE"     => FALSE,
2260       "MSG"              => "",
2261       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2263   /* The gosa base schema */
2264   $checks['gosaObject'] = $def_check;
2265   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2266   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2267   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2268   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2270   /* GOsa Account class */
2271   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2272   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2273   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2274   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2275   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2277   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2278   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2279   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2280   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2281   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2282   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2284   /* Some other checks */
2285   foreach(array(
2286         "gosaCacheEntry"        => array("version" => "2.4"),
2287         "gosaDepartment"        => array("version" => "2.4"),
2288         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2289         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2290         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2291         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2292         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2293         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2294         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2295         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2296         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2297         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2298         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2299         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2300         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2301         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2302         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2303         "goLdapServer"          => array("version" => "2.4"),
2304         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2305         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2306         "goKrbServer"           => array("version" => "2.4"),
2307         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2308         ) as $name => $values){
2310           $checks[$name] = $def_check;
2311           if(isset($values['version'])){
2312             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2313           }
2314           if(isset($values['file'])){
2315             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2316           }
2317           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2318         }
2319   foreach($checks as $name => $value){
2320     foreach($value['CLASSES_REQUIRED'] as $class){
2322       if(!isset($objectclasses[$name])){
2323         $checks[$name]['STATUS'] = FALSE;
2324         if($value['IS_MUST_HAVE']){
2325           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2326         }else{
2327           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2328         }
2329       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2330         $checks[$name]['STATUS'] = FALSE;
2332         if($value['IS_MUST_HAVE']){
2333           $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2334         }else{
2335           $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2336         }
2337       }else{
2338         $checks[$name]['STATUS'] = TRUE;
2339         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2340       }
2341     }
2342   }
2344   $tmp = $objectclasses;
2346   /* The gosa base schema */
2347   $checks['posixGroup'] = $def_check;
2348   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2349   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2350   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2351   $checks['posixGroup']['STATUS']           = TRUE;
2352   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2353   $checks['posixGroup']['MSG']              = "";
2354   $checks['posixGroup']['INFO']             = "";
2356   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2357   if(isset($tmp['posixGroup'])){
2359     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2360       $checks['posixGroup']['STATUS']           = FALSE;
2361       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2362       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2363     }
2364     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2365       $checks['posixGroup']['STATUS']           = FALSE;
2366       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2367       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2368     }
2369   }
2371   return($checks);
2375 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2377   $tmp = array(
2378         "de_DE" => "German",
2379         "fr_FR" => "French",
2380         "it_IT" => "Italian",
2381         "es_ES" => "Spanish",
2382         "en_US" => "English",
2383         "nl_NL" => "Dutch",
2384         "pl_PL" => "Polish",
2385         "sv_SE" => "Swedish",
2386         "zh_CN" => "Chinese",
2387         "ru_RU" => "Russian");
2388   
2389   $tmp2= array(
2390         "de_DE" => _("German"),
2391         "fr_FR" => _("French"),
2392         "it_IT" => _("Italian"),
2393         "es_ES" => _("Spanish"),
2394         "en_US" => _("English"),
2395         "nl_NL" => _("Dutch"),
2396         "pl_PL" => _("Polish"),
2397         "sv_SE" => _("Swedish"),
2398         "zh_CN" => _("Chinese"),
2399         "ru_RU" => _("Russian"));
2401   $ret = array();
2402   if($languages_in_own_language){
2404     $old_lang = setlocale(LC_ALL, 0);
2405     foreach($tmp as $key => $name){
2406       $lang = $key.".UTF-8";
2407       setlocale(LC_ALL, $lang);
2408       if($strip_region_tag){
2409         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2410       }else{
2411         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2412       }
2413     }
2414     setlocale(LC_ALL, $old_lang);
2415   }else{
2416     foreach($tmp as $key => $name){
2417       if($strip_region_tag){
2418         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2419       }else{
2420         $ret[$key] = _($name);
2421       }
2422     }
2423   }
2424   return($ret);
2428 /* Returns contents of the given POST variable and check magic quotes settings */
2429 function get_post($name)
2431   if(!isset($_POST[$name])){
2432     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2433     return(FALSE);
2434   }
2435   if(get_magic_quotes_gpc()){
2436     return(stripcslashes($_POST[$name]));
2437   }else{
2438     return($_POST[$name]);
2439   }
2443 /* Return class name in correct case */
2444 function get_correct_class_name($cls)
2446   global $class_mapping;
2447   if(isset($class_mapping) && is_array($class_mapping)){
2448     foreach($class_mapping as $class => $file){
2449       if(preg_match("/^".$cls."$/i",$class)){
2450         return($class);
2451       }
2452     }
2453   }
2454   return(FALSE);
2458 // change_password, changes the Password, of the given dn
2459 function change_password ($dn, $password, $mode=0, $hash= "")
2461   global $config;
2462   $newpass= "";
2464   /* Convert to lower. Methods are lowercase */
2465   $hash= strtolower($hash);
2467   // Get all available encryption Methods
2469   // NON STATIC CALL :)
2470   $tmp = new passwordMethod(session::get('config'));
2471   $available = $tmp->get_available_methods();
2473   // read current password entry for $dn, to detect the encryption Method
2474   $ldap       = $config->get_ldap_link();
2475   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2476   $attrs      = $ldap->fetch ();
2478   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2479   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2480     $deactivated = TRUE;
2481   }else{
2482     $deactivated = FALSE;
2483   }
2485   /* Is ensure that clear passwords will stay clear */
2486   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2487     $hash = "clear";
2488   }
2490   // Detect the encryption Method
2491   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2493     /* Check for supported algorithm */
2494     mt_srand((double) microtime()*1000000);
2496     /* Extract used hash */
2497     if ($hash == ""){
2498       $hash= strtolower($matches[1]);
2499     }
2501     $test = new  $available[$hash]($config);
2503   } else {
2504     // User MD5 by default
2505     $hash= "md5";
2506     $test = new  $available['md5']($config);
2507   }
2509   /* Feed password backends with information */
2510   $test->dn= $dn;
2511   $test->attrs= $attrs;
2512   $newpass= $test->generate_hash($password);
2514   // Update shadow timestamp?
2515   if (isset($attrs["shadowLastChange"][0])){
2516     $shadow= (int)(date("U") / 86400);
2517   } else {
2518     $shadow= 0;
2519   }
2521   // Write back modified entry
2522   $ldap->cd($dn);
2523   $attrs= array();
2525   // Not for groups
2526   if ($mode == 0){
2528     if ($shadow != 0){
2529       $attrs['shadowLastChange']= $shadow;
2530     }
2532     // Create SMB Password
2533     $attrs= generate_smb_nt_hash($password);
2534   }
2536  /* Readd ! if user was deactivated */
2537   if($deactivated){
2538     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2539   }
2541   $attrs['userPassword']= array();
2542   $attrs['userPassword']= $newpass;
2544   $ldap->modify($attrs);
2546   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2548   if ($ldap->error != 'Success') {
2549     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);
2550   } else {
2552     /* Run backend method for change/create */
2553     $test->set_password($password);
2555     /* Find postmodify entries for this class */
2556     $command= $config->search("password", "POSTMODIFY",array('menu'));
2558     if ($command != ""){
2559       /* Walk through attribute list */
2560       $command= preg_replace("/%userPassword/", $password, $command);
2561       $command= preg_replace("/%dn/", $dn, $command);
2563       if (check_command($command)){
2564         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2565         exec($command);
2566       } else {
2567         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2568         msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2569       }
2570     }
2571   }
2575 // Return something like array['sambaLMPassword']= "lalla..."
2576 function generate_smb_nt_hash($password)
2578   global $config;
2580   # Try to use gosa-si?
2581   if (isset($config->current['GOSA_SI'])){
2582         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2583         $hash= $res['XML']['HASH'];
2584   } else {
2585           $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2586           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2588           exec($tmp, $ar);
2589           flush();
2590           reset($ar);
2591           $hash= current($ar);
2592   }
2594   if ($hash == "") {
2595           msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2596           return ("");
2597   }
2599   list($lm,$nt)= split (":", trim($hash));
2601   if ($config->current['SAMBAVERSION'] == 3) {
2602           $attrs['sambaLMPassword']= $lm;
2603           $attrs['sambaNTPassword']= $nt;
2604           $attrs['sambaPwdLastSet']= date('U');
2605           $attrs['sambaBadPasswordCount']= "0";
2606           $attrs['sambaBadPasswordTime']= "0";
2607   } else {
2608           $attrs['lmPassword']= $lm;
2609           $attrs['ntPassword']= $nt;
2610           $attrs['pwdLastSet']= date('U');
2611   }
2612   return($attrs);
2616 function crypt_single($string,$enc_type )
2618   return( passwordMethod::crypt_single_str($string,$enc_type));
2622 function getEntryCSN($dn)
2624   global $config;
2625   if(empty($dn) || !is_object($config)){
2626     return("");
2627   }
2629   /* Get attribute that we should use as serial number */
2630   if(isset($config->current['UNIQ_IDENTIFIER'])){
2631     $attr = $config->current['UNIQ_IDENTIFIER'];
2632   }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2633     $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2634   }
2635   if(!empty($attr)){
2636     $ldap = $config->get_ldap_link();
2637     $ldap->cat($dn,array($attr));
2638     $csn = $ldap->fetch();
2639     if(isset($csn[$attr][0])){
2640       return($csn[$attr][0]);
2641     }
2642   }
2643   return("");
2647 /* Add a given objectClass to an attrs entry */
2648 function add_objectClass($classes, &$attrs)
2650   if (is_array($classes)){
2651     $list= $classes;
2652   } else {
2653     $list= array($classes);
2654   }
2656   foreach ($list as $class){
2657     $attrs['objectClass'][]= $class;
2658   }
2662 /* Removes a given objectClass from the attrs entry */
2663 function remove_objectClass($classes, &$attrs)
2665   if (isset($attrs['objectClass'])){
2666     /* Array? */
2667     if (is_array($classes)){
2668       $list= $classes;
2669     } else {
2670       $list= array($classes);
2671     }
2673     $tmp= array();
2674     foreach ($attrs['objectClass'] as $oc) {
2675       foreach ($list as $class){
2676         if ($oc != $class){
2677           $tmp[]= $oc;
2678         }
2679       }
2680     }
2681     $attrs['objectClass']= $tmp;
2682   }
2685 /*! \brief  Initialize a file download with given content, name and data type. 
2686  *  @param  data  String The content to send.
2687  *  @param  name  String The name of the file.
2688  *  @param  type  String The content identifier, default value is "application/octet-stream";
2689  */
2690 function send_binary_content($data,$name,$type = "application/octet-stream")
2692   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2693   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2694   header("Cache-Control: no-cache");
2695   header("Pragma: no-cache");
2696   header("Cache-Control: post-check=0, pre-check=0");
2697   header("Content-type: ".$type."");
2699   /* force download dialog */
2700   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2701     header('Content-Disposition: filename="'.$name.'"');
2702   } else {
2703     header('Content-Disposition: attachment; filename="'.$name.'"');
2704   }
2706   echo $data;
2707   exit();
2710 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2711 ?>