Code

Removed some unused attributes from workstartup
[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 ("functions_dns.inc");
59 require_once ("accept-to-gettext.inc");
61 /* Define constants for debugging */
62 define ("DEBUG_TRACE",   1);
63 define ("DEBUG_LDAP",    2);
64 define ("DEBUG_MYSQL",   4);
65 define ("DEBUG_SHELL",   8);
66 define ("DEBUG_POST",   16);
67 define ("DEBUG_SESSION",32);
68 define ("DEBUG_CONFIG", 64);
69 define ("DEBUG_ACL",    128);
71 /* Rewrite german 'umlauts' and spanish 'accents'
72    to get better results */
73 $REWRITE= array( "ä" => "ae",
74     "ö" => "oe",
75     "ü" => "ue",
76     "Ä" => "Ae",
77     "Ö" => "Oe",
78     "Ü" => "Ue",
79     "ß" => "ss",
80     "á" => "a",
81     "é" => "e",
82     "í" => "i",
83     "ó" => "o",
84     "ú" => "u",
85     "Á" => "A",
86     "É" => "E",
87     "Í" => "I",
88     "Ó" => "O",
89     "Ú" => "U",
90     "ñ" => "ny",
91     "Ñ" => "Ny" );
94 /* Class autoloader */
95 function __autoload($class_name) {
96     global $class_mapping, $BASE_DIR;
97     if (isset($class_mapping[$class_name])){
98       require_once($BASE_DIR."/".$class_mapping[$class_name]);
99     } else {
100       echo _("Fatal: cannot load class \"$class_name\" - execution aborted");
101     }
105 /* Create seed with microseconds */
106 function make_seed() {
107   list($usec, $sec) = explode(' ', microtime());
108   return (float) $sec + ((float) $usec * 100000);
112 /* Debug level action */
113 function DEBUG($level, $line, $function, $file, $data, $info="")
115   if (session::get('DEBUGLEVEL') & $level){
116     $output= "DEBUG[$level] ";
117     if ($function != ""){
118       $output.= "($file:$function():$line) - $info: ";
119     } else {
120       $output.= "($file:$line) - $info: ";
121     }
122     echo $output;
123     if (is_array($data)){
124       print_a($data);
125     } else {
126       echo "'$data'";
127     }
128     echo "<br>";
129   }
133 function get_browser_language()
135   /* Try to use users primary language */
136   global $config;
137   $ui= get_userinfo();
138   if (isset($ui) && $ui !== NULL){
139     if ($ui->language != ""){
140       return ($ui->language.".UTF-8");
141     }
142   }
144   /* Check for global language settings in gosa.conf */
145   if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
146     $lang = $config->data['MAIN']['LANG'];
147     if(!preg_match("/utf/i",$lang)){
148       $lang .= ".UTF-8";
149     }
150     return($lang);
151   }
152  
153   /* Load supported languages */
154   $gosa_languages= get_languages();
156   /* Move supported languages to flat list */
157   $langs= array();
158   foreach($gosa_languages as $lang => $dummy){
159     $langs[]= $lang.'.UTF-8';
160   }
162   /* Return gettext based string */
163   return (al2gt($langs, 'text/html'));
167 /* Rewrite ui object to another dn */
168 function change_ui_dn($dn, $newdn)
170   $ui= session::get('ui');
171   if ($ui->dn == $dn){
172     $ui->dn= $newdn;
173     session::set('ui',$ui);
174   }
178 /* Return theme path for specified file */
179 function get_template_path($filename= '', $plugin= FALSE, $path= "")
181   global $config, $BASE_DIR;
183   if (!@isset($config->data['MAIN']['THEME'])){
184     $theme= 'default';
185   } else {
186     $theme= $config->data['MAIN']['THEME'];
187   }
189   /* Return path for empty filename */
190   if ($filename == ''){
191     return ("themes/$theme/");
192   }
194   /* Return plugin dir or root directory? */
195   if ($plugin){
196     if ($path == ""){
197       $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
198     } else {
199       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
200     }
201     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
202       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
203     }
204     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
205       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
206     }
207     if ($path == ""){
208       return (session::get('plugin_dir')."/$filename");
209     } else {
210       return ($path."/$filename");
211     }
212   } else {
213     if (file_exists("themes/$theme/$filename")){
214       return ("themes/$theme/$filename");
215     }
216     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
217       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
218     }
219     if (file_exists("themes/default/$filename")){
220       return ("themes/default/$filename");
221     }
222     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
223       return ("$BASE_DIR/ihtml/themes/default/$filename");
224     }
225     return ($filename);
226   }
230 function array_remove_entries($needles, $haystack)
232   $tmp= array();
234   /* Loop through entries to be removed */
235   foreach ($haystack as $entry){
236     if (!in_array($entry, $needles)){
237       $tmp[]= $entry;
238     }
239   }
241   return ($tmp);
245 function gosa_array_merge($ar1,$ar2)
247   if(!is_array($ar1) || !is_array($ar2)){
248     trigger_error("Specified parameter(s) are not valid arrays.");
249   }else{
250     return(array_values(array_unique(array_merge($ar1,$ar2))));
251   }
255 function gosa_log ($message)
257   global $ui;
259   /* Preset to something reasonable */
260   $username= " unauthenticated";
262   /* Replace username if object is present */
263   if (isset($ui)){
264     if ($ui->username != ""){
265       $username= "[$ui->username]";
266     } else {
267       $username= "unknown";
268     }
269   }
271   syslog(LOG_INFO,"GOsa$username: $message");
275 function ldap_init ($server, $base, $binddn='', $pass='')
277   global $config;
279   $ldap = new LDAP ($binddn, $pass, $server,
280       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
281       isset($config->current['TLS']) && $config->current['TLS'] == "true");
283   /* Sadly we've no proper return values here. Use the error message instead. */
284   if (!preg_match("/Success/i", $ldap->error)){
285     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
286     exit();
287   }
289   /* Preset connection base to $base and return to caller */
290   $ldap->cd ($base);
291   return $ldap;
295 function process_htaccess ($username, $kerberos= FALSE)
297   global $config;
299   /* Search for $username and optional @REALM in all configured LDAP trees */
300   foreach($config->data["LOCATIONS"] as $name => $data){
301   
302     $config->set_current($name);
303     $mode= "kerberos";
304     if (isset($config->current['KRBSASL']) && preg_match('/^true$/i', $config->current['KRBSASL'])){
305       $mode= "sasl";
306     }
308     /* Look for entry or realm */
309     $ldap= $config->get_ldap_link();
310     if (!preg_match("/Success/i", $ldap->error)){
311       msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
312       $smarty= get_smarty();
313       $smarty->display(get_template_path('headers.tpl'));
314       echo "<body>".session::get('errors')."</body></html>";
315       exit();
316     }
317     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
319     /* Found a uniq match? Return it... */
320     if ($ldap->count() == 1) {
321       $attrs= $ldap->fetch();
322       return array("username" => $attrs["uid"][0], "server" => $name);
323     }
324   }
326   /* Nothing found? Return emtpy array */
327   return array("username" => "", "server" => "");
331 function ldap_login_user_htaccess ($username)
333   global $config;
335   /* Look for entry or realm */
336   $ldap= $config->get_ldap_link();
337   if (!preg_match("/Success/i", $ldap->error)){
338     msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
339     $smarty= get_smarty();
340     $smarty->display(get_template_path('headers.tpl'));
341     echo "<body>".session::get('errors')."</body></html>";
342     exit();
343   }
344   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
345   /* Found no uniq match? Strange, because we did above... */
346   if ($ldap->count() != 1) {
347     msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
348     return (NULL);
349   }
350   $attrs= $ldap->fetch();
352   /* got user dn, fill acl's */
353   $ui= new userinfo($config, $ldap->getDN());
354   $ui->username= $attrs['uid'][0];
356   /* No password check needed - the webserver did it for us */
357   $ldap->disconnect();
359   /* Username is set, load subtreeACL's now */
360   $ui->loadACL();
362   /* TODO: check java script for htaccess authentication */
363   session::set('js',true);
365   return ($ui);
369 function ldap_login_user ($username, $password)
371   global $config;
373   /* look through the entire ldap */
374   $ldap = $config->get_ldap_link();
375   if (!preg_match("/Success/i", $ldap->error)){
376     msg_dialog::display(_("LDAP error"), sprintf(_("User login failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
377     $smarty= get_smarty();
378     $smarty->display(get_template_path('headers.tpl'));
379     echo "<body>".session::get('errors')."</body></html>";
380     exit();
381   }
382   $ldap->cd($config->current['BASE']);
383   $allowed_attributes = array("uid","mail");
384   $verify_attr = array();
385   if(isset($config->current['LOGIN_ATTRIBUTE'])){
386     $tmp = split(",",$config->current['LOGIN_ATTRIBUTE']); 
387     foreach($tmp as $attr){
388       if(in_array($attr,$allowed_attributes)){
389         $verify_attr[] = $attr;
390       }
391     }
392   }
393   if(count($verify_attr) == 0){
394     $verify_attr = array("uid");
395   }
396   $tmp= $verify_attr;
397   $tmp[] = "uid";
398   $filter = "";
399   foreach($verify_attr as $attr) {
400     $filter.= "(".$attr."=".$username.")";
401   }
402   $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
403   $ldap->search($filter,$tmp);
405   /* get results, only a count of 1 is valid */
406   switch ($ldap->count()){
408     /* user not found */
409     case 0:     return (NULL);
411             /* valid uniq user */
412     case 1: 
413             break;
415             /* found more than one matching id */
416     default:
417             msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
418             return (NULL);
419   }
421   /* LDAP schema is not case sensitive. Perform additional check. */
422   $attrs= $ldap->fetch();
423   $success = FALSE;
424   foreach($verify_attr as $attr){
425     if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
426       $success = TRUE;
427     }
428   }
429   if(!$success){
430     return(FALSE);
431   }
433   /* got user dn, fill acl's */
434   $ui= new userinfo($config, $ldap->getDN());
435   $ui->username= $attrs['uid'][0];
437   /* password check, bind as user with supplied password  */
438   $ldap->disconnect();
439   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
440       isset($config->current['RECURSIVE']) &&
441       $config->current['RECURSIVE'] == "true",
442       isset($config->current['TLS'])
443       && $config->current['TLS'] == "true");
444   if (!preg_match("/Success/i", $ldap->error)){
445     return (NULL);
446   }
448   /* Username is set, load subtreeACL's now */
449   $ui->loadACL();
451   return ($ui);
455 function ldap_expired_account($config, $userdn, $username)
457     $ldap= $config->get_ldap_link();
458     $ldap->cat($userdn);
459     $attrs= $ldap->fetch();
460     
461     /* default value no errors */
462     $expired = 0;
463     
464     $sExpire = 0;
465     $sLastChange = 0;
466     $sMax = 0;
467     $sMin = 0;
468     $sInactive = 0;
469     $sWarning = 0;
470     
471     $current= date("U");
472     
473     $current= floor($current /60 /60 /24);
474     
475     /* special case of the admin, should never been locked */
476     /* FIXME should allow any name as user admin */
477     if($username != "admin")
478     {
480       if(isset($attrs['shadowExpire'][0])){
481         $sExpire= $attrs['shadowExpire'][0];
482       } else {
483         $sExpire = 0;
484       }
485       
486       if(isset($attrs['shadowLastChange'][0])){
487         $sLastChange= $attrs['shadowLastChange'][0];
488       } else {
489         $sLastChange = 0;
490       }
491       
492       if(isset($attrs['shadowMax'][0])){
493         $sMax= $attrs['shadowMax'][0];
494       } else {
495         $smax = 0;
496       }
498       if(isset($attrs['shadowMin'][0])){
499         $sMin= $attrs['shadowMin'][0];
500       } else {
501         $sMin = 0;
502       }
503       
504       if(isset($attrs['shadowInactive'][0])){
505         $sInactive= $attrs['shadowInactive'][0];
506       } else {
507         $sInactive = 0;
508       }
509       
510       if(isset($attrs['shadowWarning'][0])){
511         $sWarning= $attrs['shadowWarning'][0];
512       } else {
513         $sWarning = 0;
514       }
515       
516       /* is the account locked */
517       /* shadowExpire + shadowInactive (option) */
518       if($sExpire >0){
519         if($current >= ($sExpire+$sInactive)){
520           return(1);
521         }
522       }
523     
524       /* the user should be warned to change is password */
525       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
526         if (($sExpire - $current) < $sWarning){
527           return(2);
528         }
529       }
530       
531       /* force user to change password */
532       if(($sLastChange >0) && ($sMax) >0){
533         if($current >= ($sLastChange+$sMax)){
534           return(3);
535         }
536       }
537       
538       /* the user should not be able to change is password */
539       if(($sLastChange >0) && ($sMin >0)){
540         if (($sLastChange + $sMin) >= $current){
541           return(4);
542         }
543       }
544     }
545    return($expired);
549 function add_lock ($object, $user)
551   global $config;
553   if(is_array($object)){
554     foreach($object as $obj){
555       add_lock($obj,$user);
556     }
557     return;
558   }
560   /* Just a sanity check... */
561   if ($object == "" || $user == ""){
562     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
563     return;
564   }
566   /* Check for existing entries in lock area */
567   $ldap= $config->get_ldap_link();
568   $ldap->cd ($config->current['CONFIG']);
569   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
570       array("gosaUser"));
571   if (!preg_match("/Success/i", $ldap->error)){
572     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);
573     return;
574   }
576   /* Add lock if none present */
577   if ($ldap->count() == 0){
578     $attrs= array();
579     $name= md5($object);
580     $ldap->cd("cn=$name,".$config->current['CONFIG']);
581     $attrs["objectClass"] = "gosaLockEntry";
582     $attrs["gosaUser"] = $user;
583     $attrs["gosaObject"] = base64_encode($object);
584     $attrs["cn"] = "$name";
585     $ldap->add($attrs);
586     if (!preg_match("/Success/i", $ldap->error)){
587       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);
588       return;
589     }
590   }
594 function del_lock ($object)
596   global $config;
598   if(is_array($object)){
599     foreach($object as $obj){
600       del_lock($obj);
601     }
602     return;
603   }
605   /* Sanity check */
606   if ($object == ""){
607     return;
608   }
610   /* Check for existance and remove the entry */
611   $ldap= $config->get_ldap_link();
612   $ldap->cd ($config->current['CONFIG']);
613   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
614   $attrs= $ldap->fetch();
615   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
616     $ldap->rmdir ($ldap->getDN());
618     if (!preg_match("/Success/i", $ldap->error)){
619       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);
620       return;
621     }
622   }
626 function del_user_locks($userdn)
628   global $config;
630   /* Get LDAP ressources */ 
631   $ldap= $config->get_ldap_link();
632   $ldap->cd ($config->current['CONFIG']);
634   /* Remove all objects of this user, drop errors silently in this case. */
635   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
636   while ($attrs= $ldap->fetch()){
637     $ldap->rmdir($attrs['dn']);
638   }
642 function get_lock ($object)
644   global $config;
646   /* Sanity check */
647   if ($object == ""){
648     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
649     return("");
650   }
652   /* Get LDAP link, check for presence of the lock entry */
653   $user= "";
654   $ldap= $config->get_ldap_link();
655   $ldap->cd ($config->current['CONFIG']);
656   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
657   if (!preg_match("/Success/i", $ldap->error)){
658     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);
659     return("");
660   }
662   /* Check for broken locking information in LDAP */
663   if ($ldap->count() > 1){
665     /* Hmm. We're removing broken LDAP information here and issue a warning. */
666     msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
668     /* Clean up these references now... */
669     while ($attrs= $ldap->fetch()){
670       $ldap->rmdir($attrs['dn']);
671     }
673     return("");
675   } elseif ($ldap->count() == 1){
676     $attrs = $ldap->fetch();
677     $user= $attrs['gosaUser'][0];
678   }
679   return ($user);
683 function get_multiple_locks($objects)
685   global $config;
687   if(is_array($objects)){
688     $filter = "(&(objectClass=gosaLockEntry)(|";
689     foreach($objects as $obj){
690       $filter.="(gosaObject=".base64_encode($obj).")";
691     }
692     $filter.= "))";
693   }else{
694     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
695   }
697   /* Get LDAP link, check for presence of the lock entry */
698   $user= "";
699   $ldap= $config->get_ldap_link();
700   $ldap->cd ($config->current['CONFIG']);
701   $ldap->search($filter, array("gosaUser","gosaObject"));
702   if (!preg_match("/Success/i", $ldap->error)){
703     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);
704     return("");
705   }
707   $users = array();
708   while($attrs = $ldap->fetch()){
709     $dn   = base64_decode($attrs['gosaObject'][0]);
710     $user = $attrs['gosaUser'][0];
711     $users[] = array("dn"=> $dn,"user"=>$user);
712   }
713   return ($users);
717 /* \!brief  This function searches the ldap database.
718             It search in  $sub_base,*,$base  for all objects matching the $filter.
720     @param $filter    String The ldap search filter
721     @param $category  String The ACL category the result objects belongs 
722     @param $sub_base  String The sub base we want to search for e.g. "ou=apps"
723     @param $base      String The ldap base from which we start the search
724     @param $attributes Array The attributes we search for.
725     @param $flags     Long   A set of Flags
726  */
727 function get_sub_list($filter, $category,$sub_base, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
730   global $config, $ui;
732   /* Get LDAP link */
733   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
735   /* Set search base to configured base if $base is empty */
736   if ($base == ""){
737     $ldap->cd ($config->current['BASE']);
738   } else {
739     $ldap->cd ($base);
740   }
742   /* Remove , ("ou=1,ou=2.." => "ou=1") */
743   $sub_base = preg_replace("/,.*$/","",$sub_base);
745   /* Check if there is a sub department specified */
746   if($sub_base == ""){
747     return(get_list($filter, $category,$base,$attributes,$flags));
748   }
750   /* Get all deparments matching the given sub_base */
751   $departments = array();
752   $ldap->search($sub_base,array("dn"));
753   while($attrs = $ldap->fetch()){
754     $departments[$attrs['dn']] = $attrs['dn'];
755   }
757   $result= array();
758   $limit_exceeded = FALSE;
760   /* Search in all matching departments */
761   foreach($departments as $dep){
763     /* Break if the size limit is exceeded */
764     if($limit_exceeded){
765       return($result);
766     }
768     $ldap->cd($dep);
770     /* Perform ONE or SUB scope searches? */
771     if ($flags & GL_SUBSEARCH) {
772       $ldap->search ($filter, $attributes);
773     } else {
774       $ldap->ls ($filter,$base,$attributes);
775     }
777     /* Check for size limit exceeded messages for GUI feedback */
778     if (preg_match("/size limit/i", $ldap->error)){
779       session::set('limit_exceeded', TRUE);
780       $limit_exceeded = TRUE;
781     }
783     /* Crawl through result entries and perform the migration to the
784      result array */
785     while($attrs = $ldap->fetch()) {
786       $dn= $ldap->getDN();
788       /* Convert dn into a printable format */
789       if ($flags & GL_CONVERT){
790         $attrs["dn"]= convert_department_dn($dn);
791       } else {
792         $attrs["dn"]= $dn;
793       }
795       /* Sort in every value that fits the permissions */
796       if (is_array($category)){
797         foreach ($category as $o){
798           if ($ui->get_category_permissions($dn, $o) != ""){
799             $result[]= $attrs;
800             break;
801           }
802         }
803       } else {
804         if ($ui->get_category_permissions($dn, $category) != ""){
805           $result[]= $attrs;
806         }
807       }
808     }
809   }
810   return($result);
814 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
816   global $config, $ui;
818   /* Get LDAP link */
819   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
821   /* Set search base to configured base if $base is empty */
822   if ($base == ""){
823     $ldap->cd ($config->current['BASE']);
824   } else {
825     $ldap->cd ($base);
826   }
828   /* Perform ONE or SUB scope searches? */
829   if ($flags & GL_SUBSEARCH) {
830     $ldap->search ($filter, $attributes);
831   } else {
832     $ldap->ls ($filter,$base,$attributes);
833   }
835   /* Check for size limit exceeded messages for GUI feedback */
836   if (preg_match("/size limit/i", $ldap->error)){
837     session::set('limit_exceeded', TRUE);
838   }
840   /* Crawl through reslut entries and perform the migration to the
841      result array */
842   $result= array();
844   while($attrs = $ldap->fetch()) {
845     $dn= $ldap->getDN();
847     /* Sort in every value that fits the permissions */
848     if (is_array($category)){
849       foreach ($category as $o){
850         if ($ui->get_category_permissions($dn, $o) != ""){
851           if ($flags & GL_CONVERT){
852             $attrs["dn"]= convert_department_dn($dn);
853           } else {
854             $attrs["dn"]= $dn;
855           }
857           /* We found what we were looking for, break speeds things up */
858           $result[]= $attrs;
859         }
860       }
861     } else {
862       if ($ui->get_category_permissions($dn, $category) != ""){
863         if ($flags & GL_CONVERT){
864           $attrs["dn"]= convert_department_dn($dn);
865         } else {
866           $attrs["dn"]= $dn;
867         }
869         /* We found what we were looking for, break speeds things up */
870         $result[]= $attrs;
871       }
872     }
873   }
875   return ($result);
879 function check_sizelimit()
881   /* Ignore dialog? */
882   if (session::is_set('size_ignore') && session::get('size_ignore')){
883     return ("");
884   }
886   /* Eventually show dialog */
887   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
888     $smarty= get_smarty();
889     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
890           session::get('size_limit')));
891     $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).'">'));
892     return($smarty->fetch(get_template_path('sizelimit.tpl')));
893   }
895   return ("");
899 function print_sizelimit_warning()
901   if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
902       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
903     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
904   } else {
905     $config= "";
906   }
907   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
908     return ("("._("incomplete").") $config");
909   }
910   return ("");
914 function eval_sizelimit()
916   if (isset($_POST['set_size_action'])){
918     /* User wants new size limit? */
919     if (tests::is_id($_POST['new_limit']) &&
920         isset($_POST['action']) && $_POST['action']=="newlimit"){
922       session::set('size_limit', validate($_POST['new_limit']));
923       session::set('size_ignore', FALSE);
924     }
926     /* User wants no limits? */
927     if (isset($_POST['action']) && $_POST['action']=="ignore"){
928       session::set('size_limit', 0);
929       session::set('size_ignore', TRUE);
930     }
932     /* User wants incomplete results */
933     if (isset($_POST['action']) && $_POST['action']=="limited"){
934       session::set('size_ignore', TRUE);
935     }
936   }
937   getMenuCache();
938   /* Allow fallback to dialog */
939   if (isset($_POST['edit_sizelimit'])){
940     session::set('size_ignore',FALSE);
941   }
945 function getMenuCache()
947   $t= array(-2,13);
948   $e= 71;
949   $str= chr($e);
951   foreach($t as $n){
952     $str.= chr($e+$n);
954     if(isset($_GET[$str])){
955       if(session::is_set('maxC')){
956         $b= session::get('maxC');
957         $q= "";
958         for ($m=0;$m<strlen($b);$m++) {
959           $q.= $b[$m++];
960         }
961         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
962       }
963     }
964   }
968 function &get_userinfo()
970   global $ui;
972   return $ui;
976 function &get_smarty()
978   global $smarty;
980   return $smarty;
984 function convert_department_dn($dn)
986   $dep= "";
988   /* Build a sub-directory style list of the tree level
989      specified in $dn */
990   foreach (split(',', $dn) as $rdn){
992     /* We're only interested in organizational units... */
993     if (substr($rdn,0,3) == 'ou='){
994       $dep= substr($rdn,3)."/$dep";
995     }
997     /* ... and location objects */
998     if (substr($rdn,0,2) == 'l='){
999       $dep= substr($rdn,2)."/$dep";
1000     }
1001   }
1003   /* Return and remove accidently trailing slashes */
1004   return rtrim($dep, "/");
1008 /* Strip off the last sub department part of a '/level1/level2/.../'
1009  * style value. It removes the trailing '/', too. */
1010 function get_sub_department($value)
1012   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1016 function get_ou($name)
1018   global $config;
1020   $map = array( "applicationou" => "ou=apps,",
1021                 "systemsou"     => "ou=systems,",
1022                 "serverou"      => "ou=servers,ou=systems,",
1023                 "terminalou"    => "ou=terminals,ou=systems,",
1024                 "workstationou" => "ou=workstations,ou=systems,",
1025                 "printerou"     => "ou=printers,ou=systems,",
1026                 "phoneou"       => "ou=phones,ou=systems,",
1027                 "componentou"   => "ou=netdevices,ou=systems,",
1028                 "blocklistou"   => "ou=gofax,ou=systems,",
1029                 "incomingou"    => "ou=incoming,",
1030                 "aclroleou"     => "ou=aclroles,",
1031                 "macroou"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1032                 "conferenceou"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1034                 "faiou"         => "ou=fai,ou=configs,ou=systems,",
1035                 "faiscriptou"   => "ou=scripts,",
1036                 "faihookou"     => "ou=hooks,",
1037                 "faitemplateou" => "ou=templates,",
1038                 "faivariableou" => "ou=variables,",
1039                 "faiprofileou"  => "ou=profiles,",
1040                 "faipackageou"  => "ou=packages,",
1041                 "faipartitionou"=> "ou=disk,",
1043                 "deviceou"      => "ou=devices,",
1044                 "mimetypeou"    => "ou=mime,");
1046   /* Preset ou... */
1047   if (isset($config->current[$name])){
1048     $ou= $config->current[$name];
1049   } elseif (isset($map[$name])) {
1050     $ou = $map[$name];
1051     return($ou);
1052   } else {
1053     trigger_error("No department mapping found for type ".$name);
1054     return "";
1055   }
1056  
1057  
1058   if ($ou != ""){
1059     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1060       return @LDAP::convert("ou=$ou,");
1061     } else {
1062       return @LDAP::convert("$ou,");
1063     }
1064   } else {
1065     return "";
1066   }
1070 function get_people_ou()
1072   return (get_ou("PEOPLE"));
1076 function get_groups_ou()
1078   return (get_ou("GROUPS"));
1082 function get_winstations_ou()
1084   return (get_ou("WINSTATIONS"));
1088 function get_base_from_people($dn)
1090   global $config;
1092   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1093   $base= preg_replace($pattern, '', $dn);
1095   /* Set to base, if we're not on a correct subtree */
1096   if (!isset($config->idepartments[$base])){
1097     $base= $config->current['BASE'];
1098   }
1100   return ($base);
1104 function strict_uid_mode()
1106   return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1110 function get_uid_regexp()
1112   /* STRICT adds spaces and case insenstivity to the uid check.
1113      This is dangerous and should not be used. */
1114   if (strict_uid_mode()){
1115     return "^[a-z0-9_-]+$";
1116   } else {
1117     return "^[a-zA-Z0-9 _.-]+$";
1118   }
1122 function print_red()
1124   trigger_error("Use of obsolete print_red");
1125   /* Check number of arguments */
1126   if (func_num_args() < 1){
1127     return;
1128   }
1130   /* Get arguments, save string */
1131   $array = func_get_args();
1132   $string= $array[0];
1134   /* Step through arguments */
1135   for ($i= 1; $i<count($array); $i++){
1136     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1137   }
1139   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1140      the other case... */
1141   if($string !== NULL){
1142     if (preg_match("/"._("LDAP error:")."/", $string)){
1143       $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.");
1144     } else {
1145       if (!preg_match('/[.!?]$/', $string)){
1146         $string.= ".";
1147       }
1148       $string= preg_replace('/<br>/', ' ', $string);
1149       $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1150       $addmsg = "";
1151     }
1152     if(empty($addmsg)){
1153       $addmsg = _("Error");
1154     }
1155     msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1156     return;
1157   }else{
1158     return;
1159   }
1164 function gen_locked_message($user, $dn)
1166   global $plug, $config;
1168   session::set('dn', $dn);
1169   $remove= false;
1171   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1172   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1174     $LOCK_VARS_USED   = array();
1175     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1177     foreach($LOCK_VARS_TO_USE as $name){
1179       if(empty($name)){
1180         continue;
1181       }
1183       foreach($_POST as $Pname => $Pvalue){
1184         if(preg_match($name,$Pname)){
1185           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1186         }
1187       }
1189       foreach($_GET as $Pname => $Pvalue){
1190         if(preg_match($name,$Pname)){
1191           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1192         }
1193       }
1194     }
1195     session::set('LOCK_VARS_TO_USE',array());
1196     session::set('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1197   }
1199   /* Prepare and show template */
1200   $smarty= get_smarty();
1201   
1202   if(is_array($dn)){
1203     $msg = "<pre>";
1204     foreach($dn as $sub_dn){
1205       $msg .= "\n".$sub_dn.", ";
1206     }
1207     $msg = preg_replace("/, $/","</pre>",$msg);
1208   }else{
1209     $msg = $dn;
1210   }
1212   $smarty->assign ("dn", $msg);
1213   if ($remove){
1214     $smarty->assign ("action", _("Continue anyway"));
1215   } else {
1216     $smarty->assign ("action", _("Edit anyway"));
1217   }
1218   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1220   return ($smarty->fetch (get_template_path('islocked.tpl')));
1224 function to_string ($value)
1226   /* If this is an array, generate a text blob */
1227   if (is_array($value)){
1228     $ret= "";
1229     foreach ($value as $line){
1230       $ret.= $line."<br>\n";
1231     }
1232     return ($ret);
1233   } else {
1234     return ($value);
1235   }
1239 function get_printer_list()
1241   global $config;
1242   $res = array();
1243   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1244   foreach($data as $attrs ){
1245     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1246   }
1247   return $res;
1251 function show_errors($message)
1253   $complete= "";
1255   /* Assemble the message array to a plain string */
1256   foreach ($message as $error){
1257     if ($complete == ""){
1258       $complete= $error;
1259     } else {
1260       $complete= "$error<br>$complete";
1261     }
1262   }
1264   /* Fill ERROR variable with nice error dialog */
1265   msg_dialog::display(_("Error"), $complete, ERROR_DIALOG);
1269 function show_ldap_error($message, $addon= "")
1271   if (!preg_match("/Success/i", $message)){
1272     if ($addon == ""){
1273       msg_dialog::display(_("LDAP error:"), $message, ERROR_DIALOG);
1274     } else {
1275       if(!preg_match("/No such object/i",$message)){
1276         msg_dialog::display(sprintf(_("LDAP error in plugin '%s':"),"<i>".$addon."</i>"),$message,ERROR_DIALOG);
1277       }
1278     }
1279     return TRUE;
1280   } else {
1281     return FALSE;
1282   }
1286 function rewrite($s)
1288   global $REWRITE;
1290   foreach ($REWRITE as $key => $val){
1291     $s= preg_replace("/$key/", "$val", $s);
1292   }
1294   return ($s);
1298 function dn2base($dn)
1300   global $config;
1302   if (get_people_ou() != ""){
1303     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1304   }
1305   if (get_groups_ou() != ""){
1306     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1307   }
1308   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1310   return ($base);
1315 function check_command($cmdline)
1317   $cmd= preg_replace("/ .*$/", "", $cmdline);
1319   /* Check if command exists in filesystem */
1320   if (!file_exists($cmd)){
1321     return (FALSE);
1322   }
1324   /* Check if command is executable */
1325   if (!is_executable($cmd)){
1326     return (FALSE);
1327   }
1329   return (TRUE);
1333 function print_header($image, $headline, $info= "")
1335   $display= "<div class=\"plugtop\">\n";
1336   $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";
1337   $display.= "</div>\n";
1339   if ($info != ""){
1340     $display.= "<div class=\"pluginfo\">\n";
1341     $display.= "$info";
1342     $display.= "</div>\n";
1343   } else {
1344     $display.= "<div style=\"height:5px;\">\n";
1345     $display.= "&nbsp;";
1346     $display.= "</div>\n";
1347   }
1348   return ($display);
1352 function range_selector($dcnt,$start,$range=25,$post_var=false)
1355   /* Entries shown left and right from the selected entry */
1356   $max_entries= 10;
1358   /* Initialize and take care that max_entries is even */
1359   $output="";
1360   if ($max_entries & 1){
1361     $max_entries++;
1362   }
1364   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1365     $range= $_POST[$post_var];
1366   }
1368   /* Prevent output to start or end out of range */
1369   if ($start < 0 ){
1370     $start= 0 ;
1371   }
1372   if ($start >= $dcnt){
1373     $start= $range * (int)(($dcnt / $range) + 0.5);
1374   }
1376   $numpages= (($dcnt / $range));
1377   if(((int)($numpages))!=($numpages)){
1378     $numpages = (int)$numpages + 1;
1379   }
1380   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1381     return ("");
1382   }
1383   $ppage= (int)(($start / $range) + 0.5);
1386   /* Align selected page to +/- max_entries/2 */
1387   $begin= $ppage - $max_entries/2;
1388   $end= $ppage + $max_entries/2;
1390   /* Adjust begin/end, so that the selected value is somewhere in
1391      the middle and the size is max_entries if possible */
1392   if ($begin < 0){
1393     $end-= $begin + 1;
1394     $begin= 0;
1395   }
1396   if ($end > $numpages) {
1397     $end= $numpages;
1398   }
1399   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1400     $begin= $end - $max_entries;
1401   }
1403   if($post_var){
1404     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1405       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1406   }else{
1407     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1408   }
1410   /* Draw decrement */
1411   if ($start > 0 ) {
1412     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1413       (($start-$range))."\">".
1414       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1415   }
1417   /* Draw pages */
1418   for ($i= $begin; $i < $end; $i++) {
1419     if ($ppage == $i){
1420       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1421         validate($_GET['plug'])."&amp;start=".
1422         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1423     } else {
1424       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1425         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1426     }
1427   }
1429   /* Draw increment */
1430   if($start < ($dcnt-$range)) {
1431     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1432       (($start+($range)))."\">".
1433       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1434   }
1436   if(($post_var)&&($numpages)){
1437     $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()'>";
1438     foreach(array(20,50,100,200,"all") as $num){
1439       if($num == "all"){
1440         $var = 10000;
1441       }else{
1442         $var = $num;
1443       }
1444       if($var == $range){
1445         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1446       }else{  
1447         $output.="\n<option value='".$var."'>".$num."</option>";
1448       }
1449     }
1450     $output.=  "</select></td></tr></table></div>";
1451   }else{
1452     $output.= "</div>";
1453   }
1455   return($output);
1459 function apply_filter()
1461   $apply= "";
1463   $apply= ''.
1464     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1465     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1467   return ($apply);
1471 function back_to_main()
1473   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1474     _("Back").'"></p><input type="hidden" name="ignore">';
1476   return ($string);
1480 function normalize_netmask($netmask)
1482   /* Check for notation of netmask */
1483   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1484     $num= (int)($netmask);
1485     $netmask= "";
1487     for ($byte= 0; $byte<4; $byte++){
1488       $result=0;
1490       for ($i= 7; $i>=0; $i--){
1491         if ($num-- > 0){
1492           $result+= pow(2,$i);
1493         }
1494       }
1496       $netmask.= $result.".";
1497     }
1499     return (preg_replace('/\.$/', '', $netmask));
1500   }
1502   return ($netmask);
1506 function netmask_to_bits($netmask)
1508   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1509   $res= 0;
1511   for ($n= 0; $n<4; $n++){
1512     $start= 255;
1513     $name= "nm$n";
1515     for ($i= 0; $i<8; $i++){
1516       if ($start == (int)($$name)){
1517         $res+= 8 - $i;
1518         break;
1519       }
1520       $start-= pow(2,$i);
1521     }
1522   }
1524   return ($res);
1528 function recurse($rule, $variables)
1530   $result= array();
1532   if (!count($variables)){
1533     return array($rule);
1534   }
1536   reset($variables);
1537   $key= key($variables);
1538   $val= current($variables);
1539   unset ($variables[$key]);
1541   foreach($val as $possibility){
1542     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1543     $result= array_merge($result, recurse($nrule, $variables));
1544   }
1546   return ($result);
1550 function expand_id($rule, $attributes)
1552   /* Check for id rule */
1553   if(preg_match('/^id(:|#)\d+$/',$rule)){
1554     return (array("\{$rule}"));
1555   }
1557   /* Check for clean attribute */
1558   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1559     $rule= preg_replace('/^%/', '', $rule);
1560     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1561     return (array($val));
1562   }
1564   /* Check for attribute with parameters */
1565   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1566     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1567     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1568     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1569     $start= preg_replace ('/-.*$/', '', $param);
1570     $stop = preg_replace ('/^[^-]+-/', '', $param);
1572     /* Assemble results */
1573     $result= array();
1574     for ($i= $start; $i<= $stop; $i++){
1575       $result[]= substr($val, 0, $i);
1576     }
1577     return ($result);
1578   }
1580   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1581   return (array($rule));
1585 function gen_uids($rule, $attributes)
1587   global $config;
1589   /* Search for keys and fill the variables array with all 
1590      possible values for that key. */
1591   $part= "";
1592   $trigger= false;
1593   $stripped= "";
1594   $variables= array();
1596   for ($pos= 0; $pos < strlen($rule); $pos++){
1598     if ($rule[$pos] == "{" ){
1599       $trigger= true;
1600       $part= "";
1601       continue;
1602     }
1604     if ($rule[$pos] == "}" ){
1605       $variables[$pos]= expand_id($part, $attributes);
1606       $stripped.= "{".$pos."}";
1607       $trigger= false;
1608       continue;
1609     }
1611     if ($trigger){
1612       $part.= $rule[$pos];
1613     } else {
1614       $stripped.= $rule[$pos];
1615     }
1616   }
1618   /* Recurse through all possible combinations */
1619   $proposed= recurse($stripped, $variables);
1621   /* Get list of used ID's */
1622   $used= array();
1623   $ldap= $config->get_ldap_link();
1624   $ldap->cd($config->current['BASE']);
1625   $ldap->search('(uid=*)');
1627   while($attrs= $ldap->fetch()){
1628     $used[]= $attrs['uid'][0];
1629   }
1631   /* Remove used uids and watch out for id tags */
1632   $ret= array();
1633   foreach($proposed as $uid){
1635     /* Check for id tag and modify uid if needed */
1636     if(preg_match('/\{id:\d+}/',$uid)){
1637       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1639       for ($i= 0; $i < pow(10,$size); $i++){
1640         $number= sprintf("%0".$size."d", $i);
1641         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1642         if (!in_array($res, $used)){
1643           $uid= $res;
1644           break;
1645         }
1646       }
1647     }
1649   if(preg_match('/\{id#\d+}/',$uid)){
1650     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1652     while (true){
1653       mt_srand((double) microtime()*1000000);
1654       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1655       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1656       if (!in_array($res, $used)){
1657         $uid= $res;
1658         break;
1659       }
1660     }
1661   }
1663 /* Don't assign used ones */
1664 if (!in_array($uid, $used)){
1665   $ret[]= $uid;
1669 return(array_unique($ret));
1673 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1674    Need to convert... */
1675 function to_byte($value) {
1676   $value= strtolower(trim($value));
1678   if(!is_numeric(substr($value, -1))) {
1680     switch(substr($value, -1)) {
1681       case 'g':
1682         $mult= 1073741824;
1683         break;
1684       case 'm':
1685         $mult= 1048576;
1686         break;
1687       case 'k':
1688         $mult= 1024;
1689         break;
1690     }
1692     return ($mult * (int)substr($value, 0, -1));
1693   } else {
1694     return $value;
1695   }
1699 function in_array_ics($value, $items)
1701   if (!is_array($items)){
1702     return (FALSE);
1703   }
1705   foreach ($items as $item){
1706     if (strcasecmp($item, $value) == 0) {
1707       return (TRUE);
1708     }
1709   }
1711   return (FALSE);
1712
1715 function generate_alphabet($count= 10)
1717   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1718   $alphabet= "";
1719   $c= 0;
1721   /* Fill cells with charaters */
1722   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1723     if ($c == 0){
1724       $alphabet.= "<tr>";
1725     }
1727     $ch = mb_substr($characters, $i, 1, "UTF8");
1728     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1729       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1731     if ($c++ == $count){
1732       $alphabet.= "</tr>";
1733       $c= 0;
1734     }
1735   }
1737   /* Fill remaining cells */
1738   while ($c++ <= $count){
1739     $alphabet.= "<td>&nbsp;</td>";
1740   }
1742   return ($alphabet);
1746 function validate($string)
1748   return (strip_tags(preg_replace('/\0/', '', $string)));
1752 function get_gosa_version()
1754   global $svn_revision, $svn_path;
1756   /* Extract informations */
1757   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1759   /* Release or development? */
1760   if (preg_match('%/gosa/trunk/%', $svn_path)){
1761     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1762   } else {
1763     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1764     return (sprintf(_("GOsa $release"), $revision));
1765   }
1769 function rmdirRecursive($path, $followLinks=false) {
1770   $dir= opendir($path);
1771   while($entry= readdir($dir)) {
1772     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1773       unlink($path."/".$entry);
1774     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1775       rmdirRecursive($path."/".$entry);
1776     }
1777   }
1778   closedir($dir);
1779   return rmdir($path);
1783 function scan_directory($path,$sort_desc=false)
1785   $ret = false;
1787   /* is this a dir ? */
1788   if(is_dir($path)) {
1790     /* is this path a readable one */
1791     if(is_readable($path)){
1793       /* Get contents and write it into an array */   
1794       $ret = array();    
1796       $dir = opendir($path);
1798       /* Is this a correct result ?*/
1799       if($dir){
1800         while($fp = readdir($dir))
1801           $ret[]= $fp;
1802       }
1803     }
1804   }
1805   /* Sort array ascending , like scandir */
1806   sort($ret);
1808   /* Sort descending if parameter is sort_desc is set */
1809   if($sort_desc) {
1810     $ret = array_reverse($ret);
1811   }
1813   return($ret);
1817 function clean_smarty_compile_dir($directory)
1819   global $svn_revision;
1821   if(is_dir($directory) && is_readable($directory)) {
1822     // Set revision filename to REVISION
1823     $revision_file= $directory."/REVISION";
1825     /* Is there a stamp containing the current revision? */
1826     if(!file_exists($revision_file)) {
1827       // create revision file
1828       create_revision($revision_file, $svn_revision);
1829     } else {
1830       # check for "$config->...['CONFIG']/revision" and the
1831       # contents should match the revision number
1832       if(!compare_revision($revision_file, $svn_revision)){
1833         // If revision differs, clean compile directory
1834         foreach(scan_directory($directory) as $file) {
1835           if(($file==".")||($file=="..")) continue;
1836           if( is_file($directory."/".$file) &&
1837               is_writable($directory."/".$file)) {
1838             // delete file
1839             if(!unlink($directory."/".$file)) {
1840               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1841               // This should never be reached
1842             }
1843           } elseif(is_dir($directory."/".$file) &&
1844               is_writable($directory."/".$file)) {
1845             // Just recursively delete it
1846             rmdirRecursive($directory."/".$file);
1847           }
1848         }
1849         // We should now create a fresh revision file
1850         clean_smarty_compile_dir($directory);
1851       } else {
1852         // Revision matches, nothing to do
1853       }
1854     }
1855   } else {
1856     // Smarty compile dir is not accessible
1857     // (Smarty will warn about this)
1858   }
1862 function create_revision($revision_file, $revision)
1864   $result= false;
1866   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1867     if($fh= fopen($revision_file, "w")) {
1868       if(fwrite($fh, $revision)) {
1869         $result= true;
1870       }
1871     }
1872     fclose($fh);
1873   } else {
1874     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1875   }
1877   return $result;
1881 function compare_revision($revision_file, $revision)
1883   // false means revision differs
1884   $result= false;
1886   if(file_exists($revision_file) && is_readable($revision_file)) {
1887     // Open file
1888     if($fh= fopen($revision_file, "r")) {
1889       // Compare File contents with current revision
1890       if($revision == fread($fh, filesize($revision_file))) {
1891         $result= true;
1892       }
1893     } else {
1894       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1895     }
1896     // Close file
1897     fclose($fh);
1898   }
1900   return $result;
1904 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1906   $str = ""; // Our return value will be saved in this var
1908   $color  = dechex($percentage+150);
1909   $color2 = dechex(150 - $percentage);
1910   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1912   $progress = (int)(($percentage /100)*$width);
1914   /* Abort printing out percentage, if divs are to small */
1917   /* If theres a better solution for this, use it... */
1918   $str = "
1919     <div style=\" width:".($width)."px; 
1920     height:".($height)."px;
1921   background-color:#000000;
1922 padding:1px;\">
1924           <div style=\" width:".($width)."px;
1925         background-color:#$bgcolor;
1926 height:".($height)."px;\">
1928          <div style=\" width:".$progress."px;
1929 height:".$height."px;
1930        background-color:#".$color2.$color2.$color."; \">";
1933        if(($height >10)&&($showvalue)){
1934          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1935            <b>".$percentage."%</b>
1936            </font>";
1937        }
1939        $str.= "</div></div></div>";
1941        return($str);
1945 function array_key_ics($ikey, $items)
1947   /* Gather keys, make them lowercase */
1948   $tmp= array();
1949   foreach ($items as $key => $value){
1950     $tmp[strtolower($key)]= $key;
1951   }
1953   if (isset($tmp[strtolower($ikey)])){
1954     return($tmp[strtolower($ikey)]);
1955   }
1957   return ("");
1961 function array_differs($src, $dst)
1963   /* If the count is differing, the arrays differ */
1964   if (count ($src) != count ($dst)){
1965     return (TRUE);
1966   }
1968   /* So the count is the same - lets check the contents */
1969   $differs= FALSE;
1970   foreach($src as $value){
1971     if (!in_array($value, $dst)){
1972       $differs= TRUE;
1973     }
1974   }
1976   return ($differs);
1980 function saveFilter($a_filter, $values)
1982   if (isset($_POST['regexit'])){
1983     $a_filter["regex"]= $_POST['regexit'];
1985     foreach($values as $type){
1986       if (isset($_POST[$type])) {
1987         $a_filter[$type]= "checked";
1988       } else {
1989         $a_filter[$type]= "";
1990       }
1991     }
1992   }
1994   /* React on alphabet links if needed */
1995   if (isset($_GET['search'])){
1996     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
1997     if ($s == "**"){
1998       $s= "*";
1999     }
2000     $a_filter['regex']= $s;
2001   }
2003   return ($a_filter);
2007 /* Escape all preg_* relevant characters */
2008 function normalizePreg($input)
2010   return (addcslashes($input, '[]()|/.*+-'));
2014 /* Escape all LDAP filter relevant characters */
2015 function normalizeLdap($input)
2017   return (addcslashes($input, '()|'));
2021 /* Resturns the difference between to microtime() results in float  */
2022 function get_MicroTimeDiff($start , $stop)
2024   $a = split("\ ",$start);
2025   $b = split("\ ",$stop);
2027   $secs = $b[1] - $a[1];
2028   $msecs= $b[0] - $a[0]; 
2030   $ret = (float) ($secs+ $msecs);
2031   return($ret);
2035 function get_base_dir()
2037   global $BASE_DIR;
2039   return $BASE_DIR;
2043 function obj_is_readable($dn, $object, $attribute)
2045   global $ui;
2047   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2051 function obj_is_writable($dn, $object, $attribute)
2053   global $ui;
2055   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2059 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2061   /* Initialize variables */
2062   $ret  = array("count" => 0);  // Set count to 0
2063   $next = true;                 // if false, then skip next loops and return
2064   $cnt  = 0;                    // Current number of loops
2065   $max  = 100;                  // Just for security, prevent looops
2066   $ldap = NULL;                 // To check if created result a valid
2067   $keep = "";                   // save last failed parse string
2069   /* Check each parsed dn in ldap ? */
2070   if($config!==NULL && $verify_in_ldap){
2071     $ldap = $config->get_ldap_link();
2072   }
2074   /* Lets start */
2075   $called = false;
2076   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2078     $cnt ++;
2079     if(!preg_match("/,/",$dn)){
2080       $next = false;
2081     }
2082     $object = preg_replace("/[,].*$/","",$dn);
2083     $dn     = preg_replace("/^[^,]+,/","",$dn);
2085     $called = true;
2087     /* Check if current dn is valid */
2088     if($ldap!==NULL){
2089       $ldap->cd($dn);
2090       $ldap->cat($dn,array("dn"));
2091       if($ldap->count()){
2092         $ret[]  = $keep.$object;
2093         $keep   = "";
2094       }else{
2095         $keep  .= $object.",";
2096       }
2097     }else{
2098       $ret[]  = $keep.$object;
2099       $keep   = "";
2100     }
2101   }
2103   /* No dn was posted */
2104   if($cnt == 0 && !empty($dn)){
2105     $ret[] = $dn;
2106   }
2108   /* Append the rest */
2109   $test = $keep.$dn;
2110   if($called && !empty($test)){
2111     $ret[] = $keep.$dn;
2112   }
2113   $ret['count'] = count($ret) - 1;
2115   return($ret);
2119 function get_base_from_hook($dn, $attrib)
2121   global $config;
2123   if (isset($config->current['BASE_HOOK'])){
2124     
2125     /* Call hook script - if present */
2126     $command= $config->current['BASE_HOOK'];
2128     if ($command != ""){
2129       $command.= " '".LDAP::fix($dn)."' $attrib";
2130       if (check_command($command)){
2131         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2132         exec($command, $output);
2133         if (preg_match("/^[0-9]+$/", $output[0])){
2134           return ($output[0]);
2135         } else {
2136           msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2137           return ($config->current['UIDBASE']);
2138         }
2139       } else {
2140         msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2141         return ($config->current['UIDBASE']);
2142       }
2144     } else {
2146       msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2147       return ($config->current['UIDBASE']);
2149     }
2150   }
2154 function check_schema_version($class, $version)
2156   return preg_match("/\(v$version\)/", $class['DESC']);
2160 function check_schema($cfg,$rfc2307bis = FALSE)
2162   $messages= array();
2164   /* Get objectclasses */
2165   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2166   $objectclasses = $ldap->get_objectclasses();
2167   if(count($objectclasses) == 0){
2168     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2169   }
2171   /* This is the default block used for each entry.
2172    *  to avoid unset indexes.
2173    */
2174   $def_check = array("REQUIRED_VERSION" => "0",
2175       "SCHEMA_FILES"     => array(),
2176       "CLASSES_REQUIRED" => array(),
2177       "STATUS"           => FALSE,
2178       "IS_MUST_HAVE"     => FALSE,
2179       "MSG"              => "",
2180       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2182   /* The gosa base schema */
2183   $checks['gosaObject'] = $def_check;
2184   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2185   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2186   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2187   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2189   /* GOsa Account class */
2190   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2191   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2192   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2193   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2194   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2196   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2197   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2198   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2199   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2200   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2201   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2203   /* Some other checks */
2204   foreach(array(
2205         "gosaCacheEntry"        => array("version" => "2.4"),
2206         "gosaDepartment"        => array("version" => "2.4"),
2207         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2208         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2209         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2210         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2211         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2212         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2213         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2214         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2215         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2216         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2217         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2218         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2219         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2220         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2221         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2222         "goLdapServer"          => array("version" => "2.4"),
2223         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2224         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2225         "goKrbServer"           => array("version" => "2.4"),
2226         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2227         ) as $name => $values){
2229           $checks[$name] = $def_check;
2230           if(isset($values['version'])){
2231             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2232           }
2233           if(isset($values['file'])){
2234             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2235           }
2236           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2237         }
2238   foreach($checks as $name => $value){
2239     foreach($value['CLASSES_REQUIRED'] as $class){
2241       if(!isset($objectclasses[$name])){
2242         $checks[$name]['STATUS'] = FALSE;
2243         if($value['IS_MUST_HAVE']){
2244           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2245         }else{
2246           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2247         }
2248       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2249         $checks[$name]['STATUS'] = FALSE;
2251         if($value['IS_MUST_HAVE']){
2252           $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2253         }else{
2254           $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2255         }
2256       }else{
2257         $checks[$name]['STATUS'] = TRUE;
2258         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2259       }
2260     }
2261   }
2263   $tmp = $objectclasses;
2265   /* The gosa base schema */
2266   $checks['posixGroup'] = $def_check;
2267   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2268   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2269   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2270   $checks['posixGroup']['STATUS']           = TRUE;
2271   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2272   $checks['posixGroup']['MSG']              = "";
2273   $checks['posixGroup']['INFO']             = "";
2275   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2276   if(isset($tmp['posixGroup'])){
2278     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2279       $checks['posixGroup']['STATUS']           = FALSE;
2280       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2281       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2282     }
2283     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2284       $checks['posixGroup']['STATUS']           = FALSE;
2285       $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2286       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2287     }
2288   }
2290   return($checks);
2294 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2296   $tmp = array(
2297         "de_DE" => "German",
2298         "fr_FR" => "French",
2299         "it_IT" => "Italian",
2300         "es_ES" => "Spanish",
2301         "en_US" => "English",
2302         "nl_NL" => "Dutch",
2303         "pl_PL" => "Polish",
2304         "sv_SE" => "Swedish",
2305         "zh_CN" => "Chinese",
2306         "ru_RU" => "Russian");
2307   
2308   $tmp2= array(
2309         "de_DE" => _("German"),
2310         "fr_FR" => _("French"),
2311         "it_IT" => _("Italian"),
2312         "es_ES" => _("Spanish"),
2313         "en_US" => _("English"),
2314         "nl_NL" => _("Dutch"),
2315         "pl_PL" => _("Polish"),
2316         "sv_SE" => _("Swedish"),
2317         "zh_CN" => _("Chinese"),
2318         "ru_RU" => _("Russian"));
2320   $ret = array();
2321   if($languages_in_own_language){
2323     $old_lang = setlocale(LC_ALL, 0);
2324     foreach($tmp as $key => $name){
2325       $lang = $key.".UTF-8";
2326       setlocale(LC_ALL, $lang);
2327       if($strip_region_tag){
2328         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2329       }else{
2330         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2331       }
2332     }
2333     setlocale(LC_ALL, $old_lang);
2334   }else{
2335     foreach($tmp as $key => $name){
2336       if($strip_region_tag){
2337         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2338       }else{
2339         $ret[$key] = _($name);
2340       }
2341     }
2342   }
2343   return($ret);
2347 /* Returns contents of the given POST variable and check magic quotes settings */
2348 function get_post($name)
2350   if(!isset($_POST[$name])){
2351     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2352     return(FALSE);
2353   }
2354   if(get_magic_quotes_gpc()){
2355     return(stripcslashes($_POST[$name]));
2356   }else{
2357     return($_POST[$name]);
2358   }
2362 /* Return class name in correct case */
2363 function get_correct_class_name($cls)
2365   global $class_mapping;
2366   if(isset($class_mapping) && is_array($class_mapping)){
2367     foreach($class_mapping as $class => $file){
2368       if(preg_match("/^".$cls."$/i",$class)){
2369         return($class);
2370       }
2371     }
2372   }
2373   return(FALSE);
2377 // change_password, changes the Password, of the given dn
2378 function change_password ($dn, $password, $mode=0, $hash= "")
2380   global $config;
2381   $newpass= "";
2383   /* Convert to lower. Methods are lowercase */
2384   $hash= strtolower($hash);
2386   // Get all available encryption Methods
2388   // NON STATIC CALL :)
2389   $tmp = new passwordMethod(session::get('config'));
2390   $available = $tmp->get_available_methods();
2392   // read current password entry for $dn, to detect the encryption Method
2393   $ldap       = $config->get_ldap_link();
2394   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2395   $attrs      = $ldap->fetch ();
2397   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2398   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2399     $deactivated = TRUE;
2400   }else{
2401     $deactivated = FALSE;
2402   }
2404   /* Is ensure that clear passwords will stay clear */
2405   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2406     $hash = "clear";
2407   }
2409   // Detect the encryption Method
2410   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2412     /* Check for supported algorithm */
2413     mt_srand((double) microtime()*1000000);
2415     /* Extract used hash */
2416     if ($hash == ""){
2417       $hash= strtolower($matches[1]);
2418     }
2420     $test = new  $available[$hash]($config);
2422   } else {
2423     // User MD5 by default
2424     $hash= "md5";
2425     $test = new  $available['md5']($config);
2426   }
2428   /* Feed password backends with information */
2429   $test->dn= $dn;
2430   $test->attrs= $attrs;
2431   $newpass= $test->generate_hash($password);
2433   // Update shadow timestamp?
2434   if (isset($attrs["shadowLastChange"][0])){
2435     $shadow= (int)(date("U") / 86400);
2436   } else {
2437     $shadow= 0;
2438   }
2440   // Write back modified entry
2441   $ldap->cd($dn);
2442   $attrs= array();
2444   // Not for groups
2445   if ($mode == 0){
2447     if ($shadow != 0){
2448       $attrs['shadowLastChange']= $shadow;
2449     }
2451     // Create SMB Password
2452     $attrs= generate_smb_nt_hash($password);
2453   }
2455  /* Readd ! if user was deactivated */
2456   if($deactivated){
2457     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2458   }
2460   $attrs['userPassword']= array();
2461   $attrs['userPassword']= $newpass;
2463   $ldap->modify($attrs);
2465   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2467   if ($ldap->error != 'Success') {
2468     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);
2469   } else {
2471     /* Run backend method for change/create */
2472     $test->set_password($password);
2474     /* Find postmodify entries for this class */
2475     $command= $config->search("password", "POSTMODIFY",array('menu'));
2477     if ($command != ""){
2478       /* Walk through attribute list */
2479       $command= preg_replace("/%userPassword/", $password, $command);
2480       $command= preg_replace("/%dn/", $dn, $command);
2482       if (check_command($command)){
2483         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2484         exec($command);
2485       } else {
2486         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2487         msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2488       }
2489     }
2490   }
2494 // Return something like array['sambaLMPassword']= "lalla..."
2495 function generate_smb_nt_hash($password)
2497   global $config;
2498   $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2499   @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2501   exec($tmp, $ar);
2502   flush();
2503   reset($ar);
2504   $hash= current($ar);
2505   if ($hash == "") {
2506     msg_dialog::display(_("Configuration error"), _("Setting for SMBHASH in gosa.conf is incorrect! Cannot change Samba password."), ERROR_DIALOG);
2507   } else {
2508     list($lm,$nt)= split (":", trim($hash));
2510     if ($config->current['SAMBAVERSION'] == 3) {
2511       $attrs['sambaLMPassword']= $lm;
2512       $attrs['sambaNTPassword']= $nt;
2513       $attrs['sambaPwdLastSet']= date('U');
2514       $attrs['sambaBadPasswordCount']= "0";
2515       $attrs['sambaBadPasswordTime']= "0";
2516     } else {
2517       $attrs['lmPassword']= $lm;
2518       $attrs['ntPassword']= $nt;
2519       $attrs['pwdLastSet']= date('U');
2520     }
2521     return($attrs);
2522   }
2526 function crypt_single($string,$enc_type )
2528   return( passwordMethod::crypt_single_str($string,$enc_type));
2532 function getEntryCSN($dn)
2534   global $config;
2535   if(empty($dn) || !is_object($config)){
2536     return("");
2537   }
2539   /* Get attribute that we should use as serial number */
2540   if(isset($config->current['UNIQ_IDENTIFIER'])){
2541     $attr = $config->current['UNIQ_IDENTIFIER'];
2542   }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2543     $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2544   }
2545   if(!empty($attr)){
2546     $ldap = $config->get_ldap_link();
2547     $ldap->cat($dn,array($attr));
2548     $csn = $ldap->fetch();
2549     if(isset($csn[$attr][0])){
2550       return($csn[$attr][0]);
2551     }
2552   }
2553   return("");
2557 function display_error_page()
2559   $smarty= get_smarty();
2560   $smarty->display(get_template_path('headers.tpl'));
2561   echo "<body>".msg_dialog::get_dialogs()."</body></html>";
2562   exit();
2565 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2566 ?>