Code

Updated gosaSupportDaemon
[gosa.git] / gosa-core / include / functions.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 /* Configuration file location */
24 define ("CONFIG_DIR", "/etc/gosa");
25 define ("CONFIG_FILE", "gosa.conf-trunk");
26 define ("CONFIG_TEMPLATE_DIR", "../contrib/");
27 define ("HELP_BASEDIR", "/var/www/doc/");
29 /* Define get_list flags */
30 define("GL_NONE",         0);
31 define("GL_SUBSEARCH",    1);
32 define("GL_SIZELIMIT",    2);
33 define("GL_CONVERT",      4);
34 define("GL_NO_ACL_CHECK", 8);
36 /* Heimdal stuff */
37 define('UNIVERSAL',0x00);
38 define('INTEGER',0x02);
39 define('OCTET_STRING',0x04);
40 define('OBJECT_IDENTIFIER ',0x06);
41 define('SEQUENCE',0x10);
42 define('SEQUENCE_OF',0x10);
43 define('SET',0x11);
44 define('SET_OF',0x11);
45 define('DEBUG',false);
46 define('HDB_KU_MKEY',0x484442);
47 define('TWO_BIT_SHIFTS',0x7efc);
48 define('DES_CBC_CRC',1);
49 define('DES_CBC_MD4',2);
50 define('DES_CBC_MD5',3);
51 define('DES3_CBC_MD5',5);
52 define('DES3_CBC_SHA1',16);
54 /* Define globals for revision comparing */
55 $svn_path = '$HeadURL: https://oss.gonicus.de/repositories/gosa/trunk/gosa-core/include/functions.inc $';
56 $svn_revision = '$Revision: 9246 $';
58 /* Include required files */
59 require_once("class_location.inc");
60 require_once ("functions_debug.inc");
61 require_once ("accept-to-gettext.inc");
63 /* Define constants for debugging */
64 define ("DEBUG_TRACE",   1);
65 define ("DEBUG_LDAP",    2);
66 define ("DEBUG_MYSQL",   4);
67 define ("DEBUG_SHELL",   8);
68 define ("DEBUG_POST",   16);
69 define ("DEBUG_SESSION",32);
70 define ("DEBUG_CONFIG", 64);
71 define ("DEBUG_ACL",    128);
73 /* Rewrite german 'umlauts' and spanish 'accents'
74    to get better results */
75 $REWRITE= array( "ä" => "ae",
76     "ö" => "oe",
77     "ü" => "ue",
78     "Ä" => "Ae",
79     "Ö" => "Oe",
80     "Ü" => "Ue",
81     "ß" => "ss",
82     "á" => "a",
83     "é" => "e",
84     "í" => "i",
85     "ó" => "o",
86     "ú" => "u",
87     "Á" => "A",
88     "É" => "E",
89     "Í" => "I",
90     "Ó" => "O",
91     "Ú" => "U",
92     "ñ" => "ny",
93     "Ñ" => "Ny" );
96 /* Class autoloader */
97 function __autoload($class_name) {
98     global $class_mapping, $BASE_DIR;
100     if ($class_mapping === NULL){
101             echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
102             exit;
103     }
105     if (isset($class_mapping[$class_name])){
106       require_once($BASE_DIR."/".$class_mapping[$class_name]);
107     } else {
108       echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
109       exit;
110     }
114 /*! \brief Checks if a class is available. 
115  *  @param  name String  The class name.
116  *  @return boolean      True if class is available, else false.
117  */
118 function class_available($name)
120   global $class_mapping;
121   return(isset($class_mapping[$name]));
125 /* Check if plugin is avaliable */
126 function plugin_available($plugin)
128         global $class_mapping, $BASE_DIR;
130         if (!isset($class_mapping[$plugin])){
131                 return false;
132         } else {
133                 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
134         }
138 /* Create seed with microseconds */
139 function make_seed() {
140   list($usec, $sec) = explode(' ', microtime());
141   return (float) $sec + ((float) $usec * 100000);
145 /* Debug level action */
146 function DEBUG($level, $line, $function, $file, $data, $info="")
148   if (session::get('DEBUGLEVEL') & $level){
149     $output= "DEBUG[$level] ";
150     if ($function != ""){
151       $output.= "($file:$function():$line) - $info: ";
152     } else {
153       $output.= "($file:$line) - $info: ";
154     }
155     echo $output;
156     if (is_array($data)){
157       print_a($data);
158     } else {
159       echo "'$data'";
160     }
161     echo "<br>";
162   }
166 function get_browser_language()
168   /* Try to use users primary language */
169   global $config;
170   $ui= get_userinfo();
171   if (isset($ui) && $ui !== NULL){
172     if ($ui->language != ""){
173       return ($ui->language.".UTF-8");
174     }
175   }
177   /* Check for global language settings in gosa.conf */
178   if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
179     $lang = $config->data['MAIN']['LANG'];
180     if(!preg_match("/utf/i",$lang)){
181       $lang .= ".UTF-8";
182     }
183     return($lang);
184   }
185  
186   /* Load supported languages */
187   $gosa_languages= get_languages();
189   /* Move supported languages to flat list */
190   $langs= array();
191   foreach($gosa_languages as $lang => $dummy){
192     $langs[]= $lang.'.UTF-8';
193   }
195   /* Return gettext based string */
196   return (al2gt($langs, 'text/html'));
200 /* Rewrite ui object to another dn */
201 function change_ui_dn($dn, $newdn)
203   $ui= session::get('ui');
204   if ($ui->dn == $dn){
205     $ui->dn= $newdn;
206     session::set('ui',$ui);
207   }
211 /* Return theme path for specified file */
212 function get_template_path($filename= '', $plugin= FALSE, $path= "")
214   global $config, $BASE_DIR;
216   if (!@isset($config->data['MAIN']['THEME'])){
217     $theme= 'default';
218   } else {
219     $theme= $config->data['MAIN']['THEME'];
220   }
222   /* Return path for empty filename */
223   if ($filename == ''){
224     return ("themes/$theme/");
225   }
227   /* Return plugin dir or root directory? */
228   if ($plugin){
229     if ($path == ""){
230       $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
231     } else {
232       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
233     }
234     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
235       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
236     }
237     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
238       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
239     }
240     if ($path == ""){
241       return (session::get('plugin_dir')."/$filename");
242     } else {
243       return ($path."/$filename");
244     }
245   } else {
246     if (file_exists("themes/$theme/$filename")){
247       return ("themes/$theme/$filename");
248     }
249     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
250       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
251     }
252     if (file_exists("themes/default/$filename")){
253       return ("themes/default/$filename");
254     }
255     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
256       return ("$BASE_DIR/ihtml/themes/default/$filename");
257     }
258     return ($filename);
259   }
263 function array_remove_entries($needles, $haystack)
265   $tmp= array();
267   /* Loop through entries to be removed */
268   foreach ($haystack as $entry){
269     if (!in_array($entry, $needles)){
270       $tmp[]= $entry;
271     }
272   }
274   return ($tmp);
278 function gosa_array_merge($ar1,$ar2)
280   if(!is_array($ar1) || !is_array($ar2)){
281     trigger_error("Specified parameter(s) are not valid arrays.");
282   }else{
283     return(array_values(array_unique(array_merge($ar1,$ar2))));
284   }
288 function gosa_log ($message)
290   global $ui;
292   /* Preset to something reasonable */
293   $username= " unauthenticated";
295   /* Replace username if object is present */
296   if (isset($ui)){
297     if ($ui->username != ""){
298       $username= "[$ui->username]";
299     } else {
300       $username= "unknown";
301     }
302   }
304   syslog(LOG_INFO,"GOsa$username: $message");
308 function ldap_init ($server, $base, $binddn='', $pass='')
310   global $config;
312   $ldap = new LDAP ($binddn, $pass, $server,
313       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
314       isset($config->current['TLS']) && $config->current['TLS'] == "true");
316   /* Sadly we've no proper return values here. Use the error message instead. */
317   if (!preg_match("/Success/i", $ldap->error)){
318     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
319     exit();
320   }
322   /* Preset connection base to $base and return to caller */
323   $ldap->cd ($base);
324   return $ldap;
328 function process_htaccess ($username, $kerberos= FALSE)
330   global $config;
332   /* Search for $username and optional @REALM in all configured LDAP trees */
333   foreach($config->data["LOCATIONS"] as $name => $data){
334   
335     $config->set_current($name);
336     $mode= "kerberos";
337     if (isset($config->current['KRBSASL']) && preg_match('/^true$/i', $config->current['KRBSASL'])){
338       $mode= "sasl";
339     }
341     /* Look for entry or realm */
342     $ldap= $config->get_ldap_link();
343     if (!preg_match("/Success/i", $ldap->error)){
344       msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
345       $smarty= get_smarty();
346       $smarty->display(get_template_path('headers.tpl'));
347       echo "<body>".session::get('errors')."</body></html>";
348       exit();
349     }
350     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
352     /* Found a uniq match? Return it... */
353     if ($ldap->count() == 1) {
354       $attrs= $ldap->fetch();
355       return array("username" => $attrs["uid"][0], "server" => $name);
356     }
357   }
359   /* Nothing found? Return emtpy array */
360   return array("username" => "", "server" => "");
364 function ldap_login_user_htaccess ($username)
366   global $config;
368   /* Look for entry or realm */
369   $ldap= $config->get_ldap_link();
370   if (!preg_match("/Success/i", $ldap->error)){
371     msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), FATAL_ERROR_DIALOG);
372     $smarty= get_smarty();
373     $smarty->display(get_template_path('headers.tpl'));
374     echo "<body>".session::get('errors')."</body></html>";
375     exit();
376   }
377   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
378   /* Found no uniq match? Strange, because we did above... */
379   if ($ldap->count() != 1) {
380     msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
381     return (NULL);
382   }
383   $attrs= $ldap->fetch();
385   /* got user dn, fill acl's */
386   $ui= new userinfo($config, $ldap->getDN());
387   $ui->username= $attrs['uid'][0];
389   /* No password check needed - the webserver did it for us */
390   $ldap->disconnect();
392   /* Username is set, load subtreeACL's now */
393   $ui->loadACL();
395   /* TODO: check java script for htaccess authentication */
396   session::set('js',true);
398   return ($ui);
402 function ldap_login_user ($username, $password)
404   global $config;
406   /* look through the entire ldap */
407   $ldap = $config->get_ldap_link();
408   if (!preg_match("/Success/i", $ldap->error)){
409     msg_dialog::display(_("LDAP error"), sprintf(_("User login failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), FATAL_ERROR_DIALOG);
410     $smarty= get_smarty();
411     $smarty->display(get_template_path('headers.tpl'));
412     echo "<body>".session::get('errors')."</body></html>";
413     exit();
414   }
415   $ldap->cd($config->current['BASE']);
416   $allowed_attributes = array("uid","mail");
417   $verify_attr = array();
418   if(isset($config->current['LOGIN_ATTRIBUTE'])){
419     $tmp = split(",",$config->current['LOGIN_ATTRIBUTE']); 
420     foreach($tmp as $attr){
421       if(in_array($attr,$allowed_attributes)){
422         $verify_attr[] = $attr;
423       }
424     }
425   }
426   if(count($verify_attr) == 0){
427     $verify_attr = array("uid");
428   }
429   $tmp= $verify_attr;
430   $tmp[] = "uid";
431   $filter = "";
432   foreach($verify_attr as $attr) {
433     $filter.= "(".$attr."=".$username.")";
434   }
435   $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
436   $ldap->search($filter,$tmp);
438   /* get results, only a count of 1 is valid */
439   switch ($ldap->count()){
441     /* user not found */
442     case 0:     return (NULL);
444             /* valid uniq user */
445     case 1: 
446             break;
448             /* found more than one matching id */
449     default:
450             msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
451             return (NULL);
452   }
454   /* LDAP schema is not case sensitive. Perform additional check. */
455   $attrs= $ldap->fetch();
456   $success = FALSE;
457   foreach($verify_attr as $attr){
458     if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
459       $success = TRUE;
460     }
461   }
462   if(!$success){
463     return(FALSE);
464   }
466   /* got user dn, fill acl's */
467   $ui= new userinfo($config, $ldap->getDN());
468   $ui->username= $attrs['uid'][0];
470   /* password check, bind as user with supplied password  */
471   $ldap->disconnect();
472   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
473       isset($config->current['RECURSIVE']) &&
474       $config->current['RECURSIVE'] == "true",
475       isset($config->current['TLS'])
476       && $config->current['TLS'] == "true");
477   if (!preg_match("/Success/i", $ldap->error)){
478     return (NULL);
479   }
481   /* Username is set, load subtreeACL's now */
482   $ui->loadACL();
484   return ($ui);
488 function ldap_expired_account($config, $userdn, $username)
490     $ldap= $config->get_ldap_link();
491     $ldap->cat($userdn);
492     $attrs= $ldap->fetch();
493     
494     /* default value no errors */
495     $expired = 0;
496     
497     $sExpire = 0;
498     $sLastChange = 0;
499     $sMax = 0;
500     $sMin = 0;
501     $sInactive = 0;
502     $sWarning = 0;
503     
504     $current= date("U");
505     
506     $current= floor($current /60 /60 /24);
507     
508     /* special case of the admin, should never been locked */
509     /* FIXME should allow any name as user admin */
510     if($username != "admin")
511     {
513       if(isset($attrs['shadowExpire'][0])){
514         $sExpire= $attrs['shadowExpire'][0];
515       } else {
516         $sExpire = 0;
517       }
518       
519       if(isset($attrs['shadowLastChange'][0])){
520         $sLastChange= $attrs['shadowLastChange'][0];
521       } else {
522         $sLastChange = 0;
523       }
524       
525       if(isset($attrs['shadowMax'][0])){
526         $sMax= $attrs['shadowMax'][0];
527       } else {
528         $smax = 0;
529       }
531       if(isset($attrs['shadowMin'][0])){
532         $sMin= $attrs['shadowMin'][0];
533       } else {
534         $sMin = 0;
535       }
536       
537       if(isset($attrs['shadowInactive'][0])){
538         $sInactive= $attrs['shadowInactive'][0];
539       } else {
540         $sInactive = 0;
541       }
542       
543       if(isset($attrs['shadowWarning'][0])){
544         $sWarning= $attrs['shadowWarning'][0];
545       } else {
546         $sWarning = 0;
547       }
548       
549       /* is the account locked */
550       /* shadowExpire + shadowInactive (option) */
551       if($sExpire >0){
552         if($current >= ($sExpire+$sInactive)){
553           return(1);
554         }
555       }
556     
557       /* the user should be warned to change is password */
558       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
559         if (($sExpire - $current) < $sWarning){
560           return(2);
561         }
562       }
563       
564       /* force user to change password */
565       if(($sLastChange >0) && ($sMax) >0){
566         if($current >= ($sLastChange+$sMax)){
567           return(3);
568         }
569       }
570       
571       /* the user should not be able to change is password */
572       if(($sLastChange >0) && ($sMin >0)){
573         if (($sLastChange + $sMin) >= $current){
574           return(4);
575         }
576       }
577     }
578    return($expired);
582 function add_lock ($object, $user)
584   global $config;
586   if(is_array($object)){
587     foreach($object as $obj){
588       add_lock($obj,$user);
589     }
590     return;
591   }
593   /* Just a sanity check... */
594   if ($object == "" || $user == ""){
595     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
596     return;
597   }
599   /* Check for existing entries in lock area */
600   $ldap= $config->get_ldap_link();
601   $ldap->cd ($config->current['CONFIG']);
602   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
603       array("gosaUser"));
604   if (!preg_match("/Success/i", $ldap->error)){
605     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);
606     return;
607   }
609   /* Add lock if none present */
610   if ($ldap->count() == 0){
611     $attrs= array();
612     $name= md5($object);
613     $ldap->cd("cn=$name,".$config->current['CONFIG']);
614     $attrs["objectClass"] = "gosaLockEntry";
615     $attrs["gosaUser"] = $user;
616     $attrs["gosaObject"] = base64_encode($object);
617     $attrs["cn"] = "$name";
618     $ldap->add($attrs);
619     if (!preg_match("/Success/i", $ldap->error)){
620       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);
621       return;
622     }
623   }
627 function del_lock ($object)
629   global $config;
631   if(is_array($object)){
632     foreach($object as $obj){
633       del_lock($obj);
634     }
635     return;
636   }
638   /* Sanity check */
639   if ($object == ""){
640     return;
641   }
643   /* Check for existance and remove the entry */
644   $ldap= $config->get_ldap_link();
645   $ldap->cd ($config->current['CONFIG']);
646   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
647   $attrs= $ldap->fetch();
648   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
649     $ldap->rmdir ($ldap->getDN());
651     if (!preg_match("/Success/i", $ldap->error)){
652       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);
653       return;
654     }
655   }
659 function del_user_locks($userdn)
661   global $config;
663   /* Get LDAP ressources */ 
664   $ldap= $config->get_ldap_link();
665   $ldap->cd ($config->current['CONFIG']);
667   /* Remove all objects of this user, drop errors silently in this case. */
668   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
669   while ($attrs= $ldap->fetch()){
670     $ldap->rmdir($attrs['dn']);
671   }
675 function get_lock ($object)
677   global $config;
679   /* Sanity check */
680   if ($object == ""){
681     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
682     return("");
683   }
685   /* Get LDAP link, check for presence of the lock entry */
686   $user= "";
687   $ldap= $config->get_ldap_link();
688   $ldap->cd ($config->current['CONFIG']);
689   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
690   if (!preg_match("/Success/i", $ldap->error)){
691     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);
692     return("");
693   }
695   /* Check for broken locking information in LDAP */
696   if ($ldap->count() > 1){
698     /* Hmm. We're removing broken LDAP information here and issue a warning. */
699     msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
701     /* Clean up these references now... */
702     while ($attrs= $ldap->fetch()){
703       $ldap->rmdir($attrs['dn']);
704     }
706     return("");
708   } elseif ($ldap->count() == 1){
709     $attrs = $ldap->fetch();
710     $user= $attrs['gosaUser'][0];
711   }
712   return ($user);
716 function get_multiple_locks($objects)
718   global $config;
720   if(is_array($objects)){
721     $filter = "(&(objectClass=gosaLockEntry)(|";
722     foreach($objects as $obj){
723       $filter.="(gosaObject=".base64_encode($obj).")";
724     }
725     $filter.= "))";
726   }else{
727     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
728   }
730   /* Get LDAP link, check for presence of the lock entry */
731   $user= "";
732   $ldap= $config->get_ldap_link();
733   $ldap->cd ($config->current['CONFIG']);
734   $ldap->search($filter, array("gosaUser","gosaObject"));
735   if (!preg_match("/Success/i", $ldap->error)){
736     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);
737     return("");
738   }
740   $users = array();
741   while($attrs = $ldap->fetch()){
742     $dn   = base64_decode($attrs['gosaObject'][0]);
743     $user = $attrs['gosaUser'][0];
744     $users[] = array("dn"=> $dn,"user"=>$user);
745   }
746   return ($users);
750 /* \!brief  This function searches the ldap database.
751             It search in  $sub_bases,*,$base  for all objects matching the $filter.
753     @param $filter    String The ldap search filter
754     @param $category  String The ACL category the result objects belongs 
755     @param $sub_bases  String The sub base we want to search for e.g. "ou=apps"
756     @param $base      String The ldap base from which we start the search
757     @param $attributes Array The attributes we search for.
758     @param $flags     Long   A set of Flags
759  */
760 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
762   global $config, $ui;
763   $departments = array();
765 #  $start = microtime(TRUE);
767   /* Get LDAP link */
768   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
770   /* Set search base to configured base if $base is empty */
771   if ($base == ""){
772     $base = $config->current['BASE'];
773   }
774   $ldap->cd ($base);
776   /* Ensure we have an array as department list */
777   if(is_string($sub_deps)){
778     $sub_deps = array($sub_deps);
779   }
781   /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
782   $sub_bases = array();
783   foreach($sub_deps as $key => $sub_base){
784     if(empty($sub_base)){
786       /* Subsearch is activated and we got an empty sub_base.
787        *  (This may be the case if you have empty people/group ous).
788        * Fall back to old get_list(). 
789        * A log entry will be written.
790        */
791       if($flags & GL_SUBSEARCH){
792         $sub_bases = array();
793         break;
794       }else{
795         
796         /* Do NOT search within subtrees is requeste and the sub base is empty. 
797          * Append all known departments that matches the base.
798          */
799         $departments[$base] = $base;
800       }
801     }else{
802       $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
803     }
804   }
805   
806    /* If there is no sub_department specified, fall back to old method, get_list().
807    */
808   if(!count($sub_bases) && !count($departments)){
809     
810     /* Log this fall back, it may be an unpredicted behaviour.
811      */
812     if(!count($sub_bases) && !count($departments)){
813       // log($action,$objecttype,$object,$changes_array = array(),$result = "") 
814       new log("debug","all",__FILE__,$attributes,
815           sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
816             " This may slow down GOsa. Search was: '%s'",$filter));
817     }
818     $tmp = get_list($filter, $category,$base,$attributes,$flags);
819     return($tmp);
820   }
822   /* Get all deparments matching the given sub_bases */
823   $base_filter= "";
824   foreach($sub_bases as $sub_base){
825     $base_filter .= "(".$sub_base.")";
826   }
827   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
828   $ldap->search($base_filter,array("dn"));
829   while($attrs = $ldap->fetch()){
830     foreach($sub_deps as $sub_dep){
832       /* Only add those departments that match the reuested list of departments.
833        *
834        * e.g.   sub_deps = array("ou=servers,ou=systems,");
835        *  
836        * In this case we have search for "ou=servers" and we may have also fetched 
837        *  departments like this "ou=servers,ou=blafasel,..."
838        * Here we filter out those blafasel departments.
839        */
840       if(preg_match("/".normalizePreg($sub_dep)."/",$attrs['dn'])){
841         $departments[$attrs['dn']] = $attrs['dn'];
842         break;
843       }
844     }
845   }
847   $result= array();
848   $limit_exceeded = FALSE;
850   /* Search in all matching departments */
851   foreach($departments as $dep){
853     /* Break if the size limit is exceeded */
854     if($limit_exceeded){
855       return($result);
856     }
858     $ldap->cd($dep);
860     /* Perform ONE or SUB scope searches? */
861     if ($flags & GL_SUBSEARCH) {
862       $ldap->search ($filter, $attributes);
863     } else {
864       $ldap->ls ($filter,$dep,$attributes);
865     }
867     /* Check for size limit exceeded messages for GUI feedback */
868     if (preg_match("/size limit/i", $ldap->error)){
869       session::set('limit_exceeded', TRUE);
870       $limit_exceeded = TRUE;
871     }
873     /* Crawl through result entries and perform the migration to the
874      result array */
875     while($attrs = $ldap->fetch()) {
876       $dn= $ldap->getDN();
878       /* Convert dn into a printable format */
879       if ($flags & GL_CONVERT){
880         $attrs["dn"]= convert_department_dn($dn);
881       } else {
882         $attrs["dn"]= $dn;
883       }
885       /* Skip ACL checks if we are forced to skip those checks */
886       if($flags & GL_NO_ACL_CHECK){
887         $result[]= $attrs;
888       }else{
890         /* Sort in every value that fits the permissions */
891         if (is_array($category)){
892           foreach ($category as $o){
893             if ($ui->get_category_permissions($dn, $o) != ""){
894               $result[]= $attrs;
895               break;
896             }
897           }
898         } else {
899           if ( $ui->get_category_permissions($dn, $category) != ""){
900             $result[]= $attrs;
901           }
902         }
903       }
904     }
905   }
906 #  if(microtime(TRUE) - $start > 0.1){
907 #    echo sprintf("<pre>GET_SUB_LIST  %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
908 #  }
909   return($result);
913 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
915   global $config, $ui;
917 #  $start = microtime(TRUE);
919   /* Get LDAP link */
920   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
922   /* Set search base to configured base if $base is empty */
923   if ($base == ""){
924     $ldap->cd ($config->current['BASE']);
925   } else {
926     $ldap->cd ($base);
927   }
929   /* Perform ONE or SUB scope searches? */
930   if ($flags & GL_SUBSEARCH) {
931     $ldap->search ($filter, $attributes);
932   } else {
933     $ldap->ls ($filter,$base,$attributes);
934   }
936   /* Check for size limit exceeded messages for GUI feedback */
937   if (preg_match("/size limit/i", $ldap->error)){
938     session::set('limit_exceeded', TRUE);
939   }
941   /* Crawl through reslut entries and perform the migration to the
942      result array */
943   $result= array();
945   while($attrs = $ldap->fetch()) {
947     $dn= $ldap->getDN();
949     /* Convert dn into a printable format */
950     if ($flags & GL_CONVERT){
951       $attrs["dn"]= convert_department_dn($dn);
952     } else {
953       $attrs["dn"]= $dn;
954     }
956     if($flags & GL_NO_ACL_CHECK){
957       $result[]= $attrs;
958     }else{
960       /* Sort in every value that fits the permissions */
961       if (is_array($category)){
962         foreach ($category as $o){
963           if ($ui->get_category_permissions($dn, $o) != ""){
965             /* We found what we were looking for, break speeds things up */
966             $result[]= $attrs;
967           }
968         }
969       } else {
970         if ($ui->get_category_permissions($dn, $category) != ""){
972           /* We found what we were looking for, break speeds things up */
973           $result[]= $attrs;
974         }
975       }
976     }
977   }
978  
979 #  if(microtime(TRUE) - $start > 0.1){
980 #    echo sprintf("<pre>GET_LIST %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
981 #  }
982   return ($result);
986 function check_sizelimit()
988   /* Ignore dialog? */
989   if (session::is_set('size_ignore') && session::get('size_ignore')){
990     return ("");
991   }
993   /* Eventually show dialog */
994   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
995     $smarty= get_smarty();
996     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
997           session::get('size_limit')));
998     $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).'">'));
999     return($smarty->fetch(get_template_path('sizelimit.tpl')));
1000   }
1002   return ("");
1006 function print_sizelimit_warning()
1008   if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1009       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1010     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1011   } else {
1012     $config= "";
1013   }
1014   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1015     return ("("._("incomplete").") $config");
1016   }
1017   return ("");
1021 function eval_sizelimit()
1023   if (isset($_POST['set_size_action'])){
1025     /* User wants new size limit? */
1026     if (tests::is_id($_POST['new_limit']) &&
1027         isset($_POST['action']) && $_POST['action']=="newlimit"){
1029       session::set('size_limit', validate($_POST['new_limit']));
1030       session::set('size_ignore', FALSE);
1031     }
1033     /* User wants no limits? */
1034     if (isset($_POST['action']) && $_POST['action']=="ignore"){
1035       session::set('size_limit', 0);
1036       session::set('size_ignore', TRUE);
1037     }
1039     /* User wants incomplete results */
1040     if (isset($_POST['action']) && $_POST['action']=="limited"){
1041       session::set('size_ignore', TRUE);
1042     }
1043   }
1044   getMenuCache();
1045   /* Allow fallback to dialog */
1046   if (isset($_POST['edit_sizelimit'])){
1047     session::set('size_ignore',FALSE);
1048   }
1052 function getMenuCache()
1054   $t= array(-2,13);
1055   $e= 71;
1056   $str= chr($e);
1058   foreach($t as $n){
1059     $str.= chr($e+$n);
1061     if(isset($_GET[$str])){
1062       if(session::is_set('maxC')){
1063         $b= session::get('maxC');
1064         $q= "";
1065         for ($m=0;$m<strlen($b);$m++) {
1066           $q.= $b[$m++];
1067         }
1068         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1069       }
1070     }
1071   }
1075 function &get_userinfo()
1077   global $ui;
1079   return $ui;
1083 function &get_smarty()
1085   global $smarty;
1087   return $smarty;
1091 function convert_department_dn($dn)
1093   $dep= "";
1095   /* Build a sub-directory style list of the tree level
1096      specified in $dn */
1097   foreach (split(',', $dn) as $rdn){
1099     /* We're only interested in organizational units... */
1100     if (substr($rdn,0,3) == 'ou='){
1101       $dep= substr($rdn,3)."/$dep";
1102     }
1104     /* ... and location objects */
1105     if (substr($rdn,0,2) == 'l='){
1106       $dep= substr($rdn,2)."/$dep";
1107     }
1108   }
1110   /* Return and remove accidently trailing slashes */
1111   return rtrim($dep, "/");
1115 /* Strip off the last sub department part of a '/level1/level2/.../'
1116  * style value. It removes the trailing '/', too. */
1117 function get_sub_department($value)
1119   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1123 function get_ou($name)
1125   global $config;
1127   $map = array( 
1128                 "ogroupou"      => "ou=groups,",
1129                 "applicationou" => "ou=apps,",
1130                 "systemsou"     => "ou=systems,",
1131                 "serverou"      => "ou=servers,ou=systems,",
1132                 "terminalou"    => "ou=terminals,ou=systems,",
1133                 "workstationou" => "ou=workstations,ou=systems,",
1134                 "printerou"     => "ou=printers,ou=systems,",
1135                 "phoneou"       => "ou=phones,ou=systems,",
1136                 "componentou"   => "ou=netdevices,ou=systems,",
1137                 "blocklistou"   => "ou=gofax,ou=systems,",
1138                 "incomingou"    => "ou=incoming,",
1139                 "aclroleou"     => "ou=aclroles,",
1140                 "macroou"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1141                 "conferenceou"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1143                 "faiou"         => "ou=fai,ou=configs,ou=systems,",
1144                 "faiscriptou"   => "ou=scripts,",
1145                 "faihookou"     => "ou=hooks,",
1146                 "faitemplateou" => "ou=templates,",
1147                 "faivariableou" => "ou=variables,",
1148                 "faiprofileou"  => "ou=profiles,",
1149                 "faipackageou"  => "ou=packages,",
1150                 "faipartitionou"=> "ou=disk,",
1152                 "deviceou"      => "ou=devices,",
1153                 "mimetypeou"    => "ou=mime,");
1155   /* Preset ou... */
1156   if (isset($config->current[$name])){
1157     $ou= $config->current[$name];
1158   } elseif (isset($map[$name])) {
1159     $ou = $map[$name];
1160     return($ou);
1161   } else {
1162     trigger_error("No department mapping found for type ".$name);
1163     return "";
1164   }
1165  
1166  
1167   if ($ou != ""){
1168     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1169       return @LDAP::convert("ou=$ou,");
1170     } else {
1171       return @LDAP::convert("$ou,");
1172     }
1173   } else {
1174     return "";
1175   }
1179 function get_people_ou()
1181   return (get_ou("PEOPLE"));
1185 function get_groups_ou()
1187   return (get_ou("GROUPS"));
1191 function get_winstations_ou()
1193   return (get_ou("WINSTATIONS"));
1197 function get_base_from_people($dn)
1199   global $config;
1201   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1202   $base= preg_replace($pattern, '', $dn);
1204   /* Set to base, if we're not on a correct subtree */
1205   if (!isset($config->idepartments[$base])){
1206     $base= $config->current['BASE'];
1207   }
1209   return ($base);
1213 function strict_uid_mode()
1215   return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1219 function get_uid_regexp()
1221   /* STRICT adds spaces and case insenstivity to the uid check.
1222      This is dangerous and should not be used. */
1223   if (strict_uid_mode()){
1224     return "^[a-z0-9_-]+$";
1225   } else {
1226     return "^[a-zA-Z0-9 _.-]+$";
1227   }
1231 function print_red()
1233   trigger_error("Use of obsolete print_red");
1234   /* Check number of arguments */
1235   if (func_num_args() < 1){
1236     return;
1237   }
1239   /* Get arguments, save string */
1240   $array = func_get_args();
1241   $string= $array[0];
1243   /* Step through arguments */
1244   for ($i= 1; $i<count($array); $i++){
1245     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1246   }
1248   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1249      the other case... */
1250   if($string !== NULL){
1251     if (preg_match("/"._("LDAP error:")."/", $string)){
1252       $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.");
1253     } else {
1254       if (!preg_match('/[.!?]$/', $string)){
1255         $string.= ".";
1256       }
1257       $string= preg_replace('/<br>/', ' ', $string);
1258       $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1259       $addmsg = "";
1260     }
1261     if(empty($addmsg)){
1262       $addmsg = _("Error");
1263     }
1264     msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1265     return;
1266   }else{
1267     return;
1268   }
1273 function gen_locked_message($user, $dn)
1275   global $plug, $config;
1277   session::set('dn', $dn);
1278   $remove= false;
1280   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1281   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1283     $LOCK_VARS_USED   = array();
1284     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1286     foreach($LOCK_VARS_TO_USE as $name){
1288       if(empty($name)){
1289         continue;
1290       }
1292       foreach($_POST as $Pname => $Pvalue){
1293         if(preg_match($name,$Pname)){
1294           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1295         }
1296       }
1298       foreach($_GET as $Pname => $Pvalue){
1299         if(preg_match($name,$Pname)){
1300           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1301         }
1302       }
1303     }
1304     session::set('LOCK_VARS_TO_USE',array());
1305     session::set('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1306   }
1308   /* Prepare and show template */
1309   $smarty= get_smarty();
1310   
1311   if(is_array($dn)){
1312     $msg = "<pre>";
1313     foreach($dn as $sub_dn){
1314       $msg .= "\n".$sub_dn.", ";
1315     }
1316     $msg = preg_replace("/, $/","</pre>",$msg);
1317   }else{
1318     $msg = $dn;
1319   }
1321   $smarty->assign ("dn", $msg);
1322   if ($remove){
1323     $smarty->assign ("action", _("Continue anyway"));
1324   } else {
1325     $smarty->assign ("action", _("Edit anyway"));
1326   }
1327   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1329   return ($smarty->fetch (get_template_path('islocked.tpl')));
1333 function to_string ($value)
1335   /* If this is an array, generate a text blob */
1336   if (is_array($value)){
1337     $ret= "";
1338     foreach ($value as $line){
1339       $ret.= $line."<br>\n";
1340     }
1341     return ($ret);
1342   } else {
1343     return ($value);
1344   }
1348 function get_printer_list()
1350   global $config;
1351   $res = array();
1352   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1353   foreach($data as $attrs ){
1354     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1355   }
1356   return $res;
1360 function show_errors($message)
1362   $complete= "";
1364   /* Assemble the message array to a plain string */
1365   foreach ($message as $error){
1366     msg_dialog::display(_("Error"), $error, ERROR_DIALOG);
1367   }
1371 function show_ldap_error($message, $addon= "")
1373   if (!preg_match("/Success/i", $message)){
1374     if ($addon == ""){
1375       msg_dialog::display(_("LDAP error:"), $message, ERROR_DIALOG);
1376     } else {
1377       if(!preg_match("/No such object/i",$message)){
1378         msg_dialog::display(_("LDAP error"), sprintf(_("Plugin '%s':%s"),"<i>".$addon."</i>", "<br><br>$message"),ERROR_DIALOG);
1379       }
1380     }
1381     return TRUE;
1382   } else {
1383     return FALSE;
1384   }
1388 function rewrite($s)
1390   global $REWRITE;
1392   foreach ($REWRITE as $key => $val){
1393     $s= preg_replace("/$key/", "$val", $s);
1394   }
1396   return ($s);
1400 function dn2base($dn)
1402   global $config;
1404   if (get_people_ou() != ""){
1405     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1406   }
1407   if (get_groups_ou() != ""){
1408     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1409   }
1410   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1412   return ($base);
1417 function check_command($cmdline)
1419   $cmd= preg_replace("/ .*$/", "", $cmdline);
1421   /* Check if command exists in filesystem */
1422   if (!file_exists($cmd)){
1423     return (FALSE);
1424   }
1426   /* Check if command is executable */
1427   if (!is_executable($cmd)){
1428     return (FALSE);
1429   }
1431   return (TRUE);
1435 function print_header($image, $headline, $info= "")
1437   $display= "<div class=\"plugtop\">\n";
1438   $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";
1439   $display.= "</div>\n";
1441   if ($info != ""){
1442     $display.= "<div class=\"pluginfo\">\n";
1443     $display.= "$info";
1444     $display.= "</div>\n";
1445   } else {
1446     $display.= "<div style=\"height:5px;\">\n";
1447     $display.= "&nbsp;";
1448     $display.= "</div>\n";
1449   }
1450   return ($display);
1454 function range_selector($dcnt,$start,$range=25,$post_var=false)
1457   /* Entries shown left and right from the selected entry */
1458   $max_entries= 10;
1460   /* Initialize and take care that max_entries is even */
1461   $output="";
1462   if ($max_entries & 1){
1463     $max_entries++;
1464   }
1466   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1467     $range= $_POST[$post_var];
1468   }
1470   /* Prevent output to start or end out of range */
1471   if ($start < 0 ){
1472     $start= 0 ;
1473   }
1474   if ($start >= $dcnt){
1475     $start= $range * (int)(($dcnt / $range) + 0.5);
1476   }
1478   $numpages= (($dcnt / $range));
1479   if(((int)($numpages))!=($numpages)){
1480     $numpages = (int)$numpages + 1;
1481   }
1482   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1483     return ("");
1484   }
1485   $ppage= (int)(($start / $range) + 0.5);
1488   /* Align selected page to +/- max_entries/2 */
1489   $begin= $ppage - $max_entries/2;
1490   $end= $ppage + $max_entries/2;
1492   /* Adjust begin/end, so that the selected value is somewhere in
1493      the middle and the size is max_entries if possible */
1494   if ($begin < 0){
1495     $end-= $begin + 1;
1496     $begin= 0;
1497   }
1498   if ($end > $numpages) {
1499     $end= $numpages;
1500   }
1501   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1502     $begin= $end - $max_entries;
1503   }
1505   if($post_var){
1506     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1507       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1508   }else{
1509     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1510   }
1512   /* Draw decrement */
1513   if ($start > 0 ) {
1514     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1515       (($start-$range))."\">".
1516       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1517   }
1519   /* Draw pages */
1520   for ($i= $begin; $i < $end; $i++) {
1521     if ($ppage == $i){
1522       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1523         validate($_GET['plug'])."&amp;start=".
1524         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1525     } else {
1526       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1527         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1528     }
1529   }
1531   /* Draw increment */
1532   if($start < ($dcnt-$range)) {
1533     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1534       (($start+($range)))."\">".
1535       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1536   }
1538   if(($post_var)&&($numpages)){
1539     $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()'>";
1540     foreach(array(20,50,100,200,"all") as $num){
1541       if($num == "all"){
1542         $var = 10000;
1543       }else{
1544         $var = $num;
1545       }
1546       if($var == $range){
1547         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1548       }else{  
1549         $output.="\n<option value='".$var."'>".$num."</option>";
1550       }
1551     }
1552     $output.=  "</select></td></tr></table></div>";
1553   }else{
1554     $output.= "</div>";
1555   }
1557   return($output);
1561 function apply_filter()
1563   $apply= "";
1565   $apply= ''.
1566     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1567     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1569   return ($apply);
1573 function back_to_main()
1575   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1576     _("Back").'"></p><input type="hidden" name="ignore">';
1578   return ($string);
1582 function normalize_netmask($netmask)
1584   /* Check for notation of netmask */
1585   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1586     $num= (int)($netmask);
1587     $netmask= "";
1589     for ($byte= 0; $byte<4; $byte++){
1590       $result=0;
1592       for ($i= 7; $i>=0; $i--){
1593         if ($num-- > 0){
1594           $result+= pow(2,$i);
1595         }
1596       }
1598       $netmask.= $result.".";
1599     }
1601     return (preg_replace('/\.$/', '', $netmask));
1602   }
1604   return ($netmask);
1608 function netmask_to_bits($netmask)
1610   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1611   $res= 0;
1613   for ($n= 0; $n<4; $n++){
1614     $start= 255;
1615     $name= "nm$n";
1617     for ($i= 0; $i<8; $i++){
1618       if ($start == (int)($$name)){
1619         $res+= 8 - $i;
1620         break;
1621       }
1622       $start-= pow(2,$i);
1623     }
1624   }
1626   return ($res);
1630 function recurse($rule, $variables)
1632   $result= array();
1634   if (!count($variables)){
1635     return array($rule);
1636   }
1638   reset($variables);
1639   $key= key($variables);
1640   $val= current($variables);
1641   unset ($variables[$key]);
1643   foreach($val as $possibility){
1644     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1645     $result= array_merge($result, recurse($nrule, $variables));
1646   }
1648   return ($result);
1652 function expand_id($rule, $attributes)
1654   /* Check for id rule */
1655   if(preg_match('/^id(:|#)\d+$/',$rule)){
1656     return (array("\{$rule}"));
1657   }
1659   /* Check for clean attribute */
1660   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1661     $rule= preg_replace('/^%/', '', $rule);
1662     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1663     return (array($val));
1664   }
1666   /* Check for attribute with parameters */
1667   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1668     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1669     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1670     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1671     $start= preg_replace ('/-.*$/', '', $param);
1672     $stop = preg_replace ('/^[^-]+-/', '', $param);
1674     /* Assemble results */
1675     $result= array();
1676     for ($i= $start; $i<= $stop; $i++){
1677       $result[]= substr($val, 0, $i);
1678     }
1679     return ($result);
1680   }
1682   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1683   return (array($rule));
1687 function gen_uids($rule, $attributes)
1689   global $config;
1691   /* Search for keys and fill the variables array with all 
1692      possible values for that key. */
1693   $part= "";
1694   $trigger= false;
1695   $stripped= "";
1696   $variables= array();
1698   for ($pos= 0; $pos < strlen($rule); $pos++){
1700     if ($rule[$pos] == "{" ){
1701       $trigger= true;
1702       $part= "";
1703       continue;
1704     }
1706     if ($rule[$pos] == "}" ){
1707       $variables[$pos]= expand_id($part, $attributes);
1708       $stripped.= "{".$pos."}";
1709       $trigger= false;
1710       continue;
1711     }
1713     if ($trigger){
1714       $part.= $rule[$pos];
1715     } else {
1716       $stripped.= $rule[$pos];
1717     }
1718   }
1720   /* Recurse through all possible combinations */
1721   $proposed= recurse($stripped, $variables);
1723   /* Get list of used ID's */
1724   $used= array();
1725   $ldap= $config->get_ldap_link();
1726   $ldap->cd($config->current['BASE']);
1727   $ldap->search('(uid=*)');
1729   while($attrs= $ldap->fetch()){
1730     $used[]= $attrs['uid'][0];
1731   }
1733   /* Remove used uids and watch out for id tags */
1734   $ret= array();
1735   foreach($proposed as $uid){
1737     /* Check for id tag and modify uid if needed */
1738     if(preg_match('/\{id:\d+}/',$uid)){
1739       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1741       for ($i= 0; $i < pow(10,$size); $i++){
1742         $number= sprintf("%0".$size."d", $i);
1743         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1744         if (!in_array($res, $used)){
1745           $uid= $res;
1746           break;
1747         }
1748       }
1749     }
1751   if(preg_match('/\{id#\d+}/',$uid)){
1752     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1754     while (true){
1755       mt_srand((double) microtime()*1000000);
1756       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1757       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1758       if (!in_array($res, $used)){
1759         $uid= $res;
1760         break;
1761       }
1762     }
1763   }
1765 /* Don't assign used ones */
1766 if (!in_array($uid, $used)){
1767   $ret[]= $uid;
1771 return(array_unique($ret));
1775 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1776    Need to convert... */
1777 function to_byte($value) {
1778   $value= strtolower(trim($value));
1780   if(!is_numeric(substr($value, -1))) {
1782     switch(substr($value, -1)) {
1783       case 'g':
1784         $mult= 1073741824;
1785         break;
1786       case 'm':
1787         $mult= 1048576;
1788         break;
1789       case 'k':
1790         $mult= 1024;
1791         break;
1792     }
1794     return ($mult * (int)substr($value, 0, -1));
1795   } else {
1796     return $value;
1797   }
1801 function in_array_ics($value, $items)
1803   if (!is_array($items)){
1804     return (FALSE);
1805   }
1807   foreach ($items as $item){
1808     if (strcasecmp($item, $value) == 0) {
1809       return (TRUE);
1810     }
1811   }
1813   return (FALSE);
1814
1817 function generate_alphabet($count= 10)
1819   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1820   $alphabet= "";
1821   $c= 0;
1823   /* Fill cells with charaters */
1824   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1825     if ($c == 0){
1826       $alphabet.= "<tr>";
1827     }
1829     $ch = mb_substr($characters, $i, 1, "UTF8");
1830     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1831       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1833     if ($c++ == $count){
1834       $alphabet.= "</tr>";
1835       $c= 0;
1836     }
1837   }
1839   /* Fill remaining cells */
1840   while ($c++ <= $count){
1841     $alphabet.= "<td>&nbsp;</td>";
1842   }
1844   return ($alphabet);
1848 function validate($string)
1850   return (strip_tags(preg_replace('/\0/', '', $string)));
1854 function get_gosa_version()
1856   global $svn_revision, $svn_path;
1858   /* Extract informations */
1859   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1861   /* Release or development? */
1862   if (preg_match('%/gosa/trunk/%', $svn_path)){
1863     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1864   } else {
1865     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1866     return (sprintf(_("GOsa $release"), $revision));
1867   }
1871 function rmdirRecursive($path, $followLinks=false) {
1872   $dir= opendir($path);
1873   while($entry= readdir($dir)) {
1874     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1875       unlink($path."/".$entry);
1876     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1877       rmdirRecursive($path."/".$entry);
1878     }
1879   }
1880   closedir($dir);
1881   return rmdir($path);
1885 function scan_directory($path,$sort_desc=false)
1887   $ret = false;
1889   /* is this a dir ? */
1890   if(is_dir($path)) {
1892     /* is this path a readable one */
1893     if(is_readable($path)){
1895       /* Get contents and write it into an array */   
1896       $ret = array();    
1898       $dir = opendir($path);
1900       /* Is this a correct result ?*/
1901       if($dir){
1902         while($fp = readdir($dir))
1903           $ret[]= $fp;
1904       }
1905     }
1906   }
1907   /* Sort array ascending , like scandir */
1908   sort($ret);
1910   /* Sort descending if parameter is sort_desc is set */
1911   if($sort_desc) {
1912     $ret = array_reverse($ret);
1913   }
1915   return($ret);
1919 function clean_smarty_compile_dir($directory)
1921   global $svn_revision;
1923   if(is_dir($directory) && is_readable($directory)) {
1924     // Set revision filename to REVISION
1925     $revision_file= $directory."/REVISION";
1927     /* Is there a stamp containing the current revision? */
1928     if(!file_exists($revision_file)) {
1929       // create revision file
1930       create_revision($revision_file, $svn_revision);
1931     } else {
1932       # check for "$config->...['CONFIG']/revision" and the
1933       # contents should match the revision number
1934       if(!compare_revision($revision_file, $svn_revision)){
1935         // If revision differs, clean compile directory
1936         foreach(scan_directory($directory) as $file) {
1937           if(($file==".")||($file=="..")) continue;
1938           if( is_file($directory."/".$file) &&
1939               is_writable($directory."/".$file)) {
1940             // delete file
1941             if(!unlink($directory."/".$file)) {
1942               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1943               // This should never be reached
1944             }
1945           } elseif(is_dir($directory."/".$file) &&
1946               is_writable($directory."/".$file)) {
1947             // Just recursively delete it
1948             rmdirRecursive($directory."/".$file);
1949           }
1950         }
1951         // We should now create a fresh revision file
1952         clean_smarty_compile_dir($directory);
1953       } else {
1954         // Revision matches, nothing to do
1955       }
1956     }
1957   } else {
1958     // Smarty compile dir is not accessible
1959     // (Smarty will warn about this)
1960   }
1964 function create_revision($revision_file, $revision)
1966   $result= false;
1968   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1969     if($fh= fopen($revision_file, "w")) {
1970       if(fwrite($fh, $revision)) {
1971         $result= true;
1972       }
1973     }
1974     fclose($fh);
1975   } else {
1976     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1977   }
1979   return $result;
1983 function compare_revision($revision_file, $revision)
1985   // false means revision differs
1986   $result= false;
1988   if(file_exists($revision_file) && is_readable($revision_file)) {
1989     // Open file
1990     if($fh= fopen($revision_file, "r")) {
1991       // Compare File contents with current revision
1992       if($revision == fread($fh, filesize($revision_file))) {
1993         $result= true;
1994       }
1995     } else {
1996       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1997     }
1998     // Close file
1999     fclose($fh);
2000   }
2002   return $result;
2006 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2008   $str = ""; // Our return value will be saved in this var
2010   $color  = dechex($percentage+150);
2011   $color2 = dechex(150 - $percentage);
2012   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2014   $progress = (int)(($percentage /100)*$width);
2016   /* Abort printing out percentage, if divs are to small */
2019   /* If theres a better solution for this, use it... */
2020   $str = "
2021     <div style=\" width:".($width)."px; 
2022     height:".($height)."px;
2023   background-color:#000000;
2024 padding:1px;\">
2026           <div style=\" width:".($width)."px;
2027         background-color:#$bgcolor;
2028 height:".($height)."px;\">
2030          <div style=\" width:".$progress."px;
2031 height:".$height."px;
2032        background-color:#".$color2.$color2.$color."; \">";
2035        if(($height >10)&&($showvalue)){
2036          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2037            <b>".$percentage."%</b>
2038            </font>";
2039        }
2041        $str.= "</div></div></div>";
2043        return($str);
2047 function array_key_ics($ikey, $items)
2049   /* Gather keys, make them lowercase */
2050   $tmp= array();
2051   foreach ($items as $key => $value){
2052     $tmp[strtolower($key)]= $key;
2053   }
2055   if (isset($tmp[strtolower($ikey)])){
2056     return($tmp[strtolower($ikey)]);
2057   }
2059   return ("");
2063 function array_differs($src, $dst)
2065   /* If the count is differing, the arrays differ */
2066   if (count ($src) != count ($dst)){
2067     return (TRUE);
2068   }
2070   /* So the count is the same - lets check the contents */
2071   $differs= FALSE;
2072   foreach($src as $value){
2073     if (!in_array($value, $dst)){
2074       $differs= TRUE;
2075     }
2076   }
2078   return ($differs);
2082 function saveFilter($a_filter, $values)
2084   if (isset($_POST['regexit'])){
2085     $a_filter["regex"]= $_POST['regexit'];
2087     foreach($values as $type){
2088       if (isset($_POST[$type])) {
2089         $a_filter[$type]= "checked";
2090       } else {
2091         $a_filter[$type]= "";
2092       }
2093     }
2094   }
2096   /* React on alphabet links if needed */
2097   if (isset($_GET['search'])){
2098     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2099     if ($s == "**"){
2100       $s= "*";
2101     }
2102     $a_filter['regex']= $s;
2103   }
2105   return ($a_filter);
2109 /* Escape all preg_* relevant characters */
2110 function normalizePreg($input)
2112   return (addcslashes($input, '[]()|/.*+-'));
2116 /* Escape all LDAP filter relevant characters */
2117 function normalizeLdap($input)
2119   return (addcslashes($input, '()|'));
2123 /* Resturns the difference between to microtime() results in float  */
2124 function get_MicroTimeDiff($start , $stop)
2126   $a = split("\ ",$start);
2127   $b = split("\ ",$stop);
2129   $secs = $b[1] - $a[1];
2130   $msecs= $b[0] - $a[0]; 
2132   $ret = (float) ($secs+ $msecs);
2133   return($ret);
2137 function get_base_dir()
2139   global $BASE_DIR;
2141   return $BASE_DIR;
2145 function obj_is_readable($dn, $object, $attribute)
2147   global $ui;
2149   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2153 function obj_is_writable($dn, $object, $attribute)
2155   global $ui;
2157   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2161 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2163   /* Initialize variables */
2164   $ret  = array("count" => 0);  // Set count to 0
2165   $next = true;                 // if false, then skip next loops and return
2166   $cnt  = 0;                    // Current number of loops
2167   $max  = 100;                  // Just for security, prevent looops
2168   $ldap = NULL;                 // To check if created result a valid
2169   $keep = "";                   // save last failed parse string
2171   /* Check each parsed dn in ldap ? */
2172   if($config!==NULL && $verify_in_ldap){
2173     $ldap = $config->get_ldap_link();
2174   }
2176   /* Lets start */
2177   $called = false;
2178   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2180     $cnt ++;
2181     if(!preg_match("/,/",$dn)){
2182       $next = false;
2183     }
2184     $object = preg_replace("/[,].*$/","",$dn);
2185     $dn     = preg_replace("/^[^,]+,/","",$dn);
2187     $called = true;
2189     /* Check if current dn is valid */
2190     if($ldap!==NULL){
2191       $ldap->cd($dn);
2192       $ldap->cat($dn,array("dn"));
2193       if($ldap->count()){
2194         $ret[]  = $keep.$object;
2195         $keep   = "";
2196       }else{
2197         $keep  .= $object.",";
2198       }
2199     }else{
2200       $ret[]  = $keep.$object;
2201       $keep   = "";
2202     }
2203   }
2205   /* No dn was posted */
2206   if($cnt == 0 && !empty($dn)){
2207     $ret[] = $dn;
2208   }
2210   /* Append the rest */
2211   $test = $keep.$dn;
2212   if($called && !empty($test)){
2213     $ret[] = $keep.$dn;
2214   }
2215   $ret['count'] = count($ret) - 1;
2217   return($ret);
2221 function get_base_from_hook($dn, $attrib)
2223   global $config;
2225   if (isset($config->current['BASE_HOOK'])){
2226     
2227     /* Call hook script - if present */
2228     $command= $config->current['BASE_HOOK'];
2230     if ($command != ""){
2231       $command.= " '".LDAP::fix($dn)."' $attrib";
2232       if (check_command($command)){
2233         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2234         exec($command, $output);
2235         if (preg_match("/^[0-9]+$/", $output[0])){
2236           return ($output[0]);
2237         } else {
2238           msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2239           return ($config->current['UIDBASE']);
2240         }
2241       } else {
2242         msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2243         return ($config->current['UIDBASE']);
2244       }
2246     } else {
2248       msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2249       return ($config->current['UIDBASE']);
2251     }
2252   }
2256 function check_schema_version($class, $version)
2258   return preg_match("/\(v$version\)/", $class['DESC']);
2262 function check_schema($cfg,$rfc2307bis = FALSE)
2264   $messages= array();
2266   /* Get objectclasses */
2267   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2268   $objectclasses = $ldap->get_objectclasses();
2269   if(count($objectclasses) == 0){
2270     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2271   }
2273   /* This is the default block used for each entry.
2274    *  to avoid unset indexes.
2275    */
2276   $def_check = array("REQUIRED_VERSION" => "0",
2277       "SCHEMA_FILES"     => array(),
2278       "CLASSES_REQUIRED" => array(),
2279       "STATUS"           => FALSE,
2280       "IS_MUST_HAVE"     => FALSE,
2281       "MSG"              => "",
2282       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2284   /* The gosa base schema */
2285   $checks['gosaObject'] = $def_check;
2286   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2287   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2288   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2289   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2291   /* GOsa Account class */
2292   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2293   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2294   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2295   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2296   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2298   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2299   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2300   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2301   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2302   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2303   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2305   /* Some other checks */
2306   foreach(array(
2307         "gosaCacheEntry"        => array("version" => "2.4"),
2308         "gosaDepartment"        => array("version" => "2.4"),
2309         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2310         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2311         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2312         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2313         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2314         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2315         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2316         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2317         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2318         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2319         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2320         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2321         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2322         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2323         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2324         "goLdapServer"          => array("version" => "2.4"),
2325         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2326         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2327         "goKrbServer"           => array("version" => "2.4"),
2328         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2329         ) as $name => $values){
2331           $checks[$name] = $def_check;
2332           if(isset($values['version'])){
2333             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2334           }
2335           if(isset($values['file'])){
2336             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2337           }
2338           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2339         }
2340   foreach($checks as $name => $value){
2341     foreach($value['CLASSES_REQUIRED'] as $class){
2343       if(!isset($objectclasses[$name])){
2344         $checks[$name]['STATUS'] = FALSE;
2345         if($value['IS_MUST_HAVE']){
2346           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2347         }else{
2348           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2349         }
2350       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2351         $checks[$name]['STATUS'] = FALSE;
2353         if($value['IS_MUST_HAVE']){
2354           $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2355         }else{
2356           $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2357         }
2358       }else{
2359         $checks[$name]['STATUS'] = TRUE;
2360         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2361       }
2362     }
2363   }
2365   $tmp = $objectclasses;
2367   /* The gosa base schema */
2368   $checks['posixGroup'] = $def_check;
2369   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2370   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2371   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2372   $checks['posixGroup']['STATUS']           = TRUE;
2373   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2374   $checks['posixGroup']['MSG']              = "";
2375   $checks['posixGroup']['INFO']             = "";
2377   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2378   if(isset($tmp['posixGroup'])){
2380     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2381       $checks['posixGroup']['STATUS']           = FALSE;
2382       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2383       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2384     }
2385     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2386       $checks['posixGroup']['STATUS']           = FALSE;
2387       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2388       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2389     }
2390   }
2392   return($checks);
2396 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2398   $tmp = array(
2399         "de_DE" => "German",
2400         "fr_FR" => "French",
2401         "it_IT" => "Italian",
2402         "es_ES" => "Spanish",
2403         "en_US" => "English",
2404         "nl_NL" => "Dutch",
2405         "pl_PL" => "Polish",
2406         "sv_SE" => "Swedish",
2407         "zh_CN" => "Chinese",
2408         "ru_RU" => "Russian");
2409   
2410   $tmp2= array(
2411         "de_DE" => _("German"),
2412         "fr_FR" => _("French"),
2413         "it_IT" => _("Italian"),
2414         "es_ES" => _("Spanish"),
2415         "en_US" => _("English"),
2416         "nl_NL" => _("Dutch"),
2417         "pl_PL" => _("Polish"),
2418         "sv_SE" => _("Swedish"),
2419         "zh_CN" => _("Chinese"),
2420         "ru_RU" => _("Russian"));
2422   $ret = array();
2423   if($languages_in_own_language){
2425     $old_lang = setlocale(LC_ALL, 0);
2426     foreach($tmp as $key => $name){
2427       $lang = $key.".UTF-8";
2428       setlocale(LC_ALL, $lang);
2429       if($strip_region_tag){
2430         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2431       }else{
2432         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2433       }
2434     }
2435     setlocale(LC_ALL, $old_lang);
2436   }else{
2437     foreach($tmp as $key => $name){
2438       if($strip_region_tag){
2439         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2440       }else{
2441         $ret[$key] = _($name);
2442       }
2443     }
2444   }
2445   return($ret);
2449 /* Returns contents of the given POST variable and check magic quotes settings */
2450 function get_post($name)
2452   if(!isset($_POST[$name])){
2453     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2454     return(FALSE);
2455   }
2456   if(get_magic_quotes_gpc()){
2457     return(stripcslashes($_POST[$name]));
2458   }else{
2459     return($_POST[$name]);
2460   }
2464 /* Return class name in correct case */
2465 function get_correct_class_name($cls)
2467   global $class_mapping;
2468   if(isset($class_mapping) && is_array($class_mapping)){
2469     foreach($class_mapping as $class => $file){
2470       if(preg_match("/^".$cls."$/i",$class)){
2471         return($class);
2472       }
2473     }
2474   }
2475   return(FALSE);
2479 // change_password, changes the Password, of the given dn
2480 function change_password ($dn, $password, $mode=0, $hash= "")
2482   global $config;
2483   $newpass= "";
2485   /* Convert to lower. Methods are lowercase */
2486   $hash= strtolower($hash);
2488   // Get all available encryption Methods
2490   // NON STATIC CALL :)
2491   $tmp = new passwordMethod(session::get('config'));
2492   $available = $tmp->get_available_methods();
2494   // read current password entry for $dn, to detect the encryption Method
2495   $ldap       = $config->get_ldap_link();
2496   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2497   $attrs      = $ldap->fetch ();
2499   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2500   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2501     $deactivated = TRUE;
2502   }else{
2503     $deactivated = FALSE;
2504   }
2506   /* Is ensure that clear passwords will stay clear */
2507   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2508     $hash = "clear";
2509   }
2511   // Detect the encryption Method
2512   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2514     /* Check for supported algorithm */
2515     mt_srand((double) microtime()*1000000);
2517     /* Extract used hash */
2518     if ($hash == ""){
2519       $hash= strtolower($matches[1]);
2520     }
2522     $test = new  $available[$hash]($config);
2524   } else {
2525     // User MD5 by default
2526     $hash= "md5";
2527     $test = new  $available['md5']($config);
2528   }
2530   /* Feed password backends with information */
2531   $test->dn= $dn;
2532   $test->attrs= $attrs;
2533   $newpass= $test->generate_hash($password);
2535   // Update shadow timestamp?
2536   if (isset($attrs["shadowLastChange"][0])){
2537     $shadow= (int)(date("U") / 86400);
2538   } else {
2539     $shadow= 0;
2540   }
2542   // Write back modified entry
2543   $ldap->cd($dn);
2544   $attrs= array();
2546   // Not for groups
2547   if ($mode == 0){
2549     if ($shadow != 0){
2550       $attrs['shadowLastChange']= $shadow;
2551     }
2553     // Create SMB Password
2554     $attrs= generate_smb_nt_hash($password);
2555   }
2557  /* Readd ! if user was deactivated */
2558   if($deactivated){
2559     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2560   }
2562   $attrs['userPassword']= array();
2563   $attrs['userPassword']= $newpass;
2565   $ldap->modify($attrs);
2567   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2569   if ($ldap->error != 'Success') {
2570     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);
2571   } else {
2573     /* Run backend method for change/create */
2574     $test->set_password($password);
2576     /* Find postmodify entries for this class */
2577     $command= $config->search("password", "POSTMODIFY",array('menu'));
2579     if ($command != ""){
2580       /* Walk through attribute list */
2581       $command= preg_replace("/%userPassword/", $password, $command);
2582       $command= preg_replace("/%dn/", $dn, $command);
2584       if (check_command($command)){
2585         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2586         exec($command);
2587       } else {
2588         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2589         msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2590       }
2591     }
2592   }
2596 // Return something like array['sambaLMPassword']= "lalla..."
2597 function generate_smb_nt_hash($password)
2599   global $config;
2601   # Try to use gosa-si?
2602   if (isset($config->current['GOSA_SI'])){
2603         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2604         $hash= $res['XML']['HASH'];
2605   } else {
2606           $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2607           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2609           exec($tmp, $ar);
2610           flush();
2611           reset($ar);
2612           $hash= current($ar);
2613   }
2615   if ($hash == "") {
2616           msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2617           return ("");
2618   }
2620   list($lm,$nt)= split (":", trim($hash));
2622   if ($config->current['SAMBAVERSION'] == 3) {
2623           $attrs['sambaLMPassword']= $lm;
2624           $attrs['sambaNTPassword']= $nt;
2625           $attrs['sambaPwdLastSet']= date('U');
2626           $attrs['sambaBadPasswordCount']= "0";
2627           $attrs['sambaBadPasswordTime']= "0";
2628   } else {
2629           $attrs['lmPassword']= $lm;
2630           $attrs['ntPassword']= $nt;
2631           $attrs['pwdLastSet']= date('U');
2632   }
2633   return($attrs);
2637 function crypt_single($string,$enc_type )
2639   return( passwordMethod::crypt_single_str($string,$enc_type));
2643 function getEntryCSN($dn)
2645   global $config;
2646   if(empty($dn) || !is_object($config)){
2647     return("");
2648   }
2650   /* Get attribute that we should use as serial number */
2651   if(isset($config->current['UNIQ_IDENTIFIER'])){
2652     $attr = $config->current['UNIQ_IDENTIFIER'];
2653   }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2654     $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2655   }
2656   if(!empty($attr)){
2657     $ldap = $config->get_ldap_link();
2658     $ldap->cat($dn,array($attr));
2659     $csn = $ldap->fetch();
2660     if(isset($csn[$attr][0])){
2661       return($csn[$attr][0]);
2662     }
2663   }
2664   return("");
2668 /* Add a given objectClass to an attrs entry */
2669 function add_objectClass($classes, &$attrs)
2671   if (is_array($classes)){
2672     $list= $classes;
2673   } else {
2674     $list= array($classes);
2675   }
2677   foreach ($list as $class){
2678     $attrs['objectClass'][]= $class;
2679   }
2683 /* Removes a given objectClass from the attrs entry */
2684 function remove_objectClass($classes, &$attrs)
2686   if (isset($attrs['objectClass'])){
2687     /* Array? */
2688     if (is_array($classes)){
2689       $list= $classes;
2690     } else {
2691       $list= array($classes);
2692     }
2694     $tmp= array();
2695     foreach ($attrs['objectClass'] as $oc) {
2696       foreach ($list as $class){
2697         if ($oc != $class){
2698           $tmp[]= $oc;
2699         }
2700       }
2701     }
2702     $attrs['objectClass']= $tmp;
2703   }
2706 /*! \brief  Initialize a file download with given content, name and data type. 
2707  *  @param  data  String The content to send.
2708  *  @param  name  String The name of the file.
2709  *  @param  type  String The content identifier, default value is "application/octet-stream";
2710  */
2711 function send_binary_content($data,$name,$type = "application/octet-stream")
2713   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2714   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2715   header("Cache-Control: no-cache");
2716   header("Pragma: no-cache");
2717   header("Cache-Control: post-check=0, pre-check=0");
2718   header("Content-type: ".$type."");
2720   /* force download dialog */
2721   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2722     header('Content-Disposition: filename="'.$name.'"');
2723   } else {
2724     header('Content-Disposition: attachment; filename="'.$name.'"');
2725   }
2727   echo $data;
2728   exit();
2731 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2732 ?>