Code

87c667de61bfaab2ec2819d0d3f53ff136f86111
[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 (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 is_phone_nr($nr)
1106   if ($nr == ""){
1107     return (TRUE);
1108   }
1110   return preg_match ("/^[\/0-9 ()+*-]+$/", $nr);
1114 function is_dns_name($str)
1116   return(preg_match("/^[a-z0-9\.\-]*$/i",$str));
1120 function is_url($url)
1122   if ($url == ""){
1123     return (TRUE);
1124   }
1126   return preg_match ("/^(http|https):\/\/((?:[a-zA-Z0-9_-]+\.?)+):?(\d*)/", $url);
1130 function is_dn($dn)
1132   if ($dn == ""){
1133     return (TRUE);
1134   }
1136   return preg_match ("/^[a-z0-9 _-]+$/i", $dn);
1140 function strict_uid_mode()
1142   return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
1146 function get_uid_regexp()
1148   /* STRICT adds spaces and case insenstivity to the uid check.
1149      This is dangerous and should not be used. */
1150   if (strict_uid_mode()){
1151     return "^[a-z0-9_-]+$";
1152   } else {
1153     return "^[a-zA-Z0-9 _.-]+$";
1154   }
1158 function is_uid($uid)
1160   global $config;
1162   if ($uid == ""){
1163     return (TRUE);
1164   }
1166   /* STRICT adds spaces and case insenstivity to the uid check.
1167      This is dangerous and should not be used. */
1168   if (strict_uid_mode()){
1169     return preg_match ("/^[a-z0-9_-]+$/", $uid);
1170   } else {
1171     return preg_match ("/^[a-z0-9 _.-]+$/i", $uid);
1172   }
1176 function is_ip($ip)
1178   return preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/", $ip);
1182 function is_mac($mac)
1184   return preg_match("/^[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]$/i", $mac);
1188 /* Checks if the given ip address dosen't match 
1189     "is_ip" because there is also a sub net mask given */
1190 function is_ip_with_subnetmask($ip)
1192         /* Generate list of valid submasks */
1193         $res = array();
1194         for($e = 0 ; $e <= 32; $e++){
1195                 $res[$e] = $e;
1196         }
1197         $i[0] =255;
1198         $i[1] =255;
1199         $i[2] =255;
1200         $i[3] =255;
1201         for($a= 3 ; $a >= 0 ; $a --){
1202                 $c = 1;
1203                 while($i[$a] > 0 ){
1204                         $str  = $i[0].".".$i[1].".".$i[2].".".$i[3];
1205                         $res[$str] = $str;
1206                         $i[$a] -=$c;
1207                         $c = 2*$c;
1208                 }
1209         }
1210         $res["0.0.0.0"] = "0.0.0.0";
1211         if(preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1212                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1213                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1214                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/", $ip)){
1215                 $mask = preg_replace("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1216                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1217                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.".
1218                         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/","",$ip);
1220                 $mask = preg_replace("/^\//","",$mask);
1221                 if((in_array("$mask",$res)) && preg_match("/^[0-9\.]/",$mask)){
1222                         return(TRUE);
1223                 }
1224         }
1225         return(FALSE);
1229 /* Simple is domain check, it checks if the given string looks like "string(...).string" */
1230 function is_domain($str)
1232   return(preg_match("/^([a-z0-9i\-]*)\.[a-z0-9]*$/i",$str));
1236 function is_id($id)
1238   if ($id == ""){
1239     return (FALSE);
1240   }
1242   return preg_match ("/^[0-9]+$/", $id);
1246 function is_path($path)
1248   if ($path == ""){
1249     return (TRUE);
1250   }
1251   if (!preg_match('/^[a-z0-9%\/_.+-]+$/i', $path)){
1252     return (FALSE);
1253   }
1255   return preg_match ("/\/.+$/", $path);
1259 function is_email($address, $template= FALSE)
1261   if ($address == ""){
1262     return (TRUE);
1263   }
1264   if ($template){
1265     return preg_match ("/^[._a-z0-9%-]+@[_a-z0-9-]+(\.[a-z0-9-]+)(\.[a-z0-9-]+)*$/i",
1266         $address);
1267   } else {
1268     return preg_match ("/^[._a-z0-9-]+@[_a-z0-9-]+(\.[a-z0-9i-]+)(\.[a-z0-9-]+)*$/i",
1269         $address);
1270   }
1274 function print_red()
1276   trigger_error("Use of obsolete print_red");
1277   /* Check number of arguments */
1278   if (func_num_args() < 1){
1279     return;
1280   }
1282   /* Get arguments, save string */
1283   $array = func_get_args();
1284   $string= $array[0];
1286   /* Step through arguments */
1287   for ($i= 1; $i<count($array); $i++){
1288     $string= preg_replace ("/%s/", $array[$i], $string, 1);
1289   }
1291   /* If DEBUGLEVEL is set, we're in web mode, use textual output in
1292      the other case... */
1293   if($string !== NULL){
1294     if (preg_match("/"._("LDAP error:")."/", $string)){
1295       $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.");
1296     } else {
1297       if (!preg_match('/[.!?]$/', $string)){
1298         $string.= ".";
1299       }
1300       $string= preg_replace('/<br>/', ' ', $string);
1301       $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
1302       $addmsg = "";
1303     }
1304     if(empty($addmsg)){
1305       $addmsg = _("Error");
1306     }
1307     msg_dialog::display($addmsg, $string,ERROR_DIALOG);
1308     return;
1309   }else{
1310     return;
1311   }
1316 function gen_locked_message($user, $dn)
1318   global $plug, $config;
1320   session::set('dn', $dn);
1321   $remove= false;
1323   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1324   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1326     $LOCK_VARS_USED   = array();
1327     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1329     foreach($LOCK_VARS_TO_USE as $name){
1331       if(empty($name)){
1332         continue;
1333       }
1335       foreach($_POST as $Pname => $Pvalue){
1336         if(preg_match($name,$Pname)){
1337           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1338         }
1339       }
1341       foreach($_GET as $Pname => $Pvalue){
1342         if(preg_match($name,$Pname)){
1343           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1344         }
1345       }
1346     }
1347     session::set('LOCK_VARS_TO_USE',array());
1348     session::set('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1349   }
1351   /* Prepare and show template */
1352   $smarty= get_smarty();
1353   
1354   if(is_array($dn)){
1355     $msg = "<pre>";
1356     foreach($dn as $sub_dn){
1357       $msg .= "\n".$sub_dn.", ";
1358     }
1359     $msg = preg_replace("/, $/","</pre>",$msg);
1360   }else{
1361     $msg = $dn;
1362   }
1364   $smarty->assign ("dn", $msg);
1365   if ($remove){
1366     $smarty->assign ("action", _("Continue anyway"));
1367   } else {
1368     $smarty->assign ("action", _("Edit anyway"));
1369   }
1370   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
1372   return ($smarty->fetch (get_template_path('islocked.tpl')));
1376 function to_string ($value)
1378   /* If this is an array, generate a text blob */
1379   if (is_array($value)){
1380     $ret= "";
1381     foreach ($value as $line){
1382       $ret.= $line."<br>\n";
1383     }
1384     return ($ret);
1385   } else {
1386     return ($value);
1387   }
1391 function get_printer_list()
1393   global $config;
1394   $res = array();
1395   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1396   foreach($data as $attrs ){
1397     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1398   }
1399   return $res;
1403 function show_errors($message)
1405   $complete= "";
1407   /* Assemble the message array to a plain string */
1408   foreach ($message as $error){
1409     if ($complete == ""){
1410       $complete= $error;
1411     } else {
1412       $complete= "$error<br>$complete";
1413     }
1414   }
1416   /* Fill ERROR variable with nice error dialog */
1417   msg_dialog::display(_("Error"), $complete, ERROR_DIALOG);
1421 function show_ldap_error($message, $addon= "")
1423   if (!preg_match("/Success/i", $message)){
1424     if ($addon == ""){
1425       msg_dialog::display(_("LDAP error:"), $message, ERROR_DIALOG);
1426     } else {
1427       if(!preg_match("/No such object/i",$message)){
1428         msg_dialog::display(sprintf(_("LDAP error in plugin '%s':"),"<i>".$addon."</i>"),$message,ERROR_DIALOG);
1429       }
1430     }
1431     return TRUE;
1432   } else {
1433     return FALSE;
1434   }
1438 function rewrite($s)
1440   global $REWRITE;
1442   foreach ($REWRITE as $key => $val){
1443     $s= preg_replace("/$key/", "$val", $s);
1444   }
1446   return ($s);
1450 function dn2base($dn)
1452   global $config;
1454   if (get_people_ou() != ""){
1455     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1456   }
1457   if (get_groups_ou() != ""){
1458     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1459   }
1460   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1462   return ($base);
1467 function check_command($cmdline)
1469   $cmd= preg_replace("/ .*$/", "", $cmdline);
1471   /* Check if command exists in filesystem */
1472   if (!file_exists($cmd)){
1473     return (FALSE);
1474   }
1476   /* Check if command is executable */
1477   if (!is_executable($cmd)){
1478     return (FALSE);
1479   }
1481   return (TRUE);
1485 function print_header($image, $headline, $info= "")
1487   $display= "<div class=\"plugtop\">\n";
1488   $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";
1489   $display.= "</div>\n";
1491   if ($info != ""){
1492     $display.= "<div class=\"pluginfo\">\n";
1493     $display.= "$info";
1494     $display.= "</div>\n";
1495   } else {
1496     $display.= "<div style=\"height:5px;\">\n";
1497     $display.= "&nbsp;";
1498     $display.= "</div>\n";
1499   }
1500   return ($display);
1504 function range_selector($dcnt,$start,$range=25,$post_var=false)
1507   /* Entries shown left and right from the selected entry */
1508   $max_entries= 10;
1510   /* Initialize and take care that max_entries is even */
1511   $output="";
1512   if ($max_entries & 1){
1513     $max_entries++;
1514   }
1516   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1517     $range= $_POST[$post_var];
1518   }
1520   /* Prevent output to start or end out of range */
1521   if ($start < 0 ){
1522     $start= 0 ;
1523   }
1524   if ($start >= $dcnt){
1525     $start= $range * (int)(($dcnt / $range) + 0.5);
1526   }
1528   $numpages= (($dcnt / $range));
1529   if(((int)($numpages))!=($numpages)){
1530     $numpages = (int)$numpages + 1;
1531   }
1532   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1533     return ("");
1534   }
1535   $ppage= (int)(($start / $range) + 0.5);
1538   /* Align selected page to +/- max_entries/2 */
1539   $begin= $ppage - $max_entries/2;
1540   $end= $ppage + $max_entries/2;
1542   /* Adjust begin/end, so that the selected value is somewhere in
1543      the middle and the size is max_entries if possible */
1544   if ($begin < 0){
1545     $end-= $begin + 1;
1546     $begin= 0;
1547   }
1548   if ($end > $numpages) {
1549     $end= $numpages;
1550   }
1551   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1552     $begin= $end - $max_entries;
1553   }
1555   if($post_var){
1556     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1557       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1558   }else{
1559     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1560   }
1562   /* Draw decrement */
1563   if ($start > 0 ) {
1564     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1565       (($start-$range))."\">".
1566       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1567   }
1569   /* Draw pages */
1570   for ($i= $begin; $i < $end; $i++) {
1571     if ($ppage == $i){
1572       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1573         validate($_GET['plug'])."&amp;start=".
1574         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1575     } else {
1576       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1577         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1578     }
1579   }
1581   /* Draw increment */
1582   if($start < ($dcnt-$range)) {
1583     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1584       (($start+($range)))."\">".
1585       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1586   }
1588   if(($post_var)&&($numpages)){
1589     $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()'>";
1590     foreach(array(20,50,100,200,"all") as $num){
1591       if($num == "all"){
1592         $var = 10000;
1593       }else{
1594         $var = $num;
1595       }
1596       if($var == $range){
1597         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1598       }else{  
1599         $output.="\n<option value='".$var."'>".$num."</option>";
1600       }
1601     }
1602     $output.=  "</select></td></tr></table></div>";
1603   }else{
1604     $output.= "</div>";
1605   }
1607   return($output);
1611 function apply_filter()
1613   $apply= "";
1615   $apply= ''.
1616     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1617     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1619   return ($apply);
1623 function back_to_main()
1625   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1626     _("Back").'"></p><input type="hidden" name="ignore">';
1628   return ($string);
1632 function normalize_netmask($netmask)
1634   /* Check for notation of netmask */
1635   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1636     $num= (int)($netmask);
1637     $netmask= "";
1639     for ($byte= 0; $byte<4; $byte++){
1640       $result=0;
1642       for ($i= 7; $i>=0; $i--){
1643         if ($num-- > 0){
1644           $result+= pow(2,$i);
1645         }
1646       }
1648       $netmask.= $result.".";
1649     }
1651     return (preg_replace('/\.$/', '', $netmask));
1652   }
1654   return ($netmask);
1658 function netmask_to_bits($netmask)
1660   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1661   $res= 0;
1663   for ($n= 0; $n<4; $n++){
1664     $start= 255;
1665     $name= "nm$n";
1667     for ($i= 0; $i<8; $i++){
1668       if ($start == (int)($$name)){
1669         $res+= 8 - $i;
1670         break;
1671       }
1672       $start-= pow(2,$i);
1673     }
1674   }
1676   return ($res);
1680 function recurse($rule, $variables)
1682   $result= array();
1684   if (!count($variables)){
1685     return array($rule);
1686   }
1688   reset($variables);
1689   $key= key($variables);
1690   $val= current($variables);
1691   unset ($variables[$key]);
1693   foreach($val as $possibility){
1694     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1695     $result= array_merge($result, recurse($nrule, $variables));
1696   }
1698   return ($result);
1702 function expand_id($rule, $attributes)
1704   /* Check for id rule */
1705   if(preg_match('/^id(:|#)\d+$/',$rule)){
1706     return (array("\{$rule}"));
1707   }
1709   /* Check for clean attribute */
1710   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1711     $rule= preg_replace('/^%/', '', $rule);
1712     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1713     return (array($val));
1714   }
1716   /* Check for attribute with parameters */
1717   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1718     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1719     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1720     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1721     $start= preg_replace ('/-.*$/', '', $param);
1722     $stop = preg_replace ('/^[^-]+-/', '', $param);
1724     /* Assemble results */
1725     $result= array();
1726     for ($i= $start; $i<= $stop; $i++){
1727       $result[]= substr($val, 0, $i);
1728     }
1729     return ($result);
1730   }
1732   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1733   return (array($rule));
1737 function gen_uids($rule, $attributes)
1739   global $config;
1741   /* Search for keys and fill the variables array with all 
1742      possible values for that key. */
1743   $part= "";
1744   $trigger= false;
1745   $stripped= "";
1746   $variables= array();
1748   for ($pos= 0; $pos < strlen($rule); $pos++){
1750     if ($rule[$pos] == "{" ){
1751       $trigger= true;
1752       $part= "";
1753       continue;
1754     }
1756     if ($rule[$pos] == "}" ){
1757       $variables[$pos]= expand_id($part, $attributes);
1758       $stripped.= "{".$pos."}";
1759       $trigger= false;
1760       continue;
1761     }
1763     if ($trigger){
1764       $part.= $rule[$pos];
1765     } else {
1766       $stripped.= $rule[$pos];
1767     }
1768   }
1770   /* Recurse through all possible combinations */
1771   $proposed= recurse($stripped, $variables);
1773   /* Get list of used ID's */
1774   $used= array();
1775   $ldap= $config->get_ldap_link();
1776   $ldap->cd($config->current['BASE']);
1777   $ldap->search('(uid=*)');
1779   while($attrs= $ldap->fetch()){
1780     $used[]= $attrs['uid'][0];
1781   }
1783   /* Remove used uids and watch out for id tags */
1784   $ret= array();
1785   foreach($proposed as $uid){
1787     /* Check for id tag and modify uid if needed */
1788     if(preg_match('/\{id:\d+}/',$uid)){
1789       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1791       for ($i= 0; $i < pow(10,$size); $i++){
1792         $number= sprintf("%0".$size."d", $i);
1793         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1794         if (!in_array($res, $used)){
1795           $uid= $res;
1796           break;
1797         }
1798       }
1799     }
1801   if(preg_match('/\{id#\d+}/',$uid)){
1802     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1804     while (true){
1805       mt_srand((double) microtime()*1000000);
1806       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1807       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1808       if (!in_array($res, $used)){
1809         $uid= $res;
1810         break;
1811       }
1812     }
1813   }
1815 /* Don't assign used ones */
1816 if (!in_array($uid, $used)){
1817   $ret[]= $uid;
1821 return(array_unique($ret));
1825 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1826    Need to convert... */
1827 function to_byte($value) {
1828   $value= strtolower(trim($value));
1830   if(!is_numeric(substr($value, -1))) {
1832     switch(substr($value, -1)) {
1833       case 'g':
1834         $mult= 1073741824;
1835         break;
1836       case 'm':
1837         $mult= 1048576;
1838         break;
1839       case 'k':
1840         $mult= 1024;
1841         break;
1842     }
1844     return ($mult * (int)substr($value, 0, -1));
1845   } else {
1846     return $value;
1847   }
1851 function in_array_ics($value, $items)
1853   if (!is_array($items)){
1854     return (FALSE);
1855   }
1857   foreach ($items as $item){
1858     if (strcasecmp($item, $value) == 0) {
1859       return (TRUE);
1860     }
1861   }
1863   return (FALSE);
1864
1867 function generate_alphabet($count= 10)
1869   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1870   $alphabet= "";
1871   $c= 0;
1873   /* Fill cells with charaters */
1874   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1875     if ($c == 0){
1876       $alphabet.= "<tr>";
1877     }
1879     $ch = mb_substr($characters, $i, 1, "UTF8");
1880     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1881       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1883     if ($c++ == $count){
1884       $alphabet.= "</tr>";
1885       $c= 0;
1886     }
1887   }
1889   /* Fill remaining cells */
1890   while ($c++ <= $count){
1891     $alphabet.= "<td>&nbsp;</td>";
1892   }
1894   return ($alphabet);
1898 function validate($string)
1900   return (strip_tags(preg_replace('/\0/', '', $string)));
1904 function get_gosa_version()
1906   global $svn_revision, $svn_path;
1908   /* Extract informations */
1909   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1911   /* Release or development? */
1912   if (preg_match('%/gosa/trunk/%', $svn_path)){
1913     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1914   } else {
1915     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1916     return (sprintf(_("GOsa $release"), $revision));
1917   }
1921 function rmdirRecursive($path, $followLinks=false) {
1922   $dir= opendir($path);
1923   while($entry= readdir($dir)) {
1924     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1925       unlink($path."/".$entry);
1926     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1927       rmdirRecursive($path."/".$entry);
1928     }
1929   }
1930   closedir($dir);
1931   return rmdir($path);
1935 function scan_directory($path,$sort_desc=false)
1937   $ret = false;
1939   /* is this a dir ? */
1940   if(is_dir($path)) {
1942     /* is this path a readable one */
1943     if(is_readable($path)){
1945       /* Get contents and write it into an array */   
1946       $ret = array();    
1948       $dir = opendir($path);
1950       /* Is this a correct result ?*/
1951       if($dir){
1952         while($fp = readdir($dir))
1953           $ret[]= $fp;
1954       }
1955     }
1956   }
1957   /* Sort array ascending , like scandir */
1958   sort($ret);
1960   /* Sort descending if parameter is sort_desc is set */
1961   if($sort_desc) {
1962     $ret = array_reverse($ret);
1963   }
1965   return($ret);
1969 function clean_smarty_compile_dir($directory)
1971   global $svn_revision;
1973   if(is_dir($directory) && is_readable($directory)) {
1974     // Set revision filename to REVISION
1975     $revision_file= $directory."/REVISION";
1977     /* Is there a stamp containing the current revision? */
1978     if(!file_exists($revision_file)) {
1979       // create revision file
1980       create_revision($revision_file, $svn_revision);
1981     } else {
1982       # check for "$config->...['CONFIG']/revision" and the
1983       # contents should match the revision number
1984       if(!compare_revision($revision_file, $svn_revision)){
1985         // If revision differs, clean compile directory
1986         foreach(scan_directory($directory) as $file) {
1987           if(($file==".")||($file=="..")) continue;
1988           if( is_file($directory."/".$file) &&
1989               is_writable($directory."/".$file)) {
1990             // delete file
1991             if(!unlink($directory."/".$file)) {
1992               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1993               // This should never be reached
1994             }
1995           } elseif(is_dir($directory."/".$file) &&
1996               is_writable($directory."/".$file)) {
1997             // Just recursively delete it
1998             rmdirRecursive($directory."/".$file);
1999           }
2000         }
2001         // We should now create a fresh revision file
2002         clean_smarty_compile_dir($directory);
2003       } else {
2004         // Revision matches, nothing to do
2005       }
2006     }
2007   } else {
2008     // Smarty compile dir is not accessible
2009     // (Smarty will warn about this)
2010   }
2014 function create_revision($revision_file, $revision)
2016   $result= false;
2018   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
2019     if($fh= fopen($revision_file, "w")) {
2020       if(fwrite($fh, $revision)) {
2021         $result= true;
2022       }
2023     }
2024     fclose($fh);
2025   } else {
2026     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2027   }
2029   return $result;
2033 function compare_revision($revision_file, $revision)
2035   // false means revision differs
2036   $result= false;
2038   if(file_exists($revision_file) && is_readable($revision_file)) {
2039     // Open file
2040     if($fh= fopen($revision_file, "r")) {
2041       // Compare File contents with current revision
2042       if($revision == fread($fh, filesize($revision_file))) {
2043         $result= true;
2044       }
2045     } else {
2046       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
2047     }
2048     // Close file
2049     fclose($fh);
2050   }
2052   return $result;
2056 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
2058   $str = ""; // Our return value will be saved in this var
2060   $color  = dechex($percentage+150);
2061   $color2 = dechex(150 - $percentage);
2062   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
2064   $progress = (int)(($percentage /100)*$width);
2066   /* Abort printing out percentage, if divs are to small */
2069   /* If theres a better solution for this, use it... */
2070   $str = "
2071     <div style=\" width:".($width)."px; 
2072     height:".($height)."px;
2073   background-color:#000000;
2074 padding:1px;\">
2076           <div style=\" width:".($width)."px;
2077         background-color:#$bgcolor;
2078 height:".($height)."px;\">
2080          <div style=\" width:".$progress."px;
2081 height:".$height."px;
2082        background-color:#".$color2.$color2.$color."; \">";
2085        if(($height >10)&&($showvalue)){
2086          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
2087            <b>".$percentage."%</b>
2088            </font>";
2089        }
2091        $str.= "</div></div></div>";
2093        return($str);
2097 function array_key_ics($ikey, $items)
2099   /* Gather keys, make them lowercase */
2100   $tmp= array();
2101   foreach ($items as $key => $value){
2102     $tmp[strtolower($key)]= $key;
2103   }
2105   if (isset($tmp[strtolower($ikey)])){
2106     return($tmp[strtolower($ikey)]);
2107   }
2109   return ("");
2113 function array_differs($src, $dst)
2115   /* If the count is differing, the arrays differ */
2116   if (count ($src) != count ($dst)){
2117     return (TRUE);
2118   }
2120   /* So the count is the same - lets check the contents */
2121   $differs= FALSE;
2122   foreach($src as $value){
2123     if (!in_array($value, $dst)){
2124       $differs= TRUE;
2125     }
2126   }
2128   return ($differs);
2132 function saveFilter($a_filter, $values)
2134   if (isset($_POST['regexit'])){
2135     $a_filter["regex"]= $_POST['regexit'];
2137     foreach($values as $type){
2138       if (isset($_POST[$type])) {
2139         $a_filter[$type]= "checked";
2140       } else {
2141         $a_filter[$type]= "";
2142       }
2143     }
2144   }
2146   /* React on alphabet links if needed */
2147   if (isset($_GET['search'])){
2148     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2149     if ($s == "**"){
2150       $s= "*";
2151     }
2152     $a_filter['regex']= $s;
2153   }
2155   return ($a_filter);
2159 /* Escape all preg_* relevant characters */
2160 function normalizePreg($input)
2162   return (addcslashes($input, '[]()|/.*+-'));
2166 /* Escape all LDAP filter relevant characters */
2167 function normalizeLdap($input)
2169   return (addcslashes($input, '()|'));
2173 /* Resturns the difference between to microtime() results in float  */
2174 function get_MicroTimeDiff($start , $stop)
2176   $a = split("\ ",$start);
2177   $b = split("\ ",$stop);
2179   $secs = $b[1] - $a[1];
2180   $msecs= $b[0] - $a[0]; 
2182   $ret = (float) ($secs+ $msecs);
2183   return($ret);
2187 /* Check if the given department name is valid */
2188 function is_department_name_reserved($name,$base)
2190   $reservedName = array("systems","apps","incomming","internal","accounts","fax","addressbook",
2191                           preg_replace("/ou=(.*),/","\\1",get_people_ou()),
2192                           preg_replace("/ou=(.*),/","\\1",get_groups_ou()));
2193   $follwedNames['/ou=fai,ou=configs,ou=systems,/'] = array("fai","hooks","templates","scripts","disk","packages","variables","profiles");
2195   /* Check if name is one of the reserved names */
2196   if(in_array_ics($name,$reservedName)) {
2197     return(true);
2198   }
2200   /* Check all follow combinations if name is in array && parent base == array_key, return false*/
2201   foreach($follwedNames as $key => $names){
2202     if((in_array_ics($name,$names)) && (preg_match($key,$base))){
2203       return(true);
2204     }
2205   }
2206   return(false);
2210 function get_base_dir()
2212   global $BASE_DIR;
2214   return $BASE_DIR;
2218 function obj_is_readable($dn, $object, $attribute)
2220   global $ui;
2222   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2226 function obj_is_writable($dn, $object, $attribute)
2228   global $ui;
2230   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2234 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2236   /* Initialize variables */
2237   $ret  = array("count" => 0);  // Set count to 0
2238   $next = true;                 // if false, then skip next loops and return
2239   $cnt  = 0;                    // Current number of loops
2240   $max  = 100;                  // Just for security, prevent looops
2241   $ldap = NULL;                 // To check if created result a valid
2242   $keep = "";                   // save last failed parse string
2244   /* Check each parsed dn in ldap ? */
2245   if($config!==NULL && $verify_in_ldap){
2246     $ldap = $config->get_ldap_link();
2247   }
2249   /* Lets start */
2250   $called = false;
2251   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2253     $cnt ++;
2254     if(!preg_match("/,/",$dn)){
2255       $next = false;
2256     }
2257     $object = preg_replace("/[,].*$/","",$dn);
2258     $dn     = preg_replace("/^[^,]+,/","",$dn);
2260     $called = true;
2262     /* Check if current dn is valid */
2263     if($ldap!==NULL){
2264       $ldap->cd($dn);
2265       $ldap->cat($dn,array("dn"));
2266       if($ldap->count()){
2267         $ret[]  = $keep.$object;
2268         $keep   = "";
2269       }else{
2270         $keep  .= $object.",";
2271       }
2272     }else{
2273       $ret[]  = $keep.$object;
2274       $keep   = "";
2275     }
2276   }
2278   /* No dn was posted */
2279   if($cnt == 0 && !empty($dn)){
2280     $ret[] = $dn;
2281   }
2283   /* Append the rest */
2284   $test = $keep.$dn;
2285   if($called && !empty($test)){
2286     $ret[] = $keep.$dn;
2287   }
2288   $ret['count'] = count($ret) - 1;
2290   return($ret);
2294 function get_base_from_hook($dn, $attrib)
2296   global $config;
2298   if (isset($config->current['BASE_HOOK'])){
2299     
2300     /* Call hook script - if present */
2301     $command= $config->current['BASE_HOOK'];
2303     if ($command != ""){
2304       $command.= " '".LDAP::fix($dn)."' $attrib";
2305       if (check_command($command)){
2306         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2307         exec($command, $output);
2308         if (preg_match("/^[0-9]+$/", $output[0])){
2309           return ($output[0]);
2310         } else {
2311           msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2312           return ($config->current['UIDBASE']);
2313         }
2314       } else {
2315         msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2316         return ($config->current['UIDBASE']);
2317       }
2319     } else {
2321       msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
2322       return ($config->current['UIDBASE']);
2324     }
2325   }
2329 function check_schema_version($class, $version)
2331   return preg_match("/\(v$version\)/", $class['DESC']);
2335 function check_schema($cfg,$rfc2307bis = FALSE)
2337   $messages= array();
2339   /* Get objectclasses */
2340   $ldap = new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']);
2341   $objectclasses = $ldap->get_objectclasses();
2342   if(count($objectclasses) == 0){
2343     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2344   }
2346   /* This is the default block used for each entry.
2347    *  to avoid unset indexes.
2348    */
2349   $def_check = array("REQUIRED_VERSION" => "0",
2350       "SCHEMA_FILES"     => array(),
2351       "CLASSES_REQUIRED" => array(),
2352       "STATUS"           => FALSE,
2353       "IS_MUST_HAVE"     => FALSE,
2354       "MSG"              => "",
2355       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2357   /* The gosa base schema */
2358   $checks['gosaObject'] = $def_check;
2359   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2360   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2361   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2362   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2364   /* GOsa Account class */
2365   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2366   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2367   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2368   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2369   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2371   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2372   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2373   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2374   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2375   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2376   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2378   /* Some other checks */
2379   foreach(array(
2380         "gosaCacheEntry"        => array("version" => "2.4"),
2381         "gosaDepartment"        => array("version" => "2.4"),
2382         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2383         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2384         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2385         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2386         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2387         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2388         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2389         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2390         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2391         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2392         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2393         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2394         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2395         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2396         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2397         "goLdapServer"          => array("version" => "2.4"),
2398         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2399         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2400         "goKrbServer"           => array("version" => "2.4"),
2401         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2402         ) as $name => $values){
2404           $checks[$name] = $def_check;
2405           if(isset($values['version'])){
2406             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2407           }
2408           if(isset($values['file'])){
2409             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2410           }
2411           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2412         }
2413   foreach($checks as $name => $value){
2414     foreach($value['CLASSES_REQUIRED'] as $class){
2416       if(!isset($objectclasses[$name])){
2417         $checks[$name]['STATUS'] = FALSE;
2418         if($value['IS_MUST_HAVE']){
2419           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2420         }else{
2421           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2422         }
2423       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2424         $checks[$name]['STATUS'] = FALSE;
2426         if($value['IS_MUST_HAVE']){
2427           $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2428         }else{
2429           $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2430         }
2431       }else{
2432         $checks[$name]['STATUS'] = TRUE;
2433         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2434       }
2435     }
2436   }
2438   $tmp = $objectclasses;
2440   /* The gosa base schema */
2441   $checks['posixGroup'] = $def_check;
2442   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2443   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2444   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2445   $checks['posixGroup']['STATUS']           = TRUE;
2446   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2447   $checks['posixGroup']['MSG']              = "";
2448   $checks['posixGroup']['INFO']             = "";
2450   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2451   if(isset($tmp['posixGroup'])){
2453     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2454       $checks['posixGroup']['STATUS']           = FALSE;
2455       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2456       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2457     }
2458     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2459       $checks['posixGroup']['STATUS']           = FALSE;
2460       $checks['posixGroup']['MSG']              = _("You have disabled the rfc2307bis option on the 'ldap setup' step, but your schema   configuration do not support this option.");
2461       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2462     }
2463   }
2465   return($checks);
2469 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2471   $tmp = array(
2472         "de_DE" => "German",
2473         "fr_FR" => "French",
2474         "it_IT" => "Italian",
2475         "es_ES" => "Spanish",
2476         "en_US" => "English",
2477         "nl_NL" => "Dutch",
2478         "pl_PL" => "Polish",
2479         "sv_SE" => "Swedish",
2480         "zh_CN" => "Chinese",
2481         "ru_RU" => "Russian");
2482   
2483   $tmp2= array(
2484         "de_DE" => _("German"),
2485         "fr_FR" => _("French"),
2486         "it_IT" => _("Italian"),
2487         "es_ES" => _("Spanish"),
2488         "en_US" => _("English"),
2489         "nl_NL" => _("Dutch"),
2490         "pl_PL" => _("Polish"),
2491         "sv_SE" => _("Swedish"),
2492         "zh_CN" => _("Chinese"),
2493         "ru_RU" => _("Russian"));
2495   $ret = array();
2496   if($languages_in_own_language){
2498     $old_lang = setlocale(LC_ALL, 0);
2499     foreach($tmp as $key => $name){
2500       $lang = $key.".UTF-8";
2501       setlocale(LC_ALL, $lang);
2502       if($strip_region_tag){
2503         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2504       }else{
2505         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2506       }
2507     }
2508     setlocale(LC_ALL, $old_lang);
2509   }else{
2510     foreach($tmp as $key => $name){
2511       if($strip_region_tag){
2512         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2513       }else{
2514         $ret[$key] = _($name);
2515       }
2516     }
2517   }
2518   return($ret);
2522 /* Returns contents of the given POST variable and check magic quotes settings */
2523 function get_post($name)
2525   if(!isset($_POST[$name])){
2526     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2527     return(FALSE);
2528   }
2529   if(get_magic_quotes_gpc()){
2530     return(stripcslashes($_POST[$name]));
2531   }else{
2532     return($_POST[$name]);
2533   }
2537 /* Check if $ip1 and $ip2 represents a valid IP range 
2538  *  returns TRUE in case of a valid range, FALSE in case of an error. 
2539  */
2540 function is_ip_range($ip1,$ip2)
2542   if(!is_ip($ip1) || !is_ip($ip2)){
2543     return(FALSE);
2544   }else{
2545     $ar1 = split("\.",$ip1);
2546     $var1 = $ar1[0] * (16777216) + $ar1[1] * (65536) + $ar1[2] * (256) + $ar1[3];
2548     $ar2 = split("\.",$ip2);
2549     $var2 = $ar2[0] * (16777216) + $ar2[1] * (65536) + $ar2[2] * (256) + $ar2[3];
2550     return($var1 < $var2);
2551   }
2555 /* Check if the specified IP address $address is inside the given network */
2556 function is_in_network($network, $netmask, $address)
2558   $nw= split('\.', $network);
2559   $nm= split('\.', $netmask);
2560   $ad= split('\.', $address);
2562   /* Generate inverted netmask */
2563   for ($i= 0; $i<4; $i++){
2564     $ni[$i]= 255-$nm[$i];
2565     $la[$i]= $nw[$i] | $ni[$i];
2566   }
2568   /* Transform to integer */
2569   $first= $nw[0] * (16777216) + $nw[1] * (65536) + $nw[2] * (256) + $nw[3];
2570   $curr=  $ad[0] * (16777216) + $ad[1] * (65536) + $ad[2] * (256) + $ad[3];
2571   $last=  $la[0] * (16777216) + $la[1] * (65536) + $la[2] * (256) + $la[3];
2573   return ($first < $curr&& $last > $curr);
2577 /* Return class name in correct case */
2578 function get_correct_class_name($cls)
2580   global $class_mapping;
2581   if(isset($class_mapping) && is_array($class_mapping)){
2582     foreach($class_mapping as $class => $file){
2583       if(preg_match("/^".$cls."$/i",$class)){
2584         return($class);
2585       }
2586     }
2587   }
2588   return(FALSE);
2592 // change_password, changes the Password, of the given dn
2593 function change_password ($dn, $password, $mode=0, $hash= "")
2595   global $config;
2596   $newpass= "";
2598   /* Convert to lower. Methods are lowercase */
2599   $hash= strtolower($hash);
2601   // Get all available encryption Methods
2603   // NON STATIC CALL :)
2604   $tmp = new passwordMethod(session::get('config'));
2605   $available = $tmp->get_available_methods();
2607   // read current password entry for $dn, to detect the encryption Method
2608   $ldap       = $config->get_ldap_link();
2609   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2610   $attrs      = $ldap->fetch ();
2612   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2613   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2614     $deactivated = TRUE;
2615   }else{
2616     $deactivated = FALSE;
2617   }
2619   /* Is ensure that clear passwords will stay clear */
2620   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2621     $hash = "clear";
2622   }
2624   // Detect the encryption Method
2625   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2627     /* Check for supported algorithm */
2628     mt_srand((double) microtime()*1000000);
2630     /* Extract used hash */
2631     if ($hash == ""){
2632       $hash= strtolower($matches[1]);
2633     }
2635     $test = new  $available[$hash]($config);
2637   } else {
2638     // User MD5 by default
2639     $hash= "md5";
2640     $test = new  $available['md5']($config);
2641   }
2643   /* Feed password backends with information */
2644   $test->dn= $dn;
2645   $test->attrs= $attrs;
2646   $newpass= $test->generate_hash($password);
2648   // Update shadow timestamp?
2649   if (isset($attrs["shadowLastChange"][0])){
2650     $shadow= (int)(date("U") / 86400);
2651   } else {
2652     $shadow= 0;
2653   }
2655   // Write back modified entry
2656   $ldap->cd($dn);
2657   $attrs= array();
2659   // Not for groups
2660   if ($mode == 0){
2662     if ($shadow != 0){
2663       $attrs['shadowLastChange']= $shadow;
2664     }
2666     // Create SMB Password
2667     $attrs= generate_smb_nt_hash($password);
2668   }
2670  /* Readd ! if user was deactivated */
2671   if($deactivated){
2672     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2673   }
2675   $attrs['userPassword']= array();
2676   $attrs['userPassword']= $newpass;
2678   $ldap->modify($attrs);
2680   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2682   if ($ldap->error != 'Success') {
2683     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);
2684   } else {
2686     /* Run backend method for change/create */
2687     $test->set_password($password);
2689     /* Find postmodify entries for this class */
2690     $command= $config->search("password", "POSTMODIFY",array('menu'));
2692     if ($command != ""){
2693       /* Walk through attribute list */
2694       $command= preg_replace("/%userPassword/", $password, $command);
2695       $command= preg_replace("/%dn/", $dn, $command);
2697       if (check_command($command)){
2698         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2699         exec($command);
2700       } else {
2701         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2702         msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2703       }
2704     }
2705   }
2709 // Return something like array['sambaLMPassword']= "lalla..."
2710 function generate_smb_nt_hash($password)
2712   global $config;
2713   $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
2714   @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2716   exec($tmp, $ar);
2717   flush();
2718   reset($ar);
2719   $hash= current($ar);
2720   if ($hash == "") {
2721     msg_dialog::display(_("Configuration error"), _("Setting for SMBHASH in gosa.conf is incorrect! Cannot change Samba password."), ERROR_DIALOG);
2722   } else {
2723     list($lm,$nt)= split (":", trim($hash));
2725     if ($config->current['SAMBAVERSION'] == 3) {
2726       $attrs['sambaLMPassword']= $lm;
2727       $attrs['sambaNTPassword']= $nt;
2728       $attrs['sambaPwdLastSet']= date('U');
2729       $attrs['sambaBadPasswordCount']= "0";
2730       $attrs['sambaBadPasswordTime']= "0";
2731     } else {
2732       $attrs['lmPassword']= $lm;
2733       $attrs['ntPassword']= $nt;
2734       $attrs['pwdLastSet']= date('U');
2735     }
2736     return($attrs);
2737   }
2741 function crypt_single($string,$enc_type )
2743   return( passwordMethod::crypt_single_str($string,$enc_type));
2747 function getEntryCSN($dn)
2749   global $config;
2750   if(empty($dn) || !is_object($config)){
2751     return("");
2752   }
2754   /* Get attribute that we should use as serial number */
2755   if(isset($config->current['UNIQ_IDENTIFIER'])){
2756     $attr = $config->current['UNIQ_IDENTIFIER'];
2757   }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
2758     $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
2759   }
2760   if(!empty($attr)){
2761     $ldap = $config->get_ldap_link();
2762     $ldap->cat($dn,array($attr));
2763     $csn = $ldap->fetch();
2764     if(isset($csn[$attr][0])){
2765       return($csn[$attr][0]);
2766     }
2767   }
2768   return("");
2772 function display_error_page()
2774   $smarty= get_smarty();
2775   $smarty->display(get_template_path('headers.tpl'));
2776   echo "<body>".msg_dialog::get_dialogs()."</body></html>";
2777   exit();
2780 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2781 ?>