Code

Removed class_location.inc
[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);
33 /* Heimdal stuff */
34 define('UNIVERSAL',0x00);
35 define('INTEGER',0x02);
36 define('OCTET_STRING',0x04);
37 define('OBJECT_IDENTIFIER ',0x06);
38 define('SEQUENCE',0x10);
39 define('SEQUENCE_OF',0x10);
40 define('SET',0x11);
41 define('SET_OF',0x11);
42 define('DEBUG',false);
43 define('HDB_KU_MKEY',0x484442);
44 define('TWO_BIT_SHIFTS',0x7efc);
45 define('DES_CBC_CRC',1);
46 define('DES_CBC_MD4',2);
47 define('DES_CBC_MD5',3);
48 define('DES3_CBC_MD5',5);
49 define('DES3_CBC_SHA1',16);
51 /* Define globals for revision comparing */
52 $svn_path = '$HeadURL$';
53 $svn_revision = '$Revision$';
55 /* Include required files */
56 require_once("class_location.inc");
57 require_once ("functions_debug.inc");
58 require_once ("accept-to-gettext.inc");
60 /* Define constants for debugging */
61 define ("DEBUG_TRACE",   1);
62 define ("DEBUG_LDAP",    2);
63 define ("DEBUG_MYSQL",   4);
64 define ("DEBUG_SHELL",   8);
65 define ("DEBUG_POST",   16);
66 define ("DEBUG_SESSION",32);
67 define ("DEBUG_CONFIG", 64);
68 define ("DEBUG_ACL",    128);
70 /* Rewrite german 'umlauts' and spanish 'accents'
71    to get better results */
72 $REWRITE= array( "ä" => "ae",
73     "ö" => "oe",
74     "ü" => "ue",
75     "Ä" => "Ae",
76     "Ö" => "Oe",
77     "Ü" => "Ue",
78     "ß" => "ss",
79     "á" => "a",
80     "é" => "e",
81     "í" => "i",
82     "ó" => "o",
83     "ú" => "u",
84     "Á" => "A",
85     "É" => "E",
86     "Í" => "I",
87     "Ó" => "O",
88     "Ú" => "U",
89     "ñ" => "ny",
90     "Ñ" => "Ny" );
93 /* Class autoloader */
94 function __autoload($class_name) {
95     global $class_mapping, $BASE_DIR;
96     if (isset($class_mapping[$class_name])){
97       require_once($BASE_DIR."/".$class_mapping[$class_name]);
98     } else {
99       echo sprintf(_("Fatal error: cannot instantiate class '%s' - execution aborted"), $class_name);
100       print_a(debug_backtrace());
101       exit;
102     }
106 /* Check if plugin is avaliable */
107 function plugin_available($plugin)
109         global $class_mapping, $BASE_DIR;
111         if (!isset($class_mapping[$plugin])){
112                 return false;
113         } else {
114                 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
115         }
119 /* Create seed with microseconds */
120 function make_seed() {
121   list($usec, $sec) = explode(' ', microtime());
122   return (float) $sec + ((float) $usec * 100000);
126 /* Debug level action */
127 function DEBUG($level, $line, $function, $file, $data, $info="")
129   if (session::get('DEBUGLEVEL') & $level){
130     $output= "DEBUG[$level] ";
131     if ($function != ""){
132       $output.= "($file:$function():$line) - $info: ";
133     } else {
134       $output.= "($file:$line) - $info: ";
135     }
136     echo $output;
137     if (is_array($data)){
138       print_a($data);
139     } else {
140       echo "'$data'";
141     }
142     echo "<br>";
143   }
147 function get_browser_language()
149   /* Try to use users primary language */
150   global $config;
151   $ui= get_userinfo();
152   if (isset($ui) && $ui !== NULL){
153     if ($ui->language != ""){
154       return ($ui->language.".UTF-8");
155     }
156   }
158   /* Check for global language settings in gosa.conf */
159   if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
160     $lang = $config->data['MAIN']['LANG'];
161     if(!preg_match("/utf/i",$lang)){
162       $lang .= ".UTF-8";
163     }
164     return($lang);
165   }
166  
167   /* Load supported languages */
168   $gosa_languages= get_languages();
170   /* Move supported languages to flat list */
171   $langs= array();
172   foreach($gosa_languages as $lang => $dummy){
173     $langs[]= $lang.'.UTF-8';
174   }
176   /* Return gettext based string */
177   return (al2gt($langs, 'text/html'));
181 /* Rewrite ui object to another dn */
182 function change_ui_dn($dn, $newdn)
184   $ui= session::get('ui');
185   if ($ui->dn == $dn){
186     $ui->dn= $newdn;
187     session::set('ui',$ui);
188   }
192 /* Return theme path for specified file */
193 function get_template_path($filename= '', $plugin= FALSE, $path= "")
195   global $config, $BASE_DIR;
197   if (!@isset($config->data['MAIN']['THEME'])){
198     $theme= 'default';
199   } else {
200     $theme= $config->data['MAIN']['THEME'];
201   }
203   /* Return path for empty filename */
204   if ($filename == ''){
205     return ("themes/$theme/");
206   }
208   /* Return plugin dir or root directory? */
209   if ($plugin){
210     if ($path == ""){
211       $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
212     } else {
213       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
214     }
215     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
216       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
217     }
218     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
219       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
220     }
221     if ($path == ""){
222       return (session::get('plugin_dir')."/$filename");
223     } else {
224       return ($path."/$filename");
225     }
226   } else {
227     if (file_exists("themes/$theme/$filename")){
228       return ("themes/$theme/$filename");
229     }
230     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
231       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
232     }
233     if (file_exists("themes/default/$filename")){
234       return ("themes/default/$filename");
235     }
236     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
237       return ("$BASE_DIR/ihtml/themes/default/$filename");
238     }
239     return ($filename);
240   }
244 function array_remove_entries($needles, $haystack)
246   $tmp= array();
248   /* Loop through entries to be removed */
249   foreach ($haystack as $entry){
250     if (!in_array($entry, $needles)){
251       $tmp[]= $entry;
252     }
253   }
255   return ($tmp);
259 function gosa_array_merge($ar1,$ar2)
261   if(!is_array($ar1) || !is_array($ar2)){
262     trigger_error("Specified parameter(s) are not valid arrays.");
263   }else{
264     return(array_values(array_unique(array_merge($ar1,$ar2))));
265   }
269 function gosa_log ($message)
271   global $ui;
273   /* Preset to something reasonable */
274   $username= " unauthenticated";
276   /* Replace username if object is present */
277   if (isset($ui)){
278     if ($ui->username != ""){
279       $username= "[$ui->username]";
280     } else {
281       $username= "unknown";
282     }
283   }
285   syslog(LOG_INFO,"GOsa$username: $message");
289 function ldap_init ($server, $base, $binddn='', $pass='')
291   global $config;
293   $ldap = new LDAP ($binddn, $pass, $server,
294       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
295       isset($config->current['TLS']) && $config->current['TLS'] == "true");
297   /* Sadly we've no proper return values here. Use the error message instead. */
298   if (!preg_match("/Success/i", $ldap->error)){
299     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
300     exit();
301   }
303   /* Preset connection base to $base and return to caller */
304   $ldap->cd ($base);
305   return $ldap;
309 function process_htaccess ($username, $kerberos= FALSE)
311   global $config;
313   /* Search for $username and optional @REALM in all configured LDAP trees */
314   foreach($config->data["LOCATIONS"] as $name => $data){
315   
316     $config->set_current($name);
317     $mode= "kerberos";
318     if (isset($config->current['KRBSASL']) && preg_match('/^true$/i', $config->current['KRBSASL'])){
319       $mode= "sasl";
320     }
322     /* Look for entry or realm */
323     $ldap= $config->get_ldap_link();
324     if (!preg_match("/Success/i", $ldap->error)){
325       msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
326       $smarty= get_smarty();
327       $smarty->display(get_template_path('headers.tpl'));
328       echo "<body>".session::get('errors')."</body></html>";
329       exit();
330     }
331     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
333     /* Found a uniq match? Return it... */
334     if ($ldap->count() == 1) {
335       $attrs= $ldap->fetch();
336       return array("username" => $attrs["uid"][0], "server" => $name);
337     }
338   }
340   /* Nothing found? Return emtpy array */
341   return array("username" => "", "server" => "");
345 function ldap_login_user_htaccess ($username)
347   global $config;
349   /* Look for entry or realm */
350   $ldap= $config->get_ldap_link();
351   if (!preg_match("/Success/i", $ldap->error)){
352     msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
353     $smarty= get_smarty();
354     $smarty->display(get_template_path('headers.tpl'));
355     echo "<body>".session::get('errors')."</body></html>";
356     exit();
357   }
358   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
359   /* Found no uniq match? Strange, because we did above... */
360   if ($ldap->count() != 1) {
361     msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
362     return (NULL);
363   }
364   $attrs= $ldap->fetch();
366   /* got user dn, fill acl's */
367   $ui= new userinfo($config, $ldap->getDN());
368   $ui->username= $attrs['uid'][0];
370   /* No password check needed - the webserver did it for us */
371   $ldap->disconnect();
373   /* Username is set, load subtreeACL's now */
374   $ui->loadACL();
376   /* TODO: check java script for htaccess authentication */
377   session::set('js',true);
379   return ($ui);
383 function ldap_login_user ($username, $password)
385   global $config;
387   /* look through the entire ldap */
388   $ldap = $config->get_ldap_link();
389   if (!preg_match("/Success/i", $ldap->error)){
390     msg_dialog::display(_("LDAP error"), sprintf(_("User login failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
391     $smarty= get_smarty();
392     $smarty->display(get_template_path('headers.tpl'));
393     echo "<body>".session::get('errors')."</body></html>";
394     exit();
395   }
396   $ldap->cd($config->current['BASE']);
397   $allowed_attributes = array("uid","mail");
398   $verify_attr = array();
399   if(isset($config->current['LOGIN_ATTRIBUTE'])){
400     $tmp = split(",",$config->current['LOGIN_ATTRIBUTE']); 
401     foreach($tmp as $attr){
402       if(in_array($attr,$allowed_attributes)){
403         $verify_attr[] = $attr;
404       }
405     }
406   }
407   if(count($verify_attr) == 0){
408     $verify_attr = array("uid");
409   }
410   $tmp= $verify_attr;
411   $tmp[] = "uid";
412   $filter = "";
413   foreach($verify_attr as $attr) {
414     $filter.= "(".$attr."=".$username.")";
415   }
416   $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
417   $ldap->search($filter,$tmp);
419   /* get results, only a count of 1 is valid */
420   switch ($ldap->count()){
422     /* user not found */
423     case 0:     return (NULL);
425             /* valid uniq user */
426     case 1: 
427             break;
429             /* found more than one matching id */
430     default:
431             msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
432             return (NULL);
433   }
435   /* LDAP schema is not case sensitive. Perform additional check. */
436   $attrs= $ldap->fetch();
437   $success = FALSE;
438   foreach($verify_attr as $attr){
439     if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
440       $success = TRUE;
441     }
442   }
443   if(!$success){
444     return(FALSE);
445   }
447   /* got user dn, fill acl's */
448   $ui= new userinfo($config, $ldap->getDN());
449   $ui->username= $attrs['uid'][0];
451   /* password check, bind as user with supplied password  */
452   $ldap->disconnect();
453   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
454       isset($config->current['RECURSIVE']) &&
455       $config->current['RECURSIVE'] == "true",
456       isset($config->current['TLS'])
457       && $config->current['TLS'] == "true");
458   if (!preg_match("/Success/i", $ldap->error)){
459     return (NULL);
460   }
462   /* Username is set, load subtreeACL's now */
463   $ui->loadACL();
465   return ($ui);
469 function ldap_expired_account($config, $userdn, $username)
471     $ldap= $config->get_ldap_link();
472     $ldap->cat($userdn);
473     $attrs= $ldap->fetch();
474     
475     /* default value no errors */
476     $expired = 0;
477     
478     $sExpire = 0;
479     $sLastChange = 0;
480     $sMax = 0;
481     $sMin = 0;
482     $sInactive = 0;
483     $sWarning = 0;
484     
485     $current= date("U");
486     
487     $current= floor($current /60 /60 /24);
488     
489     /* special case of the admin, should never been locked */
490     /* FIXME should allow any name as user admin */
491     if($username != "admin")
492     {
494       if(isset($attrs['shadowExpire'][0])){
495         $sExpire= $attrs['shadowExpire'][0];
496       } else {
497         $sExpire = 0;
498       }
499       
500       if(isset($attrs['shadowLastChange'][0])){
501         $sLastChange= $attrs['shadowLastChange'][0];
502       } else {
503         $sLastChange = 0;
504       }
505       
506       if(isset($attrs['shadowMax'][0])){
507         $sMax= $attrs['shadowMax'][0];
508       } else {
509         $smax = 0;
510       }
512       if(isset($attrs['shadowMin'][0])){
513         $sMin= $attrs['shadowMin'][0];
514       } else {
515         $sMin = 0;
516       }
517       
518       if(isset($attrs['shadowInactive'][0])){
519         $sInactive= $attrs['shadowInactive'][0];
520       } else {
521         $sInactive = 0;
522       }
523       
524       if(isset($attrs['shadowWarning'][0])){
525         $sWarning= $attrs['shadowWarning'][0];
526       } else {
527         $sWarning = 0;
528       }
529       
530       /* is the account locked */
531       /* shadowExpire + shadowInactive (option) */
532       if($sExpire >0){
533         if($current >= ($sExpire+$sInactive)){
534           return(1);
535         }
536       }
537     
538       /* the user should be warned to change is password */
539       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
540         if (($sExpire - $current) < $sWarning){
541           return(2);
542         }
543       }
544       
545       /* force user to change password */
546       if(($sLastChange >0) && ($sMax) >0){
547         if($current >= ($sLastChange+$sMax)){
548           return(3);
549         }
550       }
551       
552       /* the user should not be able to change is password */
553       if(($sLastChange >0) && ($sMin >0)){
554         if (($sLastChange + $sMin) >= $current){
555           return(4);
556         }
557       }
558     }
559    return($expired);
563 function add_lock ($object, $user)
565   global $config;
567   if(is_array($object)){
568     foreach($object as $obj){
569       add_lock($obj,$user);
570     }
571     return;
572   }
574   /* Just a sanity check... */
575   if ($object == "" || $user == ""){
576     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
577     return;
578   }
580   /* Check for existing entries in lock area */
581   $ldap= $config->get_ldap_link();
582   $ldap->cd ($config->current['CONFIG']);
583   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
584       array("gosaUser"));
585   if (!preg_match("/Success/i", $ldap->error)){
586     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);
587     return;
588   }
590   /* Add lock if none present */
591   if ($ldap->count() == 0){
592     $attrs= array();
593     $name= md5($object);
594     $ldap->cd("cn=$name,".$config->current['CONFIG']);
595     $attrs["objectClass"] = "gosaLockEntry";
596     $attrs["gosaUser"] = $user;
597     $attrs["gosaObject"] = base64_encode($object);
598     $attrs["cn"] = "$name";
599     $ldap->add($attrs);
600     if (!preg_match("/Success/i", $ldap->error)){
601       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);
602       return;
603     }
604   }
608 function del_lock ($object)
610   global $config;
612   if(is_array($object)){
613     foreach($object as $obj){
614       del_lock($obj);
615     }
616     return;
617   }
619   /* Sanity check */
620   if ($object == ""){
621     return;
622   }
624   /* Check for existance and remove the entry */
625   $ldap= $config->get_ldap_link();
626   $ldap->cd ($config->current['CONFIG']);
627   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
628   $attrs= $ldap->fetch();
629   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
630     $ldap->rmdir ($ldap->getDN());
632     if (!preg_match("/Success/i", $ldap->error)){
633       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);
634       return;
635     }
636   }
640 function del_user_locks($userdn)
642   global $config;
644   /* Get LDAP ressources */ 
645   $ldap= $config->get_ldap_link();
646   $ldap->cd ($config->current['CONFIG']);
648   /* Remove all objects of this user, drop errors silently in this case. */
649   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
650   while ($attrs= $ldap->fetch()){
651     $ldap->rmdir($attrs['dn']);
652   }
656 function get_lock ($object)
658   global $config;
660   /* Sanity check */
661   if ($object == ""){
662     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
663     return("");
664   }
666   /* Get LDAP link, check for presence of the lock entry */
667   $user= "";
668   $ldap= $config->get_ldap_link();
669   $ldap->cd ($config->current['CONFIG']);
670   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
671   if (!preg_match("/Success/i", $ldap->error)){
672     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);
673     return("");
674   }
676   /* Check for broken locking information in LDAP */
677   if ($ldap->count() > 1){
679     /* Hmm. We're removing broken LDAP information here and issue a warning. */
680     msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
682     /* Clean up these references now... */
683     while ($attrs= $ldap->fetch()){
684       $ldap->rmdir($attrs['dn']);
685     }
687     return("");
689   } elseif ($ldap->count() == 1){
690     $attrs = $ldap->fetch();
691     $user= $attrs['gosaUser'][0];
692   }
693   return ($user);
697 function get_multiple_locks($objects)
699   global $config;
701   if(is_array($objects)){
702     $filter = "(&(objectClass=gosaLockEntry)(|";
703     foreach($objects as $obj){
704       $filter.="(gosaObject=".base64_encode($obj).")";
705     }
706     $filter.= "))";
707   }else{
708     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
709   }
711   /* Get LDAP link, check for presence of the lock entry */
712   $user= "";
713   $ldap= $config->get_ldap_link();
714   $ldap->cd ($config->current['CONFIG']);
715   $ldap->search($filter, array("gosaUser","gosaObject"));
716   if (!preg_match("/Success/i", $ldap->error)){
717     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);
718     return("");
719   }
721   $users = array();
722   while($attrs = $ldap->fetch()){
723     $dn   = base64_decode($attrs['gosaObject'][0]);
724     $user = $attrs['gosaUser'][0];
725     $users[] = array("dn"=> $dn,"user"=>$user);
726   }
727   return ($users);
731 /* \!brief  This function searches the ldap database.
732             It search in  $sub_base,*,$base  for all objects matching the $filter.
734     @param $filter    String The ldap search filter
735     @param $category  String The ACL category the result objects belongs 
736     @param $sub_base  String The sub base we want to search for e.g. "ou=apps"
737     @param $base      String The ldap base from which we start the search
738     @param $attributes Array The attributes we search for.
739     @param $flags     Long   A set of Flags
740  */
741 function get_sub_list($filter, $category,$sub_base, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
744   global $config, $ui;
746   /* Get LDAP link */
747   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
749   /* Set search base to configured base if $base is empty */
750   if ($base == ""){
751     $ldap->cd ($config->current['BASE']);
752   } else {
753     $ldap->cd ($base);
754   }
756   /* Remove , ("ou=1,ou=2.." => "ou=1") */
757   $sub_base = preg_replace("/,.*$/","",$sub_base);
759   /* Check if there is a sub department specified */
760   if($sub_base == ""){
761     return(get_list($filter, $category,$base,$attributes,$flags));
762   }
764   /* Get all deparments matching the given sub_base */
765   $departments = array();
766   $ldap->search($sub_base,array("dn"));
767   while($attrs = $ldap->fetch()){
768     $departments[$attrs['dn']] = $attrs['dn'];
769   }
771   $result= array();
772   $limit_exceeded = FALSE;
774   /* Search in all matching departments */
775   foreach($departments as $dep){
777     /* Break if the size limit is exceeded */
778     if($limit_exceeded){
779       return($result);
780     }
782     $ldap->cd($dep);
784     /* Perform ONE or SUB scope searches? */
785     if ($flags & GL_SUBSEARCH) {
786       $ldap->search ($filter, $attributes);
787     } else {
788       $ldap->ls ($filter,$base,$attributes);
789     }
791     /* Check for size limit exceeded messages for GUI feedback */
792     if (preg_match("/size limit/i", $ldap->error)){
793       session::set('limit_exceeded', TRUE);
794       $limit_exceeded = TRUE;
795     }
797     /* Crawl through result entries and perform the migration to the
798      result array */
799     while($attrs = $ldap->fetch()) {
800       $dn= $ldap->getDN();
802       /* Convert dn into a printable format */
803       if ($flags & GL_CONVERT){
804         $attrs["dn"]= convert_department_dn($dn);
805       } else {
806         $attrs["dn"]= $dn;
807       }
809       /* Sort in every value that fits the permissions */
810       if (is_array($category)){
811         foreach ($category as $o){
812           if ($ui->get_category_permissions($dn, $o) != ""){
813             $result[]= $attrs;
814             break;
815           }
816         }
817       } else {
818         if ($ui->get_category_permissions($dn, $category) != ""){
819           $result[]= $attrs;
820         }
821       }
822     }
823   }
824   return($result);
828 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
830   global $config, $ui;
832   /* Get LDAP link */
833   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
835   /* Set search base to configured base if $base is empty */
836   if ($base == ""){
837     $ldap->cd ($config->current['BASE']);
838   } else {
839     $ldap->cd ($base);
840   }
842   /* Perform ONE or SUB scope searches? */
843   if ($flags & GL_SUBSEARCH) {
844     $ldap->search ($filter, $attributes);
845   } else {
846     $ldap->ls ($filter,$base,$attributes);
847   }
849   /* Check for size limit exceeded messages for GUI feedback */
850   if (preg_match("/size limit/i", $ldap->error)){
851     session::set('limit_exceeded', TRUE);
852   }
854   /* Crawl through reslut entries and perform the migration to the
855      result array */
856   $result= array();
858   while($attrs = $ldap->fetch()) {
859     $dn= $ldap->getDN();
861     /* Sort in every value that fits the permissions */
862     if (is_array($category)){
863       foreach ($category as $o){
864         if ($ui->get_category_permissions($dn, $o) != ""){
865           if ($flags & GL_CONVERT){
866             $attrs["dn"]= convert_department_dn($dn);
867           } else {
868             $attrs["dn"]= $dn;
869           }
871           /* We found what we were looking for, break speeds things up */
872           $result[]= $attrs;
873         }
874       }
875     } else {
876       if ($ui->get_category_permissions($dn, $category) != ""){
877         if ($flags & GL_CONVERT){
878           $attrs["dn"]= convert_department_dn($dn);
879         } else {
880           $attrs["dn"]= $dn;
881         }
883         /* We found what we were looking for, break speeds things up */
884         $result[]= $attrs;
885       }
886     }
887   }
889   return ($result);
893 function check_sizelimit()
895   /* Ignore dialog? */
896   if (session::is_set('size_ignore') && session::get('size_ignore')){
897     return ("");
898   }
900   /* Eventually show dialog */
901   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
902     $smarty= get_smarty();
903     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
904           session::get('size_limit')));
905     $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).'">'));
906     return($smarty->fetch(get_template_path('sizelimit.tpl')));
907   }
909   return ("");
913 function print_sizelimit_warning()
915   if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
916       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
917     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
918   } else {
919     $config= "";
920   }
921   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
922     return ("("._("incomplete").") $config");
923   }
924   return ("");
928 function eval_sizelimit()
930   if (isset($_POST['set_size_action'])){
932     /* User wants new size limit? */
933     if (tests::is_id($_POST['new_limit']) &&
934         isset($_POST['action']) && $_POST['action']=="newlimit"){
936       session::set('size_limit', validate($_POST['new_limit']));
937       session::set('size_ignore', FALSE);
938     }
940     /* User wants no limits? */
941     if (isset($_POST['action']) && $_POST['action']=="ignore"){
942       session::set('size_limit', 0);
943       session::set('size_ignore', TRUE);
944     }
946     /* User wants incomplete results */
947     if (isset($_POST['action']) && $_POST['action']=="limited"){
948       session::set('size_ignore', TRUE);
949     }
950   }
951   getMenuCache();
952   /* Allow fallback to dialog */
953   if (isset($_POST['edit_sizelimit'])){
954     session::set('size_ignore',FALSE);
955   }
959 function getMenuCache()
961   $t= array(-2,13);
962   $e= 71;
963   $str= chr($e);
965   foreach($t as $n){
966     $str.= chr($e+$n);
968     if(isset($_GET[$str])){
969       if(session::is_set('maxC')){
970         $b= session::get('maxC');
971         $q= "";
972         for ($m=0;$m<strlen($b);$m++) {
973           $q.= $b[$m++];
974         }
975         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
976       }
977     }
978   }
982 function &get_userinfo()
984   global $ui;
986   return $ui;
990 function &get_smarty()
992   global $smarty;
994   return $smarty;
998 function convert_department_dn($dn)
1000   $dep= "";
1002   /* Build a sub-directory style list of the tree level
1003      specified in $dn */
1004   foreach (split(',', $dn) as $rdn){
1006     /* We're only interested in organizational units... */
1007     if (substr($rdn,0,3) == 'ou='){
1008       $dep= substr($rdn,3)."/$dep";
1009     }
1011     /* ... and location objects */
1012     if (substr($rdn,0,2) == 'l='){
1013       $dep= substr($rdn,2)."/$dep";
1014     }
1015   }
1017   /* Return and remove accidently trailing slashes */
1018   return rtrim($dep, "/");
1022 /* Strip off the last sub department part of a '/level1/level2/.../'
1023  * style value. It removes the trailing '/', too. */
1024 function get_sub_department($value)
1026   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1030 function get_ou($name)
1032   global $config;
1034   $map = array( 
1035                 "ogroupou"      => "ou=groups,",
1036                 "applicationou" => "ou=apps,",
1037                 "systemsou"     => "ou=systems,",
1038                 "serverou"      => "ou=servers,ou=systems,",
1039                 "terminalou"    => "ou=terminals,ou=systems,",
1040                 "workstationou" => "ou=workstations,ou=systems,",
1041                 "printerou"     => "ou=printers,ou=systems,",
1042                 "phoneou"       => "ou=phones,ou=systems,",
1043                 "componentou"   => "ou=netdevices,ou=systems,",
1044                 "blocklistou"   => "ou=gofax,ou=systems,",
1045                 "incomingou"    => "ou=incoming,",
1046                 "aclroleou"     => "ou=aclroles,",
1047                 "macroou"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1048                 "conferenceou"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1050                 "faiou"         => "ou=fai,ou=configs,ou=systems,",
1051                 "faiscriptou"   => "ou=scripts,",
1052                 "faihookou"     => "ou=hooks,",
1053                 "faitemplateou" => "ou=templates,",
1054                 "faivariableou" => "ou=variables,",
1055                 "faiprofileou"  => "ou=profiles,",
1056                 "faipackageou"  => "ou=packages,",
1057                 "faipartitionou"=> "ou=disk,",
1059                 "deviceou"      => "ou=devices,",
1060                 "mimetypeou"    => "ou=mime,");
1062   /* Preset ou... */
1063   if (isset($config->current[$name])){
1064     $ou= $config->current[$name];
1065   } elseif (isset($map[$name])) {
1066     $ou = $map[$name];
1067     return($ou);
1068   } else {
1069     trigger_error("No department mapping found for type ".$name);
1070     return "";
1071   }
1072  
1073  
1074   if ($ou != ""){
1075     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1076       return @LDAP::convert("ou=$ou,");
1077     } else {
1078       return @LDAP::convert("$ou,");
1079     }
1080   } else {
1081     return "";
1082   }
1086 function get_people_ou()
1088   return (get_ou("PEOPLE"));
1092 function get_groups_ou()
1094   return (get_ou("GROUPS"));
1098 function get_winstations_ou()
1100   return (get_ou("WINSTATIONS"));
1104 function get_base_from_people($dn)
1106   global $config;
1108   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1109   $base= preg_replace($pattern, '', $dn);
1111   /* Set to base, if we're not on a correct subtree */
1112   if (!isset($config->idepartments[$base])){
1113     $base= $config->current['BASE'];
1114   }
1116   return ($base);
1120 function strict_uid_mode()
1122   return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1126 function get_uid_regexp()
1128   /* STRICT adds spaces and case insenstivity to the uid check.
1129      This is dangerous and should not be used. */
1130   if (strict_uid_mode()){
1131     return "^[a-z0-9_-]+$";
1132   } else {
1133     return "^[a-zA-Z0-9 _.-]+$";
1134   }
1138 function print_red()
1140   trigger_error("Use of obsolete print_red");
1141   /* Check number of arguments */
1142   if (func_num_args() < 1){
1143     return;
1144   }
1146   /* Get arguments, save string */
1147   $array = func_get_args();
1148   $string= $array[0];
1150   /* Step through arguments */
1151   for ($i= 1; $i<count($array); $i++){
1152     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1153   }
1155   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1156      the other case... */
1157   if($string !== NULL){
1158     if (preg_match("/"._("LDAP error:")."/", $string)){
1159       $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.");
1160     } else {
1161       if (!preg_match('/[.!?]$/', $string)){
1162         $string.= ".";
1163       }
1164       $string= preg_replace('/<br>/', ' ', $string);
1165       $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1166       $addmsg = "";
1167     }
1168     if(empty($addmsg)){
1169       $addmsg = _("Error");
1170     }
1171     msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1172     return;
1173   }else{
1174     return;
1175   }
1180 function gen_locked_message($user, $dn)
1182   global $plug, $config;
1184   session::set('dn', $dn);
1185   $remove= false;
1187   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1188   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1190     $LOCK_VARS_USED   = array();
1191     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1193     foreach($LOCK_VARS_TO_USE as $name){
1195       if(empty($name)){
1196         continue;
1197       }
1199       foreach($_POST as $Pname => $Pvalue){
1200         if(preg_match($name,$Pname)){
1201           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1202         }
1203       }
1205       foreach($_GET as $Pname => $Pvalue){
1206         if(preg_match($name,$Pname)){
1207           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1208         }
1209       }
1210     }
1211     session::set('LOCK_VARS_TO_USE',array());
1212     session::set('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1213   }
1215   /* Prepare and show template */
1216   $smarty= get_smarty();
1217   
1218   if(is_array($dn)){
1219     $msg = "<pre>";
1220     foreach($dn as $sub_dn){
1221       $msg .= "\n".$sub_dn.", ";
1222     }
1223     $msg = preg_replace("/, $/","</pre>",$msg);
1224   }else{
1225     $msg = $dn;
1226   }
1228   $smarty->assign ("dn", $msg);
1229   if ($remove){
1230     $smarty->assign ("action", _("Continue anyway"));
1231   } else {
1232     $smarty->assign ("action", _("Edit anyway"));
1233   }
1234   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1236   return ($smarty->fetch (get_template_path('islocked.tpl')));
1240 function to_string ($value)
1242   /* If this is an array, generate a text blob */
1243   if (is_array($value)){
1244     $ret= "";
1245     foreach ($value as $line){
1246       $ret.= $line."<br>\n";
1247     }
1248     return ($ret);
1249   } else {
1250     return ($value);
1251   }
1255 function get_printer_list()
1257   global $config;
1258   $res = array();
1259   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1260   foreach($data as $attrs ){
1261     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1262   }
1263   return $res;
1267 function show_errors($message)
1269   $complete= "";
1271   /* Assemble the message array to a plain string */
1272   foreach ($message as $error){
1273     if ($complete == ""){
1274       $complete= $error;
1275     } else {
1276       $complete= "$error<br>$complete";
1277     }
1278   }
1280   /* Fill ERROR variable with nice error dialog */
1281   msg_dialog::display(_("Error"), $complete, ERROR_DIALOG);
1285 function show_ldap_error($message, $addon= "")
1287   if (!preg_match("/Success/i", $message)){
1288     if ($addon == ""){
1289       msg_dialog::display(_("LDAP error:"), $message, ERROR_DIALOG);
1290     } else {
1291       if(!preg_match("/No such object/i",$message)){
1292         msg_dialog::display(_("LDAP error"), sprintf(_("Plugin '%s':%s"),"<i>".$addon."</i>", "<br><br>$message"),ERROR_DIALOG);
1293       }
1294     }
1295     return TRUE;
1296   } else {
1297     return FALSE;
1298   }
1302 function rewrite($s)
1304   global $REWRITE;
1306   foreach ($REWRITE as $key => $val){
1307     $s= preg_replace("/$key/", "$val", $s);
1308   }
1310   return ($s);
1314 function dn2base($dn)
1316   global $config;
1318   if (get_people_ou() != ""){
1319     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1320   }
1321   if (get_groups_ou() != ""){
1322     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1323   }
1324   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1326   return ($base);
1331 function check_command($cmdline)
1333   $cmd= preg_replace("/ .*$/", "", $cmdline);
1335   /* Check if command exists in filesystem */
1336   if (!file_exists($cmd)){
1337     return (FALSE);
1338   }
1340   /* Check if command is executable */
1341   if (!is_executable($cmd)){
1342     return (FALSE);
1343   }
1345   return (TRUE);
1349 function print_header($image, $headline, $info= "")
1351   $display= "<div class=\"plugtop\">\n";
1352   $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";
1353   $display.= "</div>\n";
1355   if ($info != ""){
1356     $display.= "<div class=\"pluginfo\">\n";
1357     $display.= "$info";
1358     $display.= "</div>\n";
1359   } else {
1360     $display.= "<div style=\"height:5px;\">\n";
1361     $display.= "&nbsp;";
1362     $display.= "</div>\n";
1363   }
1364   return ($display);
1368 function range_selector($dcnt,$start,$range=25,$post_var=false)
1371   /* Entries shown left and right from the selected entry */
1372   $max_entries= 10;
1374   /* Initialize and take care that max_entries is even */
1375   $output="";
1376   if ($max_entries & 1){
1377     $max_entries++;
1378   }
1380   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1381     $range= $_POST[$post_var];
1382   }
1384   /* Prevent output to start or end out of range */
1385   if ($start < 0 ){
1386     $start= 0 ;
1387   }
1388   if ($start >= $dcnt){
1389     $start= $range * (int)(($dcnt / $range) + 0.5);
1390   }
1392   $numpages= (($dcnt / $range));
1393   if(((int)($numpages))!=($numpages)){
1394     $numpages = (int)$numpages + 1;
1395   }
1396   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1397     return ("");
1398   }
1399   $ppage= (int)(($start / $range) + 0.5);
1402   /* Align selected page to +/- max_entries/2 */
1403   $begin= $ppage - $max_entries/2;
1404   $end= $ppage + $max_entries/2;
1406   /* Adjust begin/end, so that the selected value is somewhere in
1407      the middle and the size is max_entries if possible */
1408   if ($begin < 0){
1409     $end-= $begin + 1;
1410     $begin= 0;
1411   }
1412   if ($end > $numpages) {
1413     $end= $numpages;
1414   }
1415   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1416     $begin= $end - $max_entries;
1417   }
1419   if($post_var){
1420     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1421       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1422   }else{
1423     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1424   }
1426   /* Draw decrement */
1427   if ($start > 0 ) {
1428     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1429       (($start-$range))."\">".
1430       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1431   }
1433   /* Draw pages */
1434   for ($i= $begin; $i < $end; $i++) {
1435     if ($ppage == $i){
1436       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1437         validate($_GET['plug'])."&amp;start=".
1438         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1439     } else {
1440       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1441         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1442     }
1443   }
1445   /* Draw increment */
1446   if($start < ($dcnt-$range)) {
1447     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1448       (($start+($range)))."\">".
1449       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1450   }
1452   if(($post_var)&&($numpages)){
1453     $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()'>";
1454     foreach(array(20,50,100,200,"all") as $num){
1455       if($num == "all"){
1456         $var = 10000;
1457       }else{
1458         $var = $num;
1459       }
1460       if($var == $range){
1461         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1462       }else{  
1463         $output.="\n<option value='".$var."'>".$num."</option>";
1464       }
1465     }
1466     $output.=  "</select></td></tr></table></div>";
1467   }else{
1468     $output.= "</div>";
1469   }
1471   return($output);
1475 function apply_filter()
1477   $apply= "";
1479   $apply= ''.
1480     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1481     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1483   return ($apply);
1487 function back_to_main()
1489   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1490     _("Back").'"></p><input type="hidden" name="ignore">';
1492   return ($string);
1496 function normalize_netmask($netmask)
1498   /* Check for notation of netmask */
1499   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1500     $num= (int)($netmask);
1501     $netmask= "";
1503     for ($byte= 0; $byte<4; $byte++){
1504       $result=0;
1506       for ($i= 7; $i>=0; $i--){
1507         if ($num-- > 0){
1508           $result+= pow(2,$i);
1509         }
1510       }
1512       $netmask.= $result.".";
1513     }
1515     return (preg_replace('/\.$/', '', $netmask));
1516   }
1518   return ($netmask);
1522 function netmask_to_bits($netmask)
1524   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1525   $res= 0;
1527   for ($n= 0; $n<4; $n++){
1528     $start= 255;
1529     $name= "nm$n";
1531     for ($i= 0; $i<8; $i++){
1532       if ($start == (int)($$name)){
1533         $res+= 8 - $i;
1534         break;
1535       }
1536       $start-= pow(2,$i);
1537     }
1538   }
1540   return ($res);
1544 function recurse($rule, $variables)
1546   $result= array();
1548   if (!count($variables)){
1549     return array($rule);
1550   }
1552   reset($variables);
1553   $key= key($variables);
1554   $val= current($variables);
1555   unset ($variables[$key]);
1557   foreach($val as $possibility){
1558     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1559     $result= array_merge($result, recurse($nrule, $variables));
1560   }
1562   return ($result);
1566 function expand_id($rule, $attributes)
1568   /* Check for id rule */
1569   if(preg_match('/^id(:|#)\d+$/',$rule)){
1570     return (array("\{$rule}"));
1571   }
1573   /* Check for clean attribute */
1574   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1575     $rule= preg_replace('/^%/', '', $rule);
1576     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1577     return (array($val));
1578   }
1580   /* Check for attribute with parameters */
1581   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1582     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1583     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1584     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1585     $start= preg_replace ('/-.*$/', '', $param);
1586     $stop = preg_replace ('/^[^-]+-/', '', $param);
1588     /* Assemble results */
1589     $result= array();
1590     for ($i= $start; $i<= $stop; $i++){
1591       $result[]= substr($val, 0, $i);
1592     }
1593     return ($result);
1594   }
1596   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1597   return (array($rule));
1601 function gen_uids($rule, $attributes)
1603   global $config;
1605   /* Search for keys and fill the variables array with all 
1606      possible values for that key. */
1607   $part= "";
1608   $trigger= false;
1609   $stripped= "";
1610   $variables= array();
1612   for ($pos= 0; $pos < strlen($rule); $pos++){
1614     if ($rule[$pos] == "{" ){
1615       $trigger= true;
1616       $part= "";
1617       continue;
1618     }
1620     if ($rule[$pos] == "}" ){
1621       $variables[$pos]= expand_id($part, $attributes);
1622       $stripped.= "{".$pos."}";
1623       $trigger= false;
1624       continue;
1625     }
1627     if ($trigger){
1628       $part.= $rule[$pos];
1629     } else {
1630       $stripped.= $rule[$pos];
1631     }
1632   }
1634   /* Recurse through all possible combinations */
1635   $proposed= recurse($stripped, $variables);
1637   /* Get list of used ID's */
1638   $used= array();
1639   $ldap= $config->get_ldap_link();
1640   $ldap->cd($config->current['BASE']);
1641   $ldap->search('(uid=*)');
1643   while($attrs= $ldap->fetch()){
1644     $used[]= $attrs['uid'][0];
1645   }
1647   /* Remove used uids and watch out for id tags */
1648   $ret= array();
1649   foreach($proposed as $uid){
1651     /* Check for id tag and modify uid if needed */
1652     if(preg_match('/\{id:\d+}/',$uid)){
1653       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1655       for ($i= 0; $i < pow(10,$size); $i++){
1656         $number= sprintf("%0".$size."d", $i);
1657         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1658         if (!in_array($res, $used)){
1659           $uid= $res;
1660           break;
1661         }
1662       }
1663     }
1665   if(preg_match('/\{id#\d+}/',$uid)){
1666     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1668     while (true){
1669       mt_srand((double) microtime()*1000000);
1670       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1671       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1672       if (!in_array($res, $used)){
1673         $uid= $res;
1674         break;
1675       }
1676     }
1677   }
1679 /* Don't assign used ones */
1680 if (!in_array($uid, $used)){
1681   $ret[]= $uid;
1685 return(array_unique($ret));
1689 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1690    Need to convert... */
1691 function to_byte($value) {
1692   $value= strtolower(trim($value));
1694   if(!is_numeric(substr($value, -1))) {
1696     switch(substr($value, -1)) {
1697       case 'g':
1698         $mult= 1073741824;
1699         break;
1700       case 'm':
1701         $mult= 1048576;
1702         break;
1703       case 'k':
1704         $mult= 1024;
1705         break;
1706     }
1708     return ($mult * (int)substr($value, 0, -1));
1709   } else {
1710     return $value;
1711   }
1715 function in_array_ics($value, $items)
1717   if (!is_array($items)){
1718     return (FALSE);
1719   }
1721   foreach ($items as $item){
1722     if (strcasecmp($item, $value) == 0) {
1723       return (TRUE);
1724     }
1725   }
1727   return (FALSE);
1728
1731 function generate_alphabet($count= 10)
1733   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1734   $alphabet= "";
1735   $c= 0;
1737   /* Fill cells with charaters */
1738   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1739     if ($c == 0){
1740       $alphabet.= "<tr>";
1741     }
1743     $ch = mb_substr($characters, $i, 1, "UTF8");
1744     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1745       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1747     if ($c++ == $count){
1748       $alphabet.= "</tr>";
1749       $c= 0;
1750     }
1751   }
1753   /* Fill remaining cells */
1754   while ($c++ <= $count){
1755     $alphabet.= "<td>&nbsp;</td>";
1756   }
1758   return ($alphabet);
1762 function validate($string)
1764   return (strip_tags(preg_replace('/\0/', '', $string)));
1768 function get_gosa_version()
1770   global $svn_revision, $svn_path;
1772   /* Extract informations */
1773   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1775   /* Release or development? */
1776   if (preg_match('%/gosa/trunk/%', $svn_path)){
1777     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1778   } else {
1779     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1780     return (sprintf(_("GOsa $release"), $revision));
1781   }
1785 function rmdirRecursive($path, $followLinks=false) {
1786   $dir= opendir($path);
1787   while($entry= readdir($dir)) {
1788     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1789       unlink($path."/".$entry);
1790     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1791       rmdirRecursive($path."/".$entry);
1792     }
1793   }
1794   closedir($dir);
1795   return rmdir($path);
1799 function scan_directory($path,$sort_desc=false)
1801   $ret = false;
1803   /* is this a dir ? */
1804   if(is_dir($path)) {
1806     /* is this path a readable one */
1807     if(is_readable($path)){
1809       /* Get contents and write it into an array */   
1810       $ret = array();    
1812       $dir = opendir($path);
1814       /* Is this a correct result ?*/
1815       if($dir){
1816         while($fp = readdir($dir))
1817           $ret[]= $fp;
1818       }
1819     }
1820   }
1821   /* Sort array ascending , like scandir */
1822   sort($ret);
1824   /* Sort descending if parameter is sort_desc is set */
1825   if($sort_desc) {
1826     $ret = array_reverse($ret);
1827   }
1829   return($ret);
1833 function clean_smarty_compile_dir($directory)
1835   global $svn_revision;
1837   if(is_dir($directory) && is_readable($directory)) {
1838     // Set revision filename to REVISION
1839     $revision_file= $directory."/REVISION";
1841     /* Is there a stamp containing the current revision? */
1842     if(!file_exists($revision_file)) {
1843       // create revision file
1844       create_revision($revision_file, $svn_revision);
1845     } else {
1846       # check for "$config->...['CONFIG']/revision" and the
1847       # contents should match the revision number
1848       if(!compare_revision($revision_file, $svn_revision)){
1849         // If revision differs, clean compile directory
1850         foreach(scan_directory($directory) as $file) {
1851           if(($file==".")||($file=="..")) continue;
1852           if( is_file($directory."/".$file) &&
1853               is_writable($directory."/".$file)) {
1854             // delete file
1855             if(!unlink($directory."/".$file)) {
1856               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1857               // This should never be reached
1858             }
1859           } elseif(is_dir($directory."/".$file) &&
1860               is_writable($directory."/".$file)) {
1861             // Just recursively delete it
1862             rmdirRecursive($directory."/".$file);
1863           }
1864         }
1865         // We should now create a fresh revision file
1866         clean_smarty_compile_dir($directory);
1867       } else {
1868         // Revision matches, nothing to do
1869       }
1870     }
1871   } else {
1872     // Smarty compile dir is not accessible
1873     // (Smarty will warn about this)
1874   }
1878 function create_revision($revision_file, $revision)
1880   $result= false;
1882   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1883     if($fh= fopen($revision_file, "w")) {
1884       if(fwrite($fh, $revision)) {
1885         $result= true;
1886       }
1887     }
1888     fclose($fh);
1889   } else {
1890     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1891   }
1893   return $result;
1897 function compare_revision($revision_file, $revision)
1899   // false means revision differs
1900   $result= false;
1902   if(file_exists($revision_file) && is_readable($revision_file)) {
1903     // Open file
1904     if($fh= fopen($revision_file, "r")) {
1905       // Compare File contents with current revision
1906       if($revision == fread($fh, filesize($revision_file))) {
1907         $result= true;
1908       }
1909     } else {
1910       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1911     }
1912     // Close file
1913     fclose($fh);
1914   }
1916   return $result;
1920 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1922   $str = ""; // Our return value will be saved in this var
1924   $color  = dechex($percentage+150);
1925   $color2 = dechex(150 - $percentage);
1926   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1928   $progress = (int)(($percentage /100)*$width);
1930   /* Abort printing out percentage, if divs are to small */
1933   /* If theres a better solution for this, use it... */
1934   $str = "
1935     <div style=\" width:".($width)."px; 
1936     height:".($height)."px;
1937   background-color:#000000;
1938 padding:1px;\">
1940           <div style=\" width:".($width)."px;
1941         background-color:#$bgcolor;
1942 height:".($height)."px;\">
1944          <div style=\" width:".$progress."px;
1945 height:".$height."px;
1946        background-color:#".$color2.$color2.$color."; \">";
1949        if(($height >10)&&($showvalue)){
1950          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1951            <b>".$percentage."%</b>
1952            </font>";
1953        }
1955        $str.= "</div></div></div>";
1957        return($str);
1961 function array_key_ics($ikey, $items)
1963   /* Gather keys, make them lowercase */
1964   $tmp= array();
1965   foreach ($items as $key => $value){
1966     $tmp[strtolower($key)]= $key;
1967   }
1969   if (isset($tmp[strtolower($ikey)])){
1970     return($tmp[strtolower($ikey)]);
1971   }
1973   return ("");
1977 function array_differs($src, $dst)
1979   /* If the count is differing, the arrays differ */
1980   if (count ($src) != count ($dst)){
1981     return (TRUE);
1982   }
1984   /* So the count is the same - lets check the contents */
1985   $differs= FALSE;
1986   foreach($src as $value){
1987     if (!in_array($value, $dst)){
1988       $differs= TRUE;
1989     }
1990   }
1992   return ($differs);
1996 function saveFilter($a_filter, $values)
1998   if (isset($_POST['regexit'])){
1999     $a_filter["regex"]= $_POST['regexit'];
2001     foreach($values as $type){
2002       if (isset($_POST[$type])) {
2003         $a_filter[$type]= "checked";
2004       } else {
2005         $a_filter[$type]= "";
2006       }
2007     }
2008   }
2010   /* React on alphabet links if needed */
2011   if (isset($_GET['search'])){
2012     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2013     if ($s == "**"){
2014       $s= "*";
2015     }
2016     $a_filter['regex']= $s;
2017   }
2019   return ($a_filter);
2023 /* Escape all preg_* relevant characters */
2024 function normalizePreg($input)
2026   return (addcslashes($input, '[]()|/.*+-'));
2030 /* Escape all LDAP filter relevant characters */
2031 function normalizeLdap($input)
2033   return (addcslashes($input, '()|'));
2037 /* Resturns the difference between to microtime() results in float  */
2038 function get_MicroTimeDiff($start , $stop)
2040   $a = split("\ ",$start);
2041   $b = split("\ ",$stop);
2043   $secs = $b[1] - $a[1];
2044   $msecs= $b[0] - $a[0]; 
2046   $ret = (float) ($secs+ $msecs);
2047   return($ret);
2051 function get_base_dir()
2053   global $BASE_DIR;
2055   return $BASE_DIR;
2059 function obj_is_readable($dn, $object, $attribute)
2061   global $ui;
2063   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2067 function obj_is_writable($dn, $object, $attribute)
2069   global $ui;
2071   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2075 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2077   /* Initialize variables */
2078   $ret  = array("count" => 0);  // Set count to 0
2079   $next = true;                 // if false, then skip next loops and return
2080   $cnt  = 0;                    // Current number of loops
2081   $max  = 100;                  // Just for security, prevent looops
2082   $ldap = NULL;                 // To check if created result a valid
2083   $keep = "";                   // save last failed parse string
2085   /* Check each parsed dn in ldap ? */
2086   if($config!==NULL && $verify_in_ldap){
2087     $ldap = $config->get_ldap_link();
2088   }
2090   /* Lets start */
2091   $called = false;
2092   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2094     $cnt ++;
2095     if(!preg_match("/,/",$dn)){
2096       $next = false;
2097     }
2098     $object = preg_replace("/[,].*$/","",$dn);
2099     $dn     = preg_replace("/^[^,]+,/","",$dn);
2101     $called = true;
2103     /* Check if current dn is valid */
2104     if($ldap!==NULL){
2105       $ldap->cd($dn);
2106       $ldap->cat($dn,array("dn"));
2107       if($ldap->count()){
2108         $ret[]  = $keep.$object;
2109         $keep   = "";
2110       }else{
2111         $keep  .= $object.",";
2112       }
2113     }else{
2114       $ret[]  = $keep.$object;
2115       $keep   = "";
2116     }
2117   }
2119   /* No dn was posted */
2120   if($cnt == 0 && !empty($dn)){
2121     $ret[] = $dn;
2122   }
2124   /* Append the rest */
2125   $test = $keep.$dn;
2126   if($called && !empty($test)){
2127     $ret[] = $keep.$dn;
2128   }
2129   $ret['count'] = count($ret) - 1;
2131   return($ret);
2135 function get_base_from_hook($dn, $attrib)
2137   global $config;
2139   if (isset($config->current['BASE_HOOK'])){
2140     
2141     /* Call hook script - if present */
2142     $command= $config->current['BASE_HOOK'];
2144     if ($command != ""){
2145       $command.= " '".LDAP::fix($dn)."' $attrib";
2146       if (check_command($command)){
2147         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2148         exec($command, $output);
2149         if (preg_match("/^[0-9]+$/", $output[0])){
2150           return ($output[0]);
2151         } else {
2152           msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2153           return ($config->current['UIDBASE']);
2154         }
2155       } else {
2156         msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2157         return ($config->current['UIDBASE']);
2158       }
2160     } else {
2162       msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2163       return ($config->current['UIDBASE']);
2165     }
2166   }
2170 function check_schema_version($class, $version)
2172   return preg_match("/\(v$version\)/", $class['DESC']);
2176 function check_schema($cfg,$rfc2307bis = FALSE)
2178   $messages= array();
2180   /* Get objectclasses */
2181   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2182   $objectclasses = $ldap->get_objectclasses();
2183   if(count($objectclasses) == 0){
2184     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2185   }
2187   /* This is the default block used for each entry.
2188    *  to avoid unset indexes.
2189    */
2190   $def_check = array("REQUIRED_VERSION" => "0",
2191       "SCHEMA_FILES"     => array(),
2192       "CLASSES_REQUIRED" => array(),
2193       "STATUS"           => FALSE,
2194       "IS_MUST_HAVE"     => FALSE,
2195       "MSG"              => "",
2196       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2198   /* The gosa base schema */
2199   $checks['gosaObject'] = $def_check;
2200   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2201   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2202   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2203   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2205   /* GOsa Account class */
2206   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2207   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2208   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2209   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2210   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2212   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2213   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2214   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2215   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2216   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2217   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2219   /* Some other checks */
2220   foreach(array(
2221         "gosaCacheEntry"        => array("version" => "2.4"),
2222         "gosaDepartment"        => array("version" => "2.4"),
2223         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2224         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2225         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2226         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2227         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2228         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2229         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2230         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2231         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2232         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2233         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2234         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2235         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2236         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2237         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2238         "goLdapServer"          => array("version" => "2.4"),
2239         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2240         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2241         "goKrbServer"           => array("version" => "2.4"),
2242         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2243         ) as $name => $values){
2245           $checks[$name] = $def_check;
2246           if(isset($values['version'])){
2247             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2248           }
2249           if(isset($values['file'])){
2250             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2251           }
2252           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2253         }
2254   foreach($checks as $name => $value){
2255     foreach($value['CLASSES_REQUIRED'] as $class){
2257       if(!isset($objectclasses[$name])){
2258         $checks[$name]['STATUS'] = FALSE;
2259         if($value['IS_MUST_HAVE']){
2260           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2261         }else{
2262           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2263         }
2264       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2265         $checks[$name]['STATUS'] = FALSE;
2267         if($value['IS_MUST_HAVE']){
2268           $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2269         }else{
2270           $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2271         }
2272       }else{
2273         $checks[$name]['STATUS'] = TRUE;
2274         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2275       }
2276     }
2277   }
2279   $tmp = $objectclasses;
2281   /* The gosa base schema */
2282   $checks['posixGroup'] = $def_check;
2283   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2284   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2285   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2286   $checks['posixGroup']['STATUS']           = TRUE;
2287   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2288   $checks['posixGroup']['MSG']              = "";
2289   $checks['posixGroup']['INFO']             = "";
2291   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2292   if(isset($tmp['posixGroup'])){
2294     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2295       $checks['posixGroup']['STATUS']           = FALSE;
2296       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2297       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2298     }
2299     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2300       $checks['posixGroup']['STATUS']           = FALSE;
2301       $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2302       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2303     }
2304   }
2306   return($checks);
2310 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2312   $tmp = array(
2313         "de_DE" => "German",
2314         "fr_FR" => "French",
2315         "it_IT" => "Italian",
2316         "es_ES" => "Spanish",
2317         "en_US" => "English",
2318         "nl_NL" => "Dutch",
2319         "pl_PL" => "Polish",
2320         "sv_SE" => "Swedish",
2321         "zh_CN" => "Chinese",
2322         "ru_RU" => "Russian");
2323   
2324   $tmp2= array(
2325         "de_DE" => _("German"),
2326         "fr_FR" => _("French"),
2327         "it_IT" => _("Italian"),
2328         "es_ES" => _("Spanish"),
2329         "en_US" => _("English"),
2330         "nl_NL" => _("Dutch"),
2331         "pl_PL" => _("Polish"),
2332         "sv_SE" => _("Swedish"),
2333         "zh_CN" => _("Chinese"),
2334         "ru_RU" => _("Russian"));
2336   $ret = array();
2337   if($languages_in_own_language){
2339     $old_lang = setlocale(LC_ALL, 0);
2340     foreach($tmp as $key => $name){
2341       $lang = $key.".UTF-8";
2342       setlocale(LC_ALL, $lang);
2343       if($strip_region_tag){
2344         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2345       }else{
2346         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2347       }
2348     }
2349     setlocale(LC_ALL, $old_lang);
2350   }else{
2351     foreach($tmp as $key => $name){
2352       if($strip_region_tag){
2353         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2354       }else{
2355         $ret[$key] = _($name);
2356       }
2357     }
2358   }
2359   return($ret);
2363 /* Returns contents of the given POST variable and check magic quotes settings */
2364 function get_post($name)
2366   if(!isset($_POST[$name])){
2367     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2368     return(FALSE);
2369   }
2370   if(get_magic_quotes_gpc()){
2371     return(stripcslashes($_POST[$name]));
2372   }else{
2373     return($_POST[$name]);
2374   }
2378 /* Return class name in correct case */
2379 function get_correct_class_name($cls)
2381   global $class_mapping;
2382   if(isset($class_mapping) && is_array($class_mapping)){
2383     foreach($class_mapping as $class => $file){
2384       if(preg_match("/^".$cls."$/i",$class)){
2385         return($class);
2386       }
2387     }
2388   }
2389   return(FALSE);
2393 // change_password, changes the Password, of the given dn
2394 function change_password ($dn, $password, $mode=0, $hash= "")
2396   global $config;
2397   $newpass= "";
2399   /* Convert to lower. Methods are lowercase */
2400   $hash= strtolower($hash);
2402   // Get all available encryption Methods
2404   // NON STATIC CALL :)
2405   $tmp = new passwordMethod(session::get('config'));
2406   $available = $tmp->get_available_methods();
2408   // read current password entry for $dn, to detect the encryption Method
2409   $ldap       = $config->get_ldap_link();
2410   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2411   $attrs      = $ldap->fetch ();
2413   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2414   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2415     $deactivated = TRUE;
2416   }else{
2417     $deactivated = FALSE;
2418   }
2420   /* Is ensure that clear passwords will stay clear */
2421   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2422     $hash = "clear";
2423   }
2425   // Detect the encryption Method
2426   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2428     /* Check for supported algorithm */
2429     mt_srand((double) microtime()*1000000);
2431     /* Extract used hash */
2432     if ($hash == ""){
2433       $hash= strtolower($matches[1]);
2434     }
2436     $test = new  $available[$hash]($config);
2438   } else {
2439     // User MD5 by default
2440     $hash= "md5";
2441     $test = new  $available['md5']($config);
2442   }
2444   /* Feed password backends with information */
2445   $test->dn= $dn;
2446   $test->attrs= $attrs;
2447   $newpass= $test->generate_hash($password);
2449   // Update shadow timestamp?
2450   if (isset($attrs["shadowLastChange"][0])){
2451     $shadow= (int)(date("U") / 86400);
2452   } else {
2453     $shadow= 0;
2454   }
2456   // Write back modified entry
2457   $ldap->cd($dn);
2458   $attrs= array();
2460   // Not for groups
2461   if ($mode == 0){
2463     if ($shadow != 0){
2464       $attrs['shadowLastChange']= $shadow;
2465     }
2467     // Create SMB Password
2468     $attrs= generate_smb_nt_hash($password);
2469   }
2471  /* Readd ! if user was deactivated */
2472   if($deactivated){
2473     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2474   }
2476   $attrs['userPassword']= array();
2477   $attrs['userPassword']= $newpass;
2479   $ldap->modify($attrs);
2481   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2483   if ($ldap->error != 'Success') {
2484     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);
2485   } else {
2487     /* Run backend method for change/create */
2488     $test->set_password($password);
2490     /* Find postmodify entries for this class */
2491     $command= $config->search("password", "POSTMODIFY",array('menu'));
2493     if ($command != ""){
2494       /* Walk through attribute list */
2495       $command= preg_replace("/%userPassword/", $password, $command);
2496       $command= preg_replace("/%dn/", $dn, $command);
2498       if (check_command($command)){
2499         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2500         exec($command);
2501       } else {
2502         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2503         msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2504       }
2505     }
2506   }
2510 // Return something like array['sambaLMPassword']= "lalla..."
2511 function generate_smb_nt_hash($password)
2513   global $config;
2514   $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2515   @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2517   exec($tmp, $ar);
2518   flush();
2519   reset($ar);
2520   $hash= current($ar);
2521   if ($hash == "") {
2522     msg_dialog::display(_("Configuration error"), _("Setting for SMBHASH in gosa.conf is incorrect! Cannot change Samba password."), ERROR_DIALOG);
2523   } else {
2524     list($lm,$nt)= split (":", trim($hash));
2526     if ($config->current['SAMBAVERSION'] == 3) {
2527       $attrs['sambaLMPassword']= $lm;
2528       $attrs['sambaNTPassword']= $nt;
2529       $attrs['sambaPwdLastSet']= date('U');
2530       $attrs['sambaBadPasswordCount']= "0";
2531       $attrs['sambaBadPasswordTime']= "0";
2532     } else {
2533       $attrs['lmPassword']= $lm;
2534       $attrs['ntPassword']= $nt;
2535       $attrs['pwdLastSet']= date('U');
2536     }
2537     return($attrs);
2538   }
2542 function crypt_single($string,$enc_type )
2544   return( passwordMethod::crypt_single_str($string,$enc_type));
2548 function getEntryCSN($dn)
2550   global $config;
2551   if(empty($dn) || !is_object($config)){
2552     return("");
2553   }
2555   /* Get attribute that we should use as serial number */
2556   if(isset($config->current['UNIQ_IDENTIFIER'])){
2557     $attr = $config->current['UNIQ_IDENTIFIER'];
2558   }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2559     $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2560   }
2561   if(!empty($attr)){
2562     $ldap = $config->get_ldap_link();
2563     $ldap->cat($dn,array($attr));
2564     $csn = $ldap->fetch();
2565     if(isset($csn[$attr][0])){
2566       return($csn[$attr][0]);
2567     }
2568   }
2569   return("");
2573 /* Add a given objectClass to an attrs entry */
2574 function add_objectClass($classes, &$attrs)
2576   if (is_array($classes)){
2577     $list= $classes;
2578   } else {
2579     $list= array($classes);
2580   }
2582   foreach ($list as $class){
2583     $attrs['objectClass'][]= $class;
2584   }
2588 /* Removes a given objectClass from the attrs entry */
2589 function remove_objectClass($classes, &$attrs)
2591   if (isset($attrs['objectClass'])){
2592     /* Array? */
2593     if (is_array($classes)){
2594       $list= $classes;
2595     } else {
2596       $list= array($classes);
2597     }
2599     $tmp= array();
2600     foreach ($attrs['objectClass'] as $oc) {
2601       foreach ($list as $class){
2602         if ($oc != $class){
2603           $tmp[]= $oc;
2604         }
2605       }
2606     }
2607     $attrs['objectClass']= $tmp;
2608   }
2612 function display_error_page()
2614   $smarty= get_smarty();
2615   $smarty->display(get_template_path('headers.tpl'));
2616   echo "<body>".msg_dialog::get_dialogs()."</body></html>";
2617   exit();
2620 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2621 ?>