Code

8f45c429bada51671e6b1fbff1ca8cfb94dd8810
[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 _("Fatal: cannot load class \"$class_name\" - execution aborted");
100     }
104 /* Create seed with microseconds */
105 function make_seed() {
106   list($usec, $sec) = explode(' ', microtime());
107   return (float) $sec + ((float) $usec * 100000);
111 /* Debug level action */
112 function DEBUG($level, $line, $function, $file, $data, $info="")
114   if (session::get('DEBUGLEVEL') & $level){
115     $output= "DEBUG[$level] ";
116     if ($function != ""){
117       $output.= "($file:$function():$line) - $info: ";
118     } else {
119       $output.= "($file:$line) - $info: ";
120     }
121     echo $output;
122     if (is_array($data)){
123       print_a($data);
124     } else {
125       echo "'$data'";
126     }
127     echo "<br>";
128   }
132 function get_browser_language()
134   /* Try to use users primary language */
135   global $config;
136   $ui= get_userinfo();
137   if (isset($ui) && $ui !== NULL){
138     if ($ui->language != ""){
139       return ($ui->language.".UTF-8");
140     }
141   }
143   /* Check for global language settings in gosa.conf */
144   if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
145     $lang = $config->data['MAIN']['LANG'];
146     if(!preg_match("/utf/i",$lang)){
147       $lang .= ".UTF-8";
148     }
149     return($lang);
150   }
151  
152   /* Load supported languages */
153   $gosa_languages= get_languages();
155   /* Move supported languages to flat list */
156   $langs= array();
157   foreach($gosa_languages as $lang => $dummy){
158     $langs[]= $lang.'.UTF-8';
159   }
161   /* Return gettext based string */
162   return (al2gt($langs, 'text/html'));
166 /* Rewrite ui object to another dn */
167 function change_ui_dn($dn, $newdn)
169   $ui= session::get('ui');
170   if ($ui->dn == $dn){
171     $ui->dn= $newdn;
172     session::set('ui',$ui);
173   }
177 /* Return theme path for specified file */
178 function get_template_path($filename= '', $plugin= FALSE, $path= "")
180   global $config, $BASE_DIR;
182   if (!@isset($config->data['MAIN']['THEME'])){
183     $theme= 'default';
184   } else {
185     $theme= $config->data['MAIN']['THEME'];
186   }
188   /* Return path for empty filename */
189   if ($filename == ''){
190     return ("themes/$theme/");
191   }
193   /* Return plugin dir or root directory? */
194   if ($plugin){
195     if ($path == ""){
196       $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
197     } else {
198       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
199     }
200     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
201       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
202     }
203     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
204       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
205     }
206     if ($path == ""){
207       return (session::get('plugin_dir')."/$filename");
208     } else {
209       return ($path."/$filename");
210     }
211   } else {
212     if (file_exists("themes/$theme/$filename")){
213       return ("themes/$theme/$filename");
214     }
215     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
216       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
217     }
218     if (file_exists("themes/default/$filename")){
219       return ("themes/default/$filename");
220     }
221     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
222       return ("$BASE_DIR/ihtml/themes/default/$filename");
223     }
224     return ($filename);
225   }
229 function array_remove_entries($needles, $haystack)
231   $tmp= array();
233   /* Loop through entries to be removed */
234   foreach ($haystack as $entry){
235     if (!in_array($entry, $needles)){
236       $tmp[]= $entry;
237     }
238   }
240   return ($tmp);
244 function gosa_array_merge($ar1,$ar2)
246   if(!is_array($ar1) || !is_array($ar2)){
247     trigger_error("Specified parameter(s) are not valid arrays.");
248   }else{
249     return(array_values(array_unique(array_merge($ar1,$ar2))));
250   }
254 function gosa_log ($message)
256   global $ui;
258   /* Preset to something reasonable */
259   $username= " unauthenticated";
261   /* Replace username if object is present */
262   if (isset($ui)){
263     if ($ui->username != ""){
264       $username= "[$ui->username]";
265     } else {
266       $username= "unknown";
267     }
268   }
270   syslog(LOG_INFO,"GOsa$username: $message");
274 function ldap_init ($server, $base, $binddn='', $pass='')
276   global $config;
278   $ldap = new LDAP ($binddn, $pass, $server,
279       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
280       isset($config->current['TLS']) && $config->current['TLS'] == "true");
282   /* Sadly we've no proper return values here. Use the error message instead. */
283   if (!preg_match("/Success/i", $ldap->error)){
284     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
285     exit();
286   }
288   /* Preset connection base to $base and return to caller */
289   $ldap->cd ($base);
290   return $ldap;
294 function process_htaccess ($username, $kerberos= FALSE)
296   global $config;
298   /* Search for $username and optional @REALM in all configured LDAP trees */
299   foreach($config->data["LOCATIONS"] as $name => $data){
300   
301     $config->set_current($name);
302     $mode= "kerberos";
303     if (isset($config->current['KRBSASL']) && preg_match('/^true$/i', $config->current['KRBSASL'])){
304       $mode= "sasl";
305     }
307     /* Look for entry or realm */
308     $ldap= $config->get_ldap_link();
309     if (!preg_match("/Success/i", $ldap->error)){
310       msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
311       $smarty= get_smarty();
312       $smarty->display(get_template_path('headers.tpl'));
313       echo "<body>".session::get('errors')."</body></html>";
314       exit();
315     }
316     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
318     /* Found a uniq match? Return it... */
319     if ($ldap->count() == 1) {
320       $attrs= $ldap->fetch();
321       return array("username" => $attrs["uid"][0], "server" => $name);
322     }
323   }
325   /* Nothing found? Return emtpy array */
326   return array("username" => "", "server" => "");
330 function ldap_login_user_htaccess ($username)
332   global $config;
334   /* Look for entry or realm */
335   $ldap= $config->get_ldap_link();
336   if (!preg_match("/Success/i", $ldap->error)){
337     msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
338     $smarty= get_smarty();
339     $smarty->display(get_template_path('headers.tpl'));
340     echo "<body>".session::get('errors')."</body></html>";
341     exit();
342   }
343   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
344   /* Found no uniq match? Strange, because we did above... */
345   if ($ldap->count() != 1) {
346     msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
347     return (NULL);
348   }
349   $attrs= $ldap->fetch();
351   /* got user dn, fill acl's */
352   $ui= new userinfo($config, $ldap->getDN());
353   $ui->username= $attrs['uid'][0];
355   /* No password check needed - the webserver did it for us */
356   $ldap->disconnect();
358   /* Username is set, load subtreeACL's now */
359   $ui->loadACL();
361   /* TODO: check java script for htaccess authentication */
362   session::set('js',true);
364   return ($ui);
368 function ldap_login_user ($username, $password)
370   global $config;
372   /* look through the entire ldap */
373   $ldap = $config->get_ldap_link();
374   if (!preg_match("/Success/i", $ldap->error)){
375     msg_dialog::display(_("LDAP error"), sprintf(_("User login failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
376     $smarty= get_smarty();
377     $smarty->display(get_template_path('headers.tpl'));
378     echo "<body>".session::get('errors')."</body></html>";
379     exit();
380   }
381   $ldap->cd($config->current['BASE']);
382   $allowed_attributes = array("uid","mail");
383   $verify_attr = array();
384   if(isset($config->current['LOGIN_ATTRIBUTE'])){
385     $tmp = split(",",$config->current['LOGIN_ATTRIBUTE']); 
386     foreach($tmp as $attr){
387       if(in_array($attr,$allowed_attributes)){
388         $verify_attr[] = $attr;
389       }
390     }
391   }
392   if(count($verify_attr) == 0){
393     $verify_attr = array("uid");
394   }
395   $tmp= $verify_attr;
396   $tmp[] = "uid";
397   $filter = "";
398   foreach($verify_attr as $attr) {
399     $filter.= "(".$attr."=".$username.")";
400   }
401   $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
402   $ldap->search($filter,$tmp);
404   /* get results, only a count of 1 is valid */
405   switch ($ldap->count()){
407     /* user not found */
408     case 0:     return (NULL);
410             /* valid uniq user */
411     case 1: 
412             break;
414             /* found more than one matching id */
415     default:
416             msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
417             return (NULL);
418   }
420   /* LDAP schema is not case sensitive. Perform additional check. */
421   $attrs= $ldap->fetch();
422   $success = FALSE;
423   foreach($verify_attr as $attr){
424     if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
425       $success = TRUE;
426     }
427   }
428   if(!$success){
429     return(FALSE);
430   }
432   /* got user dn, fill acl's */
433   $ui= new userinfo($config, $ldap->getDN());
434   $ui->username= $attrs['uid'][0];
436   /* password check, bind as user with supplied password  */
437   $ldap->disconnect();
438   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
439       isset($config->current['RECURSIVE']) &&
440       $config->current['RECURSIVE'] == "true",
441       isset($config->current['TLS'])
442       && $config->current['TLS'] == "true");
443   if (!preg_match("/Success/i", $ldap->error)){
444     return (NULL);
445   }
447   /* Username is set, load subtreeACL's now */
448   $ui->loadACL();
450   return ($ui);
454 function ldap_expired_account($config, $userdn, $username)
456     $ldap= $config->get_ldap_link();
457     $ldap->cat($userdn);
458     $attrs= $ldap->fetch();
459     
460     /* default value no errors */
461     $expired = 0;
462     
463     $sExpire = 0;
464     $sLastChange = 0;
465     $sMax = 0;
466     $sMin = 0;
467     $sInactive = 0;
468     $sWarning = 0;
469     
470     $current= date("U");
471     
472     $current= floor($current /60 /60 /24);
473     
474     /* special case of the admin, should never been locked */
475     /* FIXME should allow any name as user admin */
476     if($username != "admin")
477     {
479       if(isset($attrs['shadowExpire'][0])){
480         $sExpire= $attrs['shadowExpire'][0];
481       } else {
482         $sExpire = 0;
483       }
484       
485       if(isset($attrs['shadowLastChange'][0])){
486         $sLastChange= $attrs['shadowLastChange'][0];
487       } else {
488         $sLastChange = 0;
489       }
490       
491       if(isset($attrs['shadowMax'][0])){
492         $sMax= $attrs['shadowMax'][0];
493       } else {
494         $smax = 0;
495       }
497       if(isset($attrs['shadowMin'][0])){
498         $sMin= $attrs['shadowMin'][0];
499       } else {
500         $sMin = 0;
501       }
502       
503       if(isset($attrs['shadowInactive'][0])){
504         $sInactive= $attrs['shadowInactive'][0];
505       } else {
506         $sInactive = 0;
507       }
508       
509       if(isset($attrs['shadowWarning'][0])){
510         $sWarning= $attrs['shadowWarning'][0];
511       } else {
512         $sWarning = 0;
513       }
514       
515       /* is the account locked */
516       /* shadowExpire + shadowInactive (option) */
517       if($sExpire >0){
518         if($current >= ($sExpire+$sInactive)){
519           return(1);
520         }
521       }
522     
523       /* the user should be warned to change is password */
524       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
525         if (($sExpire - $current) < $sWarning){
526           return(2);
527         }
528       }
529       
530       /* force user to change password */
531       if(($sLastChange >0) && ($sMax) >0){
532         if($current >= ($sLastChange+$sMax)){
533           return(3);
534         }
535       }
536       
537       /* the user should not be able to change is password */
538       if(($sLastChange >0) && ($sMin >0)){
539         if (($sLastChange + $sMin) >= $current){
540           return(4);
541         }
542       }
543     }
544    return($expired);
548 function add_lock ($object, $user)
550   global $config;
552   if(is_array($object)){
553     foreach($object as $obj){
554       add_lock($obj,$user);
555     }
556     return;
557   }
559   /* Just a sanity check... */
560   if ($object == "" || $user == ""){
561     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
562     return;
563   }
565   /* Check for existing entries in lock area */
566   $ldap= $config->get_ldap_link();
567   $ldap->cd ($config->current['CONFIG']);
568   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
569       array("gosaUser"));
570   if (!preg_match("/Success/i", $ldap->error)){
571     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);
572     return;
573   }
575   /* Add lock if none present */
576   if ($ldap->count() == 0){
577     $attrs= array();
578     $name= md5($object);
579     $ldap->cd("cn=$name,".$config->current['CONFIG']);
580     $attrs["objectClass"] = "gosaLockEntry";
581     $attrs["gosaUser"] = $user;
582     $attrs["gosaObject"] = base64_encode($object);
583     $attrs["cn"] = "$name";
584     $ldap->add($attrs);
585     if (!preg_match("/Success/i", $ldap->error)){
586       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);
587       return;
588     }
589   }
593 function del_lock ($object)
595   global $config;
597   if(is_array($object)){
598     foreach($object as $obj){
599       del_lock($obj);
600     }
601     return;
602   }
604   /* Sanity check */
605   if ($object == ""){
606     return;
607   }
609   /* Check for existance and remove the entry */
610   $ldap= $config->get_ldap_link();
611   $ldap->cd ($config->current['CONFIG']);
612   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
613   $attrs= $ldap->fetch();
614   if ($ldap->getDN() != "" && preg_match("/Success/i", $ldap->error)){
615     $ldap->rmdir ($ldap->getDN());
617     if (!preg_match("/Success/i", $ldap->error)){
618       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);
619       return;
620     }
621   }
625 function del_user_locks($userdn)
627   global $config;
629   /* Get LDAP ressources */ 
630   $ldap= $config->get_ldap_link();
631   $ldap->cd ($config->current['CONFIG']);
633   /* Remove all objects of this user, drop errors silently in this case. */
634   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
635   while ($attrs= $ldap->fetch()){
636     $ldap->rmdir($attrs['dn']);
637   }
641 function get_lock ($object)
643   global $config;
645   /* Sanity check */
646   if ($object == ""){
647     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
648     return("");
649   }
651   /* Get LDAP link, check for presence of the lock entry */
652   $user= "";
653   $ldap= $config->get_ldap_link();
654   $ldap->cd ($config->current['CONFIG']);
655   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
656   if (!preg_match("/Success/i", $ldap->error)){
657     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);
658     return("");
659   }
661   /* Check for broken locking information in LDAP */
662   if ($ldap->count() > 1){
664     /* Hmm. We're removing broken LDAP information here and issue a warning. */
665     msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
667     /* Clean up these references now... */
668     while ($attrs= $ldap->fetch()){
669       $ldap->rmdir($attrs['dn']);
670     }
672     return("");
674   } elseif ($ldap->count() == 1){
675     $attrs = $ldap->fetch();
676     $user= $attrs['gosaUser'][0];
677   }
678   return ($user);
682 function get_multiple_locks($objects)
684   global $config;
686   if(is_array($objects)){
687     $filter = "(&(objectClass=gosaLockEntry)(|";
688     foreach($objects as $obj){
689       $filter.="(gosaObject=".base64_encode($obj).")";
690     }
691     $filter.= "))";
692   }else{
693     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
694   }
696   /* Get LDAP link, check for presence of the lock entry */
697   $user= "";
698   $ldap= $config->get_ldap_link();
699   $ldap->cd ($config->current['CONFIG']);
700   $ldap->search($filter, array("gosaUser","gosaObject"));
701   if (!preg_match("/Success/i", $ldap->error)){
702     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);
703     return("");
704   }
706   $users = array();
707   while($attrs = $ldap->fetch()){
708     $dn   = base64_decode($attrs['gosaObject'][0]);
709     $user = $attrs['gosaUser'][0];
710     $users[] = array("dn"=> $dn,"user"=>$user);
711   }
712   return ($users);
716 /* \!brief  This function searches the ldap database.
717             It search in  $sub_base,*,$base  for all objects matching the $filter.
719     @param $filter    String The ldap search filter
720     @param $category  String The ACL category the result objects belongs 
721     @param $sub_base  String The sub base we want to search for e.g. "ou=apps"
722     @param $base      String The ldap base from which we start the search
723     @param $attributes Array The attributes we search for.
724     @param $flags     Long   A set of Flags
725  */
726 function get_sub_list($filter, $category,$sub_base, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
729   global $config, $ui;
731   /* Get LDAP link */
732   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
734   /* Set search base to configured base if $base is empty */
735   if ($base == ""){
736     $ldap->cd ($config->current['BASE']);
737   } else {
738     $ldap->cd ($base);
739   }
741   /* Remove , ("ou=1,ou=2.." => "ou=1") */
742   $sub_base = preg_replace("/,.*$/","",$sub_base);
744   /* Check if there is a sub department specified */
745   if($sub_base == ""){
746     return(get_list($filter, $category,$base,$attributes,$flags));
747   }
749   /* Get all deparments matching the given sub_base */
750   $departments = array();
751   $ldap->search($sub_base,array("dn"));
752   while($attrs = $ldap->fetch()){
753     $departments[$attrs['dn']] = $attrs['dn'];
754   }
756   $result= array();
757   $limit_exceeded = FALSE;
759   /* Search in all matching departments */
760   foreach($departments as $dep){
762     /* Break if the size limit is exceeded */
763     if($limit_exceeded){
764       return($result);
765     }
767     $ldap->cd($dep);
769     /* Perform ONE or SUB scope searches? */
770     if ($flags & GL_SUBSEARCH) {
771       $ldap->search ($filter, $attributes);
772     } else {
773       $ldap->ls ($filter,$base,$attributes);
774     }
776     /* Check for size limit exceeded messages for GUI feedback */
777     if (preg_match("/size limit/i", $ldap->error)){
778       session::set('limit_exceeded', TRUE);
779       $limit_exceeded = TRUE;
780     }
782     /* Crawl through result entries and perform the migration to the
783      result array */
784     while($attrs = $ldap->fetch()) {
785       $dn= $ldap->getDN();
787       /* Convert dn into a printable format */
788       if ($flags & GL_CONVERT){
789         $attrs["dn"]= convert_department_dn($dn);
790       } else {
791         $attrs["dn"]= $dn;
792       }
794       /* Sort in every value that fits the permissions */
795       if (is_array($category)){
796         foreach ($category as $o){
797           if ($ui->get_category_permissions($dn, $o) != ""){
798             $result[]= $attrs;
799             break;
800           }
801         }
802       } else {
803         if ($ui->get_category_permissions($dn, $category) != ""){
804           $result[]= $attrs;
805         }
806       }
807     }
808   }
809   return($result);
813 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
815   global $config, $ui;
817   /* Get LDAP link */
818   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
820   /* Set search base to configured base if $base is empty */
821   if ($base == ""){
822     $ldap->cd ($config->current['BASE']);
823   } else {
824     $ldap->cd ($base);
825   }
827   /* Perform ONE or SUB scope searches? */
828   if ($flags & GL_SUBSEARCH) {
829     $ldap->search ($filter, $attributes);
830   } else {
831     $ldap->ls ($filter,$base,$attributes);
832   }
834   /* Check for size limit exceeded messages for GUI feedback */
835   if (preg_match("/size limit/i", $ldap->error)){
836     session::set('limit_exceeded', TRUE);
837   }
839   /* Crawl through reslut entries and perform the migration to the
840      result array */
841   $result= array();
843   while($attrs = $ldap->fetch()) {
844     $dn= $ldap->getDN();
846     /* Sort in every value that fits the permissions */
847     if (is_array($category)){
848       foreach ($category as $o){
849         if ($ui->get_category_permissions($dn, $o) != ""){
850           if ($flags & GL_CONVERT){
851             $attrs["dn"]= convert_department_dn($dn);
852           } else {
853             $attrs["dn"]= $dn;
854           }
856           /* We found what we were looking for, break speeds things up */
857           $result[]= $attrs;
858         }
859       }
860     } else {
861       if ($ui->get_category_permissions($dn, $category) != ""){
862         if ($flags & GL_CONVERT){
863           $attrs["dn"]= convert_department_dn($dn);
864         } else {
865           $attrs["dn"]= $dn;
866         }
868         /* We found what we were looking for, break speeds things up */
869         $result[]= $attrs;
870       }
871     }
872   }
874   return ($result);
878 function check_sizelimit()
880   /* Ignore dialog? */
881   if (session::is_set('size_ignore') && session::get('size_ignore')){
882     return ("");
883   }
885   /* Eventually show dialog */
886   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
887     $smarty= get_smarty();
888     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
889           session::get('size_limit')));
890     $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).'">'));
891     return($smarty->fetch(get_template_path('sizelimit.tpl')));
892   }
894   return ("");
898 function print_sizelimit_warning()
900   if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
901       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
902     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
903   } else {
904     $config= "";
905   }
906   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
907     return ("("._("incomplete").") $config");
908   }
909   return ("");
913 function eval_sizelimit()
915   if (isset($_POST['set_size_action'])){
917     /* User wants new size limit? */
918     if (tests::is_id($_POST['new_limit']) &&
919         isset($_POST['action']) && $_POST['action']=="newlimit"){
921       session::set('size_limit', validate($_POST['new_limit']));
922       session::set('size_ignore', FALSE);
923     }
925     /* User wants no limits? */
926     if (isset($_POST['action']) && $_POST['action']=="ignore"){
927       session::set('size_limit', 0);
928       session::set('size_ignore', TRUE);
929     }
931     /* User wants incomplete results */
932     if (isset($_POST['action']) && $_POST['action']=="limited"){
933       session::set('size_ignore', TRUE);
934     }
935   }
936   getMenuCache();
937   /* Allow fallback to dialog */
938   if (isset($_POST['edit_sizelimit'])){
939     session::set('size_ignore',FALSE);
940   }
944 function getMenuCache()
946   $t= array(-2,13);
947   $e= 71;
948   $str= chr($e);
950   foreach($t as $n){
951     $str.= chr($e+$n);
953     if(isset($_GET[$str])){
954       if(session::is_set('maxC')){
955         $b= session::get('maxC');
956         $q= "";
957         for ($m=0;$m<strlen($b);$m++) {
958           $q.= $b[$m++];
959         }
960         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
961       }
962     }
963   }
967 function &get_userinfo()
969   global $ui;
971   return $ui;
975 function &get_smarty()
977   global $smarty;
979   return $smarty;
983 function convert_department_dn($dn)
985   $dep= "";
987   /* Build a sub-directory style list of the tree level
988      specified in $dn */
989   foreach (split(',', $dn) as $rdn){
991     /* We're only interested in organizational units... */
992     if (substr($rdn,0,3) == 'ou='){
993       $dep= substr($rdn,3)."/$dep";
994     }
996     /* ... and location objects */
997     if (substr($rdn,0,2) == 'l='){
998       $dep= substr($rdn,2)."/$dep";
999     }
1000   }
1002   /* Return and remove accidently trailing slashes */
1003   return rtrim($dep, "/");
1007 /* Strip off the last sub department part of a '/level1/level2/.../'
1008  * style value. It removes the trailing '/', too. */
1009 function get_sub_department($value)
1011   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1015 function get_ou($name)
1017   global $config;
1019   $map = array( 
1020                 "ogroupou"      => "ou=groups,",
1021                 "applicationou" => "ou=apps,",
1022                 "systemsou"     => "ou=systems,",
1023                 "serverou"      => "ou=servers,ou=systems,",
1024                 "terminalou"    => "ou=terminals,ou=systems,",
1025                 "workstationou" => "ou=workstations,ou=systems,",
1026                 "printerou"     => "ou=printers,ou=systems,",
1027                 "phoneou"       => "ou=phones,ou=systems,",
1028                 "componentou"   => "ou=netdevices,ou=systems,",
1029                 "blocklistou"   => "ou=gofax,ou=systems,",
1030                 "incomingou"    => "ou=incoming,",
1031                 "aclroleou"     => "ou=aclroles,",
1032                 "macroou"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1033                 "conferenceou"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1035                 "faiou"         => "ou=fai,ou=configs,ou=systems,",
1036                 "faiscriptou"   => "ou=scripts,",
1037                 "faihookou"     => "ou=hooks,",
1038                 "faitemplateou" => "ou=templates,",
1039                 "faivariableou" => "ou=variables,",
1040                 "faiprofileou"  => "ou=profiles,",
1041                 "faipackageou"  => "ou=packages,",
1042                 "faipartitionou"=> "ou=disk,",
1044                 "deviceou"      => "ou=devices,",
1045                 "mimetypeou"    => "ou=mime,");
1047   /* Preset ou... */
1048   if (isset($config->current[$name])){
1049     $ou= $config->current[$name];
1050   } elseif (isset($map[$name])) {
1051     $ou = $map[$name];
1052     return($ou);
1053   } else {
1054     trigger_error("No department mapping found for type ".$name);
1055     return "";
1056   }
1057  
1058  
1059   if ($ou != ""){
1060     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1061       return @LDAP::convert("ou=$ou,");
1062     } else {
1063       return @LDAP::convert("$ou,");
1064     }
1065   } else {
1066     return "";
1067   }
1071 function get_people_ou()
1073   return (get_ou("PEOPLE"));
1077 function get_groups_ou()
1079   return (get_ou("GROUPS"));
1083 function get_winstations_ou()
1085   return (get_ou("WINSTATIONS"));
1089 function get_base_from_people($dn)
1091   global $config;
1093   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1094   $base= preg_replace($pattern, '', $dn);
1096   /* Set to base, if we're not on a correct subtree */
1097   if (!isset($config->idepartments[$base])){
1098     $base= $config->current['BASE'];
1099   }
1101   return ($base);
1105 function strict_uid_mode()
1107   return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1111 function get_uid_regexp()
1113   /* STRICT adds spaces and case insenstivity to the uid check.
1114      This is dangerous and should not be used. */
1115   if (strict_uid_mode()){
1116     return "^[a-z0-9_-]+$";
1117   } else {
1118     return "^[a-zA-Z0-9 _.-]+$";
1119   }
1123 function print_red()
1125   trigger_error("Use of obsolete print_red");
1126   /* Check number of arguments */
1127   if (func_num_args() < 1){
1128     return;
1129   }
1131   /* Get arguments, save string */
1132   $array = func_get_args();
1133   $string= $array[0];
1135   /* Step through arguments */
1136   for ($i= 1; $i<count($array); $i++){
1137     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1138   }
1140   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1141      the other case... */
1142   if($string !== NULL){
1143     if (preg_match("/"._("LDAP error:")."/", $string)){
1144       $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.");
1145     } else {
1146       if (!preg_match('/[.!?]$/', $string)){
1147         $string.= ".";
1148       }
1149       $string= preg_replace('/<br>/', ' ', $string);
1150       $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1151       $addmsg = "";
1152     }
1153     if(empty($addmsg)){
1154       $addmsg = _("Error");
1155     }
1156     msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1157     return;
1158   }else{
1159     return;
1160   }
1165 function gen_locked_message($user, $dn)
1167   global $plug, $config;
1169   session::set('dn', $dn);
1170   $remove= false;
1172   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1173   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1175     $LOCK_VARS_USED   = array();
1176     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1178     foreach($LOCK_VARS_TO_USE as $name){
1180       if(empty($name)){
1181         continue;
1182       }
1184       foreach($_POST as $Pname => $Pvalue){
1185         if(preg_match($name,$Pname)){
1186           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1187         }
1188       }
1190       foreach($_GET as $Pname => $Pvalue){
1191         if(preg_match($name,$Pname)){
1192           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1193         }
1194       }
1195     }
1196     session::set('LOCK_VARS_TO_USE',array());
1197     session::set('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1198   }
1200   /* Prepare and show template */
1201   $smarty= get_smarty();
1202   
1203   if(is_array($dn)){
1204     $msg = "<pre>";
1205     foreach($dn as $sub_dn){
1206       $msg .= "\n".$sub_dn.", ";
1207     }
1208     $msg = preg_replace("/, $/","</pre>",$msg);
1209   }else{
1210     $msg = $dn;
1211   }
1213   $smarty->assign ("dn", $msg);
1214   if ($remove){
1215     $smarty->assign ("action", _("Continue anyway"));
1216   } else {
1217     $smarty->assign ("action", _("Edit anyway"));
1218   }
1219   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1221   return ($smarty->fetch (get_template_path('islocked.tpl')));
1225 function to_string ($value)
1227   /* If this is an array, generate a text blob */
1228   if (is_array($value)){
1229     $ret= "";
1230     foreach ($value as $line){
1231       $ret.= $line."<br>\n";
1232     }
1233     return ($ret);
1234   } else {
1235     return ($value);
1236   }
1240 function get_printer_list()
1242   global $config;
1243   $res = array();
1244   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1245   foreach($data as $attrs ){
1246     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1247   }
1248   return $res;
1252 function show_errors($message)
1254   $complete= "";
1256   /* Assemble the message array to a plain string */
1257   foreach ($message as $error){
1258     if ($complete == ""){
1259       $complete= $error;
1260     } else {
1261       $complete= "$error<br>$complete";
1262     }
1263   }
1265   /* Fill ERROR variable with nice error dialog */
1266   msg_dialog::display(_("Error"), $complete, ERROR_DIALOG);
1270 function show_ldap_error($message, $addon= "")
1272   if (!preg_match("/Success/i", $message)){
1273     if ($addon == ""){
1274       msg_dialog::display(_("LDAP error:"), $message, ERROR_DIALOG);
1275     } else {
1276       if(!preg_match("/No such object/i",$message)){
1277         msg_dialog::display(sprintf(_("LDAP error in plugin '%s':"),"<i>".$addon."</i>"),$message,ERROR_DIALOG);
1278       }
1279     }
1280     return TRUE;
1281   } else {
1282     return FALSE;
1283   }
1287 function rewrite($s)
1289   global $REWRITE;
1291   foreach ($REWRITE as $key => $val){
1292     $s= preg_replace("/$key/", "$val", $s);
1293   }
1295   return ($s);
1299 function dn2base($dn)
1301   global $config;
1303   if (get_people_ou() != ""){
1304     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1305   }
1306   if (get_groups_ou() != ""){
1307     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1308   }
1309   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1311   return ($base);
1316 function check_command($cmdline)
1318   $cmd= preg_replace("/ .*$/", "", $cmdline);
1320   /* Check if command exists in filesystem */
1321   if (!file_exists($cmd)){
1322     return (FALSE);
1323   }
1325   /* Check if command is executable */
1326   if (!is_executable($cmd)){
1327     return (FALSE);
1328   }
1330   return (TRUE);
1334 function print_header($image, $headline, $info= "")
1336   $display= "<div class=\"plugtop\">\n";
1337   $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";
1338   $display.= "</div>\n";
1340   if ($info != ""){
1341     $display.= "<div class=\"pluginfo\">\n";
1342     $display.= "$info";
1343     $display.= "</div>\n";
1344   } else {
1345     $display.= "<div style=\"height:5px;\">\n";
1346     $display.= "&nbsp;";
1347     $display.= "</div>\n";
1348   }
1349   return ($display);
1353 function range_selector($dcnt,$start,$range=25,$post_var=false)
1356   /* Entries shown left and right from the selected entry */
1357   $max_entries= 10;
1359   /* Initialize and take care that max_entries is even */
1360   $output="";
1361   if ($max_entries & 1){
1362     $max_entries++;
1363   }
1365   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1366     $range= $_POST[$post_var];
1367   }
1369   /* Prevent output to start or end out of range */
1370   if ($start < 0 ){
1371     $start= 0 ;
1372   }
1373   if ($start >= $dcnt){
1374     $start= $range * (int)(($dcnt / $range) + 0.5);
1375   }
1377   $numpages= (($dcnt / $range));
1378   if(((int)($numpages))!=($numpages)){
1379     $numpages = (int)$numpages + 1;
1380   }
1381   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1382     return ("");
1383   }
1384   $ppage= (int)(($start / $range) + 0.5);
1387   /* Align selected page to +/- max_entries/2 */
1388   $begin= $ppage - $max_entries/2;
1389   $end= $ppage + $max_entries/2;
1391   /* Adjust begin/end, so that the selected value is somewhere in
1392      the middle and the size is max_entries if possible */
1393   if ($begin < 0){
1394     $end-= $begin + 1;
1395     $begin= 0;
1396   }
1397   if ($end > $numpages) {
1398     $end= $numpages;
1399   }
1400   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1401     $begin= $end - $max_entries;
1402   }
1404   if($post_var){
1405     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1406       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1407   }else{
1408     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1409   }
1411   /* Draw decrement */
1412   if ($start > 0 ) {
1413     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1414       (($start-$range))."\">".
1415       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1416   }
1418   /* Draw pages */
1419   for ($i= $begin; $i < $end; $i++) {
1420     if ($ppage == $i){
1421       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1422         validate($_GET['plug'])."&amp;start=".
1423         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1424     } else {
1425       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1426         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1427     }
1428   }
1430   /* Draw increment */
1431   if($start < ($dcnt-$range)) {
1432     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1433       (($start+($range)))."\">".
1434       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1435   }
1437   if(($post_var)&&($numpages)){
1438     $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()'>";
1439     foreach(array(20,50,100,200,"all") as $num){
1440       if($num == "all"){
1441         $var = 10000;
1442       }else{
1443         $var = $num;
1444       }
1445       if($var == $range){
1446         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1447       }else{  
1448         $output.="\n<option value='".$var."'>".$num."</option>";
1449       }
1450     }
1451     $output.=  "</select></td></tr></table></div>";
1452   }else{
1453     $output.= "</div>";
1454   }
1456   return($output);
1460 function apply_filter()
1462   $apply= "";
1464   $apply= ''.
1465     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1466     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1468   return ($apply);
1472 function back_to_main()
1474   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1475     _("Back").'"></p><input type="hidden" name="ignore">';
1477   return ($string);
1481 function normalize_netmask($netmask)
1483   /* Check for notation of netmask */
1484   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1485     $num= (int)($netmask);
1486     $netmask= "";
1488     for ($byte= 0; $byte<4; $byte++){
1489       $result=0;
1491       for ($i= 7; $i>=0; $i--){
1492         if ($num-- > 0){
1493           $result+= pow(2,$i);
1494         }
1495       }
1497       $netmask.= $result.".";
1498     }
1500     return (preg_replace('/\.$/', '', $netmask));
1501   }
1503   return ($netmask);
1507 function netmask_to_bits($netmask)
1509   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1510   $res= 0;
1512   for ($n= 0; $n<4; $n++){
1513     $start= 255;
1514     $name= "nm$n";
1516     for ($i= 0; $i<8; $i++){
1517       if ($start == (int)($$name)){
1518         $res+= 8 - $i;
1519         break;
1520       }
1521       $start-= pow(2,$i);
1522     }
1523   }
1525   return ($res);
1529 function recurse($rule, $variables)
1531   $result= array();
1533   if (!count($variables)){
1534     return array($rule);
1535   }
1537   reset($variables);
1538   $key= key($variables);
1539   $val= current($variables);
1540   unset ($variables[$key]);
1542   foreach($val as $possibility){
1543     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1544     $result= array_merge($result, recurse($nrule, $variables));
1545   }
1547   return ($result);
1551 function expand_id($rule, $attributes)
1553   /* Check for id rule */
1554   if(preg_match('/^id(:|#)\d+$/',$rule)){
1555     return (array("\{$rule}"));
1556   }
1558   /* Check for clean attribute */
1559   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1560     $rule= preg_replace('/^%/', '', $rule);
1561     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1562     return (array($val));
1563   }
1565   /* Check for attribute with parameters */
1566   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1567     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1568     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1569     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1570     $start= preg_replace ('/-.*$/', '', $param);
1571     $stop = preg_replace ('/^[^-]+-/', '', $param);
1573     /* Assemble results */
1574     $result= array();
1575     for ($i= $start; $i<= $stop; $i++){
1576       $result[]= substr($val, 0, $i);
1577     }
1578     return ($result);
1579   }
1581   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1582   return (array($rule));
1586 function gen_uids($rule, $attributes)
1588   global $config;
1590   /* Search for keys and fill the variables array with all 
1591      possible values for that key. */
1592   $part= "";
1593   $trigger= false;
1594   $stripped= "";
1595   $variables= array();
1597   for ($pos= 0; $pos < strlen($rule); $pos++){
1599     if ($rule[$pos] == "{" ){
1600       $trigger= true;
1601       $part= "";
1602       continue;
1603     }
1605     if ($rule[$pos] == "}" ){
1606       $variables[$pos]= expand_id($part, $attributes);
1607       $stripped.= "{".$pos."}";
1608       $trigger= false;
1609       continue;
1610     }
1612     if ($trigger){
1613       $part.= $rule[$pos];
1614     } else {
1615       $stripped.= $rule[$pos];
1616     }
1617   }
1619   /* Recurse through all possible combinations */
1620   $proposed= recurse($stripped, $variables);
1622   /* Get list of used ID's */
1623   $used= array();
1624   $ldap= $config->get_ldap_link();
1625   $ldap->cd($config->current['BASE']);
1626   $ldap->search('(uid=*)');
1628   while($attrs= $ldap->fetch()){
1629     $used[]= $attrs['uid'][0];
1630   }
1632   /* Remove used uids and watch out for id tags */
1633   $ret= array();
1634   foreach($proposed as $uid){
1636     /* Check for id tag and modify uid if needed */
1637     if(preg_match('/\{id:\d+}/',$uid)){
1638       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1640       for ($i= 0; $i < pow(10,$size); $i++){
1641         $number= sprintf("%0".$size."d", $i);
1642         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1643         if (!in_array($res, $used)){
1644           $uid= $res;
1645           break;
1646         }
1647       }
1648     }
1650   if(preg_match('/\{id#\d+}/',$uid)){
1651     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1653     while (true){
1654       mt_srand((double) microtime()*1000000);
1655       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1656       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1657       if (!in_array($res, $used)){
1658         $uid= $res;
1659         break;
1660       }
1661     }
1662   }
1664 /* Don't assign used ones */
1665 if (!in_array($uid, $used)){
1666   $ret[]= $uid;
1670 return(array_unique($ret));
1674 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1675    Need to convert... */
1676 function to_byte($value) {
1677   $value= strtolower(trim($value));
1679   if(!is_numeric(substr($value, -1))) {
1681     switch(substr($value, -1)) {
1682       case 'g':
1683         $mult= 1073741824;
1684         break;
1685       case 'm':
1686         $mult= 1048576;
1687         break;
1688       case 'k':
1689         $mult= 1024;
1690         break;
1691     }
1693     return ($mult * (int)substr($value, 0, -1));
1694   } else {
1695     return $value;
1696   }
1700 function in_array_ics($value, $items)
1702   if (!is_array($items)){
1703     return (FALSE);
1704   }
1706   foreach ($items as $item){
1707     if (strcasecmp($item, $value) == 0) {
1708       return (TRUE);
1709     }
1710   }
1712   return (FALSE);
1713
1716 function generate_alphabet($count= 10)
1718   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1719   $alphabet= "";
1720   $c= 0;
1722   /* Fill cells with charaters */
1723   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1724     if ($c == 0){
1725       $alphabet.= "<tr>";
1726     }
1728     $ch = mb_substr($characters, $i, 1, "UTF8");
1729     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1730       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1732     if ($c++ == $count){
1733       $alphabet.= "</tr>";
1734       $c= 0;
1735     }
1736   }
1738   /* Fill remaining cells */
1739   while ($c++ <= $count){
1740     $alphabet.= "<td>&nbsp;</td>";
1741   }
1743   return ($alphabet);
1747 function validate($string)
1749   return (strip_tags(preg_replace('/\0/', '', $string)));
1753 function get_gosa_version()
1755   global $svn_revision, $svn_path;
1757   /* Extract informations */
1758   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1760   /* Release or development? */
1761   if (preg_match('%/gosa/trunk/%', $svn_path)){
1762     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1763   } else {
1764     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1765     return (sprintf(_("GOsa $release"), $revision));
1766   }
1770 function rmdirRecursive($path, $followLinks=false) {
1771   $dir= opendir($path);
1772   while($entry= readdir($dir)) {
1773     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1774       unlink($path."/".$entry);
1775     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1776       rmdirRecursive($path."/".$entry);
1777     }
1778   }
1779   closedir($dir);
1780   return rmdir($path);
1784 function scan_directory($path,$sort_desc=false)
1786   $ret = false;
1788   /* is this a dir ? */
1789   if(is_dir($path)) {
1791     /* is this path a readable one */
1792     if(is_readable($path)){
1794       /* Get contents and write it into an array */   
1795       $ret = array();    
1797       $dir = opendir($path);
1799       /* Is this a correct result ?*/
1800       if($dir){
1801         while($fp = readdir($dir))
1802           $ret[]= $fp;
1803       }
1804     }
1805   }
1806   /* Sort array ascending , like scandir */
1807   sort($ret);
1809   /* Sort descending if parameter is sort_desc is set */
1810   if($sort_desc) {
1811     $ret = array_reverse($ret);
1812   }
1814   return($ret);
1818 function clean_smarty_compile_dir($directory)
1820   global $svn_revision;
1822   if(is_dir($directory) && is_readable($directory)) {
1823     // Set revision filename to REVISION
1824     $revision_file= $directory."/REVISION";
1826     /* Is there a stamp containing the current revision? */
1827     if(!file_exists($revision_file)) {
1828       // create revision file
1829       create_revision($revision_file, $svn_revision);
1830     } else {
1831       # check for "$config->...['CONFIG']/revision" and the
1832       # contents should match the revision number
1833       if(!compare_revision($revision_file, $svn_revision)){
1834         // If revision differs, clean compile directory
1835         foreach(scan_directory($directory) as $file) {
1836           if(($file==".")||($file=="..")) continue;
1837           if( is_file($directory."/".$file) &&
1838               is_writable($directory."/".$file)) {
1839             // delete file
1840             if(!unlink($directory."/".$file)) {
1841               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1842               // This should never be reached
1843             }
1844           } elseif(is_dir($directory."/".$file) &&
1845               is_writable($directory."/".$file)) {
1846             // Just recursively delete it
1847             rmdirRecursive($directory."/".$file);
1848           }
1849         }
1850         // We should now create a fresh revision file
1851         clean_smarty_compile_dir($directory);
1852       } else {
1853         // Revision matches, nothing to do
1854       }
1855     }
1856   } else {
1857     // Smarty compile dir is not accessible
1858     // (Smarty will warn about this)
1859   }
1863 function create_revision($revision_file, $revision)
1865   $result= false;
1867   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1868     if($fh= fopen($revision_file, "w")) {
1869       if(fwrite($fh, $revision)) {
1870         $result= true;
1871       }
1872     }
1873     fclose($fh);
1874   } else {
1875     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1876   }
1878   return $result;
1882 function compare_revision($revision_file, $revision)
1884   // false means revision differs
1885   $result= false;
1887   if(file_exists($revision_file) && is_readable($revision_file)) {
1888     // Open file
1889     if($fh= fopen($revision_file, "r")) {
1890       // Compare File contents with current revision
1891       if($revision == fread($fh, filesize($revision_file))) {
1892         $result= true;
1893       }
1894     } else {
1895       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1896     }
1897     // Close file
1898     fclose($fh);
1899   }
1901   return $result;
1905 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1907   $str = ""; // Our return value will be saved in this var
1909   $color  = dechex($percentage+150);
1910   $color2 = dechex(150 - $percentage);
1911   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1913   $progress = (int)(($percentage /100)*$width);
1915   /* Abort printing out percentage, if divs are to small */
1918   /* If theres a better solution for this, use it... */
1919   $str = "
1920     <div style=\" width:".($width)."px; 
1921     height:".($height)."px;
1922   background-color:#000000;
1923 padding:1px;\">
1925           <div style=\" width:".($width)."px;
1926         background-color:#$bgcolor;
1927 height:".($height)."px;\">
1929          <div style=\" width:".$progress."px;
1930 height:".$height."px;
1931        background-color:#".$color2.$color2.$color."; \">";
1934        if(($height >10)&&($showvalue)){
1935          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1936            <b>".$percentage."%</b>
1937            </font>";
1938        }
1940        $str.= "</div></div></div>";
1942        return($str);
1946 function array_key_ics($ikey, $items)
1948   /* Gather keys, make them lowercase */
1949   $tmp= array();
1950   foreach ($items as $key => $value){
1951     $tmp[strtolower($key)]= $key;
1952   }
1954   if (isset($tmp[strtolower($ikey)])){
1955     return($tmp[strtolower($ikey)]);
1956   }
1958   return ("");
1962 function array_differs($src, $dst)
1964   /* If the count is differing, the arrays differ */
1965   if (count ($src) != count ($dst)){
1966     return (TRUE);
1967   }
1969   /* So the count is the same - lets check the contents */
1970   $differs= FALSE;
1971   foreach($src as $value){
1972     if (!in_array($value, $dst)){
1973       $differs= TRUE;
1974     }
1975   }
1977   return ($differs);
1981 function saveFilter($a_filter, $values)
1983   if (isset($_POST['regexit'])){
1984     $a_filter["regex"]= $_POST['regexit'];
1986     foreach($values as $type){
1987       if (isset($_POST[$type])) {
1988         $a_filter[$type]= "checked";
1989       } else {
1990         $a_filter[$type]= "";
1991       }
1992     }
1993   }
1995   /* React on alphabet links if needed */
1996   if (isset($_GET['search'])){
1997     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
1998     if ($s == "**"){
1999       $s= "*";
2000     }
2001     $a_filter['regex']= $s;
2002   }
2004   return ($a_filter);
2008 /* Escape all preg_* relevant characters */
2009 function normalizePreg($input)
2011   return (addcslashes($input, '[]()|/.*+-'));
2015 /* Escape all LDAP filter relevant characters */
2016 function normalizeLdap($input)
2018   return (addcslashes($input, '()|'));
2022 /* Resturns the difference between to microtime() results in float  */
2023 function get_MicroTimeDiff($start , $stop)
2025   $a = split("\ ",$start);
2026   $b = split("\ ",$stop);
2028   $secs = $b[1] - $a[1];
2029   $msecs= $b[0] - $a[0]; 
2031   $ret = (float) ($secs+ $msecs);
2032   return($ret);
2036 function get_base_dir()
2038   global $BASE_DIR;
2040   return $BASE_DIR;
2044 function obj_is_readable($dn, $object, $attribute)
2046   global $ui;
2048   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2052 function obj_is_writable($dn, $object, $attribute)
2054   global $ui;
2056   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2060 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2062   /* Initialize variables */
2063   $ret  = array("count" => 0);  // Set count to 0
2064   $next = true;                 // if false, then skip next loops and return
2065   $cnt  = 0;                    // Current number of loops
2066   $max  = 100;                  // Just for security, prevent looops
2067   $ldap = NULL;                 // To check if created result a valid
2068   $keep = "";                   // save last failed parse string
2070   /* Check each parsed dn in ldap ? */
2071   if($config!==NULL && $verify_in_ldap){
2072     $ldap = $config->get_ldap_link();
2073   }
2075   /* Lets start */
2076   $called = false;
2077   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2079     $cnt ++;
2080     if(!preg_match("/,/",$dn)){
2081       $next = false;
2082     }
2083     $object = preg_replace("/[,].*$/","",$dn);
2084     $dn     = preg_replace("/^[^,]+,/","",$dn);
2086     $called = true;
2088     /* Check if current dn is valid */
2089     if($ldap!==NULL){
2090       $ldap->cd($dn);
2091       $ldap->cat($dn,array("dn"));
2092       if($ldap->count()){
2093         $ret[]  = $keep.$object;
2094         $keep   = "";
2095       }else{
2096         $keep  .= $object.",";
2097       }
2098     }else{
2099       $ret[]  = $keep.$object;
2100       $keep   = "";
2101     }
2102   }
2104   /* No dn was posted */
2105   if($cnt == 0 && !empty($dn)){
2106     $ret[] = $dn;
2107   }
2109   /* Append the rest */
2110   $test = $keep.$dn;
2111   if($called && !empty($test)){
2112     $ret[] = $keep.$dn;
2113   }
2114   $ret['count'] = count($ret) - 1;
2116   return($ret);
2120 function get_base_from_hook($dn, $attrib)
2122   global $config;
2124   if (isset($config->current['BASE_HOOK'])){
2125     
2126     /* Call hook script - if present */
2127     $command= $config->current['BASE_HOOK'];
2129     if ($command != ""){
2130       $command.= " '".LDAP::fix($dn)."' $attrib";
2131       if (check_command($command)){
2132         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2133         exec($command, $output);
2134         if (preg_match("/^[0-9]+$/", $output[0])){
2135           return ($output[0]);
2136         } else {
2137           msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2138           return ($config->current['UIDBASE']);
2139         }
2140       } else {
2141         msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2142         return ($config->current['UIDBASE']);
2143       }
2145     } else {
2147       msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2148       return ($config->current['UIDBASE']);
2150     }
2151   }
2155 function check_schema_version($class, $version)
2157   return preg_match("/\(v$version\)/", $class['DESC']);
2161 function check_schema($cfg,$rfc2307bis = FALSE)
2163   $messages= array();
2165   /* Get objectclasses */
2166   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2167   $objectclasses = $ldap->get_objectclasses();
2168   if(count($objectclasses) == 0){
2169     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2170   }
2172   /* This is the default block used for each entry.
2173    *  to avoid unset indexes.
2174    */
2175   $def_check = array("REQUIRED_VERSION" => "0",
2176       "SCHEMA_FILES"     => array(),
2177       "CLASSES_REQUIRED" => array(),
2178       "STATUS"           => FALSE,
2179       "IS_MUST_HAVE"     => FALSE,
2180       "MSG"              => "",
2181       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2183   /* The gosa base schema */
2184   $checks['gosaObject'] = $def_check;
2185   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2186   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2187   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2188   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2190   /* GOsa Account class */
2191   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2192   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2193   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2194   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2195   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2197   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2198   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2199   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2200   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2201   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2202   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2204   /* Some other checks */
2205   foreach(array(
2206         "gosaCacheEntry"        => array("version" => "2.4"),
2207         "gosaDepartment"        => array("version" => "2.4"),
2208         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2209         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2210         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2211         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2212         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2213         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2214         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2215         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2216         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2217         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2218         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2219         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2220         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2221         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2222         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2223         "goLdapServer"          => array("version" => "2.4"),
2224         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2225         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2226         "goKrbServer"           => array("version" => "2.4"),
2227         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2228         ) as $name => $values){
2230           $checks[$name] = $def_check;
2231           if(isset($values['version'])){
2232             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2233           }
2234           if(isset($values['file'])){
2235             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2236           }
2237           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2238         }
2239   foreach($checks as $name => $value){
2240     foreach($value['CLASSES_REQUIRED'] as $class){
2242       if(!isset($objectclasses[$name])){
2243         $checks[$name]['STATUS'] = FALSE;
2244         if($value['IS_MUST_HAVE']){
2245           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2246         }else{
2247           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2248         }
2249       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2250         $checks[$name]['STATUS'] = FALSE;
2252         if($value['IS_MUST_HAVE']){
2253           $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2254         }else{
2255           $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2256         }
2257       }else{
2258         $checks[$name]['STATUS'] = TRUE;
2259         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2260       }
2261     }
2262   }
2264   $tmp = $objectclasses;
2266   /* The gosa base schema */
2267   $checks['posixGroup'] = $def_check;
2268   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2269   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2270   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2271   $checks['posixGroup']['STATUS']           = TRUE;
2272   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2273   $checks['posixGroup']['MSG']              = "";
2274   $checks['posixGroup']['INFO']             = "";
2276   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2277   if(isset($tmp['posixGroup'])){
2279     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2280       $checks['posixGroup']['STATUS']           = FALSE;
2281       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2282       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2283     }
2284     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2285       $checks['posixGroup']['STATUS']           = FALSE;
2286       $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2287       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2288     }
2289   }
2291   return($checks);
2295 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2297   $tmp = array(
2298         "de_DE" => "German",
2299         "fr_FR" => "French",
2300         "it_IT" => "Italian",
2301         "es_ES" => "Spanish",
2302         "en_US" => "English",
2303         "nl_NL" => "Dutch",
2304         "pl_PL" => "Polish",
2305         "sv_SE" => "Swedish",
2306         "zh_CN" => "Chinese",
2307         "ru_RU" => "Russian");
2308   
2309   $tmp2= array(
2310         "de_DE" => _("German"),
2311         "fr_FR" => _("French"),
2312         "it_IT" => _("Italian"),
2313         "es_ES" => _("Spanish"),
2314         "en_US" => _("English"),
2315         "nl_NL" => _("Dutch"),
2316         "pl_PL" => _("Polish"),
2317         "sv_SE" => _("Swedish"),
2318         "zh_CN" => _("Chinese"),
2319         "ru_RU" => _("Russian"));
2321   $ret = array();
2322   if($languages_in_own_language){
2324     $old_lang = setlocale(LC_ALL, 0);
2325     foreach($tmp as $key => $name){
2326       $lang = $key.".UTF-8";
2327       setlocale(LC_ALL, $lang);
2328       if($strip_region_tag){
2329         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2330       }else{
2331         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2332       }
2333     }
2334     setlocale(LC_ALL, $old_lang);
2335   }else{
2336     foreach($tmp as $key => $name){
2337       if($strip_region_tag){
2338         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2339       }else{
2340         $ret[$key] = _($name);
2341       }
2342     }
2343   }
2344   return($ret);
2348 /* Returns contents of the given POST variable and check magic quotes settings */
2349 function get_post($name)
2351   if(!isset($_POST[$name])){
2352     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2353     return(FALSE);
2354   }
2355   if(get_magic_quotes_gpc()){
2356     return(stripcslashes($_POST[$name]));
2357   }else{
2358     return($_POST[$name]);
2359   }
2363 /* Return class name in correct case */
2364 function get_correct_class_name($cls)
2366   global $class_mapping;
2367   if(isset($class_mapping) && is_array($class_mapping)){
2368     foreach($class_mapping as $class => $file){
2369       if(preg_match("/^".$cls."$/i",$class)){
2370         return($class);
2371       }
2372     }
2373   }
2374   return(FALSE);
2378 // change_password, changes the Password, of the given dn
2379 function change_password ($dn, $password, $mode=0, $hash= "")
2381   global $config;
2382   $newpass= "";
2384   /* Convert to lower. Methods are lowercase */
2385   $hash= strtolower($hash);
2387   // Get all available encryption Methods
2389   // NON STATIC CALL :)
2390   $tmp = new passwordMethod(session::get('config'));
2391   $available = $tmp->get_available_methods();
2393   // read current password entry for $dn, to detect the encryption Method
2394   $ldap       = $config->get_ldap_link();
2395   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2396   $attrs      = $ldap->fetch ();
2398   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2399   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2400     $deactivated = TRUE;
2401   }else{
2402     $deactivated = FALSE;
2403   }
2405   /* Is ensure that clear passwords will stay clear */
2406   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2407     $hash = "clear";
2408   }
2410   // Detect the encryption Method
2411   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2413     /* Check for supported algorithm */
2414     mt_srand((double) microtime()*1000000);
2416     /* Extract used hash */
2417     if ($hash == ""){
2418       $hash= strtolower($matches[1]);
2419     }
2421     $test = new  $available[$hash]($config);
2423   } else {
2424     // User MD5 by default
2425     $hash= "md5";
2426     $test = new  $available['md5']($config);
2427   }
2429   /* Feed password backends with information */
2430   $test->dn= $dn;
2431   $test->attrs= $attrs;
2432   $newpass= $test->generate_hash($password);
2434   // Update shadow timestamp?
2435   if (isset($attrs["shadowLastChange"][0])){
2436     $shadow= (int)(date("U") / 86400);
2437   } else {
2438     $shadow= 0;
2439   }
2441   // Write back modified entry
2442   $ldap->cd($dn);
2443   $attrs= array();
2445   // Not for groups
2446   if ($mode == 0){
2448     if ($shadow != 0){
2449       $attrs['shadowLastChange']= $shadow;
2450     }
2452     // Create SMB Password
2453     $attrs= generate_smb_nt_hash($password);
2454   }
2456  /* Readd ! if user was deactivated */
2457   if($deactivated){
2458     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2459   }
2461   $attrs['userPassword']= array();
2462   $attrs['userPassword']= $newpass;
2464   $ldap->modify($attrs);
2466   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2468   if ($ldap->error != 'Success') {
2469     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);
2470   } else {
2472     /* Run backend method for change/create */
2473     $test->set_password($password);
2475     /* Find postmodify entries for this class */
2476     $command= $config->search("password", "POSTMODIFY",array('menu'));
2478     if ($command != ""){
2479       /* Walk through attribute list */
2480       $command= preg_replace("/%userPassword/", $password, $command);
2481       $command= preg_replace("/%dn/", $dn, $command);
2483       if (check_command($command)){
2484         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2485         exec($command);
2486       } else {
2487         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2488         msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2489       }
2490     }
2491   }
2495 // Return something like array['sambaLMPassword']= "lalla..."
2496 function generate_smb_nt_hash($password)
2498   global $config;
2499   $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2500   @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2502   exec($tmp, $ar);
2503   flush();
2504   reset($ar);
2505   $hash= current($ar);
2506   if ($hash == "") {
2507     msg_dialog::display(_("Configuration error"), _("Setting for SMBHASH in gosa.conf is incorrect! Cannot change Samba password."), ERROR_DIALOG);
2508   } else {
2509     list($lm,$nt)= split (":", trim($hash));
2511     if ($config->current['SAMBAVERSION'] == 3) {
2512       $attrs['sambaLMPassword']= $lm;
2513       $attrs['sambaNTPassword']= $nt;
2514       $attrs['sambaPwdLastSet']= date('U');
2515       $attrs['sambaBadPasswordCount']= "0";
2516       $attrs['sambaBadPasswordTime']= "0";
2517     } else {
2518       $attrs['lmPassword']= $lm;
2519       $attrs['ntPassword']= $nt;
2520       $attrs['pwdLastSet']= date('U');
2521     }
2522     return($attrs);
2523   }
2527 function crypt_single($string,$enc_type )
2529   return( passwordMethod::crypt_single_str($string,$enc_type));
2533 function getEntryCSN($dn)
2535   global $config;
2536   if(empty($dn) || !is_object($config)){
2537     return("");
2538   }
2540   /* Get attribute that we should use as serial number */
2541   if(isset($config->current['UNIQ_IDENTIFIER'])){
2542     $attr = $config->current['UNIQ_IDENTIFIER'];
2543   }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2544     $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2545   }
2546   if(!empty($attr)){
2547     $ldap = $config->get_ldap_link();
2548     $ldap->cat($dn,array($attr));
2549     $csn = $ldap->fetch();
2550     if(isset($csn[$attr][0])){
2551       return($csn[$attr][0]);
2552     }
2553   }
2554   return("");
2558 /* Add a given objectClass to an attrs entry */
2559 function add_objectClass($classes, &$attrs)
2561   if (is_array($classes)){
2562     $list= $classes;
2563   } else {
2564     $list= array($classes);
2565   }
2567   foreach ($list as $class){
2568     $attrs['objectClass'][]= $class;
2569   }
2573 /* Removes a given objectClass from the attrs entry */
2574 function remove_objectClass($classes, &$attrs)
2576   if (isset($attrs['objectClass'])){
2577     /* Array? */
2578     if (is_array($classes)){
2579       $list= $classes;
2580     } else {
2581       $list= array($classes);
2582     }
2584     $tmp= array();
2585     foreach ($attrs['objectClass'] as $oc) {
2586       foreach ($list as $class){
2587         if ($oc != $class){
2588           $tmp[]= $oc;
2589         }
2590       }
2591     }
2592     $attrs['objectClass']= $tmp;
2593   }
2597 function display_error_page()
2599   $smarty= get_smarty();
2600   $smarty->display(get_template_path('headers.tpl'));
2601   echo "<body>".msg_dialog::get_dialogs()."</body></html>";
2602   exit();
2605 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2606 ?>