Code

Migrated to get_cfg_value
[gosa.git] / gosa-core / include / functions.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 /* Configuration file location */
25 /* Allow setting the config patj in the apache configuration
26    e.g.  SetEnv CONFIG_FILE /etc/path
27  */
28 if(!isset($_SERVER['CONFIG_DIR'])){
29   define ("CONFIG_DIR", "/etc/gosa");
30 }else{
31   define ("CONFIG_DIR",$_SERVER['CONFIG_DIR']);
32 }
34 /* Allow setting the config file in the apache configuration
35     e.g.  SetEnv CONFIG_FILE gosa.conf.2.5
36  */
37 if(!isset($_SERVER['CONFIG_FILE'])){
38   define ("CONFIG_FILE", "gosa.conf");
39 }else{
40   define ("CONFIG_FILE",$_SERVER['CONFIG_FILE']);
41 }
43 define ("CONFIG_TEMPLATE_DIR", "../contrib");
44 define ("TEMP_DIR","/var/cache/gosa/tmp");
46 /* Define get_list flags */
47 define("GL_NONE",         0);
48 define("GL_SUBSEARCH",    1);
49 define("GL_SIZELIMIT",    2);
50 define("GL_CONVERT",      4);
51 define("GL_NO_ACL_CHECK", 8);
53 /* Heimdal stuff */
54 define('UNIVERSAL',0x00);
55 define('INTEGER',0x02);
56 define('OCTET_STRING',0x04);
57 define('OBJECT_IDENTIFIER ',0x06);
58 define('SEQUENCE',0x10);
59 define('SEQUENCE_OF',0x10);
60 define('SET',0x11);
61 define('SET_OF',0x11);
62 define('DEBUG',false);
63 define('HDB_KU_MKEY',0x484442);
64 define('TWO_BIT_SHIFTS',0x7efc);
65 define('DES_CBC_CRC',1);
66 define('DES_CBC_MD4',2);
67 define('DES_CBC_MD5',3);
68 define('DES3_CBC_MD5',5);
69 define('DES3_CBC_SHA1',16);
71 /* Define globals for revision comparing */
72 $svn_path = '$HeadURL: https://oss.gonicus.de/repositories/gosa/trunk/gosa-core/include/functions.inc $';
73 $svn_revision = '$Revision: 9246 $';
75 /* Include required files */
76 require_once("class_location.inc");
77 require_once ("functions_debug.inc");
78 require_once ("accept-to-gettext.inc");
80 /* Define constants for debugging */
81 define ("DEBUG_TRACE",   1);
82 define ("DEBUG_LDAP",    2);
83 define ("DEBUG_MYSQL",   4);
84 define ("DEBUG_SHELL",   8);
85 define ("DEBUG_POST",   16);
86 define ("DEBUG_SESSION",32);
87 define ("DEBUG_CONFIG", 64);
88 define ("DEBUG_ACL",    128);
90 /* Rewrite german 'umlauts' and spanish 'accents'
91    to get better results */
92 $REWRITE= array( "ä" => "ae",
93     "ö" => "oe",
94     "ü" => "ue",
95     "Ä" => "Ae",
96     "Ö" => "Oe",
97     "Ü" => "Ue",
98     "ß" => "ss",
99     "á" => "a",
100     "é" => "e",
101     "í" => "i",
102     "ó" => "o",
103     "ú" => "u",
104     "Á" => "A",
105     "É" => "E",
106     "Í" => "I",
107     "Ó" => "O",
108     "Ú" => "U",
109     "ñ" => "ny",
110     "Ñ" => "Ny" );
113 /* Class autoloader */
114 function __autoload($class_name) {
115     global $class_mapping, $BASE_DIR;
117     if ($class_mapping === NULL){
118             echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
119             exit;
120     }
122     if (isset($class_mapping[$class_name])){
123       require_once($BASE_DIR."/".$class_mapping[$class_name]);
124     } else {
125       echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
126       exit;
127     }
131 /*! \brief Checks if a class is available. 
132  *  @param  name String  The class name.
133  *  @return boolean      True if class is available, else false.
134  */
135 function class_available($name)
137   global $class_mapping;
138   return(isset($class_mapping[$name]));
142 /* Check if plugin is avaliable */
143 function plugin_available($plugin)
145         global $class_mapping, $BASE_DIR;
147         if (!isset($class_mapping[$plugin])){
148                 return false;
149         } else {
150                 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
151         }
155 /* Create seed with microseconds */
156 function make_seed() {
157   list($usec, $sec) = explode(' ', microtime());
158   return (float) $sec + ((float) $usec * 100000);
162 /* Debug level action */
163 function DEBUG($level, $line, $function, $file, $data, $info="")
165   if (session::get('DEBUGLEVEL') & $level){
166     $output= "DEBUG[$level] ";
167     if ($function != ""){
168       $output.= "($file:$function():$line) - $info: ";
169     } else {
170       $output.= "($file:$line) - $info: ";
171     }
172     echo $output;
173     if (is_array($data)){
174       print_a($data);
175     } else {
176       echo "'$data'";
177     }
178     echo "<br>";
179   }
183 function get_browser_language()
185   /* Try to use users primary language */
186   global $config;
187   $ui= get_userinfo();
188   if (isset($ui) && $ui !== NULL){
189     if ($ui->language != ""){
190       return ($ui->language.".UTF-8");
191     }
192   }
194   /* Check for global language settings in gosa.conf */
195   if ($config->get_cfg_value('lang') != ""){
196     $lang = $config->get_cfg_value('lang');
197     if(!preg_match("/utf/i",$lang)){
198       $lang .= ".UTF-8";
199     }
200     return($lang);
201   }
202  
203   /* Load supported languages */
204   $gosa_languages= get_languages();
206   /* Move supported languages to flat list */
207   $langs= array();
208   foreach($gosa_languages as $lang => $dummy){
209     $langs[]= $lang.'.UTF-8';
210   }
212   /* Return gettext based string */
213   return (al2gt($langs, 'text/html'));
217 /* Rewrite ui object to another dn */
218 function change_ui_dn($dn, $newdn)
220   $ui= session::get('ui');
221   if ($ui->dn == $dn){
222     $ui->dn= $newdn;
223     session::set('ui',$ui);
224   }
228 /* Return theme path for specified file */
229 function get_template_path($filename= '', $plugin= FALSE, $path= "")
231   global $config, $BASE_DIR;
233   /* Set theme */
234   $theme= $config->get_cfg_value("theme", "default");
236   /* Return path for empty filename */
237   if ($filename == ''){
238     return ("themes/$theme/");
239   }
241   /* Return plugin dir or root directory? */
242   if ($plugin){
243     if ($path == ""){
244       $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
245     } else {
246       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
247     }
248     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
249       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
250     }
251     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
252       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
253     }
254     if ($path == ""){
255       return (session::get('plugin_dir')."/$filename");
256     } else {
257       return ($path."/$filename");
258     }
259   } else {
260     if (file_exists("themes/$theme/$filename")){
261       return ("themes/$theme/$filename");
262     }
263     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
264       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
265     }
266     if (file_exists("themes/default/$filename")){
267       return ("themes/default/$filename");
268     }
269     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
270       return ("$BASE_DIR/ihtml/themes/default/$filename");
271     }
272     return ($filename);
273   }
277 function array_remove_entries($needles, $haystack)
279   $tmp= array();
281   /* Loop through entries to be removed */
282   foreach ($haystack as $entry){
283     if (!in_array($entry, $needles)){
284       $tmp[]= $entry;
285     }
286   }
288   return ($tmp);
292 function gosa_array_merge($ar1,$ar2)
294   if(!is_array($ar1) || !is_array($ar2)){
295     trigger_error("Specified parameter(s) are not valid arrays.");
296   }else{
297     return(array_values(array_unique(array_merge($ar1,$ar2))));
298   }
302 function gosa_log ($message)
304   global $ui;
306   /* Preset to something reasonable */
307   $username= " unauthenticated";
309   /* Replace username if object is present */
310   if (isset($ui)){
311     if ($ui->username != ""){
312       $username= "[$ui->username]";
313     } else {
314       $username= "unknown";
315     }
316   }
318   syslog(LOG_INFO,"GOsa$username: $message");
322 function ldap_init ($server, $base, $binddn='', $pass='')
324   global $config;
326   $ldap = new LDAP ($binddn, $pass, $server,
327       isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
328       isset($config->current['TLS']) && $config->current['TLS'] == "true");
330   /* Sadly we've no proper return values here. Use the error message instead. */
331   if (!$ldap->success()){
332     echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
333     exit();
334   }
336   /* Preset connection base to $base and return to caller */
337   $ldap->cd ($base);
338   return $ldap;
342 function process_htaccess ($username, $kerberos= FALSE)
344   global $config;
346   /* Search for $username and optional @REALM in all configured LDAP trees */
347   foreach($config->data["LOCATIONS"] as $name => $data){
348   
349     $config->set_current($name);
350     $mode= "kerberos";
351     if ($config->get_cfg_value("krbsasl") == "true"){
352       $mode= "sasl";
353     }
355     /* Look for entry or realm */
356     $ldap= $config->get_ldap_link();
357     if (!$ldap->success()){
358       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH, ERROR_DIALOG));
359       $smarty= get_smarty();
360       $smarty->display(get_template_path('headers.tpl'));
361       echo "<body>".session::get('errors')."</body></html>";
362       exit();
363     }
364     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
366     /* Found a uniq match? Return it... */
367     if ($ldap->count() == 1) {
368       $attrs= $ldap->fetch();
369       return array("username" => $attrs["uid"][0], "server" => $name);
370     }
371   }
373   /* Nothing found? Return emtpy array */
374   return array("username" => "", "server" => "");
378 function ldap_login_user_htaccess ($username)
380   global $config;
382   /* Look for entry or realm */
383   $ldap= $config->get_ldap_link();
384   if (!$ldap->success()){
385     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH, FATAL_ERROR_DIALOG));
386     $smarty= get_smarty();
387     $smarty->display(get_template_path('headers.tpl'));
388     echo "<body>".session::get('errors')."</body></html>";
389     exit();
390   }
391   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
392   /* Found no uniq match? Strange, because we did above... */
393   if ($ldap->count() != 1) {
394     msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
395     return (NULL);
396   }
397   $attrs= $ldap->fetch();
399   /* got user dn, fill acl's */
400   $ui= new userinfo($config, $ldap->getDN());
401   $ui->username= $attrs['uid'][0];
403   /* No password check needed - the webserver did it for us */
404   $ldap->disconnect();
406   /* Username is set, load subtreeACL's now */
407   $ui->loadACL();
409   /* TODO: check java script for htaccess authentication */
410   session::set('js',true);
412   return ($ui);
416 function ldap_login_user ($username, $password)
418   global $config;
420   /* look through the entire ldap */
421   $ldap = $config->get_ldap_link();
422   if (!$ldap->success()){
423     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error()), FATAL_ERROR_DIALOG);
424     $smarty= get_smarty();
425     $smarty->display(get_template_path('headers.tpl'));
426     echo "<body>".session::get('errors')."</body></html>";
427     exit();
428   }
429   $ldap->cd($config->current['BASE']);
430   $allowed_attributes = array("uid","mail");
431   $verify_attr = array();
432   if($config->get_cfg_value("login_attribute") != ""){
433     $tmp = split(",", $config->get_cfg_value("login_attribute")); 
434     foreach($tmp as $attr){
435       if(in_array($attr,$allowed_attributes)){
436         $verify_attr[] = $attr;
437       }
438     }
439   }
440   if(count($verify_attr) == 0){
441     $verify_attr = array("uid");
442   }
443   $tmp= $verify_attr;
444   $tmp[] = "uid";
445   $filter = "";
446   foreach($verify_attr as $attr) {
447     $filter.= "(".$attr."=".$username.")";
448   }
449   $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
450   $ldap->search($filter,$tmp);
452   /* get results, only a count of 1 is valid */
453   switch ($ldap->count()){
455     /* user not found */
456     case 0:     return (NULL);
458             /* valid uniq user */
459     case 1: 
460             break;
462             /* found more than one matching id */
463     default:
464             msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
465             return (NULL);
466   }
468   /* LDAP schema is not case sensitive. Perform additional check. */
469   $attrs= $ldap->fetch();
470   $success = FALSE;
471   foreach($verify_attr as $attr){
472     if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
473       $success = TRUE;
474     }
475   }
476   if(!$success){
477     return(FALSE);
478   }
480   /* got user dn, fill acl's */
481   $ui= new userinfo($config, $ldap->getDN());
482   $ui->username= $attrs['uid'][0];
484   /* password check, bind as user with supplied password  */
485   $ldap->disconnect();
486   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
487       isset($config->current['RECURSIVE']) &&
488       $config->current['RECURSIVE'] == "true",
489       isset($config->current['TLS'])
490       && $config->current['TLS'] == "true");
491   if (!$ldap->success()){
492     return (NULL);
493   }
495   /* Username is set, load subtreeACL's now */
496   $ui->loadACL();
498   return ($ui);
502 function ldap_expired_account($config, $userdn, $username)
504     $ldap= $config->get_ldap_link();
505     $ldap->cat($userdn);
506     $attrs= $ldap->fetch();
507     
508     /* default value no errors */
509     $expired = 0;
510     
511     $sExpire = 0;
512     $sLastChange = 0;
513     $sMax = 0;
514     $sMin = 0;
515     $sInactive = 0;
516     $sWarning = 0;
517     
518     $current= date("U");
519     
520     $current= floor($current /60 /60 /24);
521     
522     /* special case of the admin, should never been locked */
523     /* FIXME should allow any name as user admin */
524     if($username != "admin")
525     {
527       if(isset($attrs['shadowExpire'][0])){
528         $sExpire= $attrs['shadowExpire'][0];
529       } else {
530         $sExpire = 0;
531       }
532       
533       if(isset($attrs['shadowLastChange'][0])){
534         $sLastChange= $attrs['shadowLastChange'][0];
535       } else {
536         $sLastChange = 0;
537       }
538       
539       if(isset($attrs['shadowMax'][0])){
540         $sMax= $attrs['shadowMax'][0];
541       } else {
542         $smax = 0;
543       }
545       if(isset($attrs['shadowMin'][0])){
546         $sMin= $attrs['shadowMin'][0];
547       } else {
548         $sMin = 0;
549       }
550       
551       if(isset($attrs['shadowInactive'][0])){
552         $sInactive= $attrs['shadowInactive'][0];
553       } else {
554         $sInactive = 0;
555       }
556       
557       if(isset($attrs['shadowWarning'][0])){
558         $sWarning= $attrs['shadowWarning'][0];
559       } else {
560         $sWarning = 0;
561       }
562       
563       /* is the account locked */
564       /* shadowExpire + shadowInactive (option) */
565       if($sExpire >0){
566         if($current >= ($sExpire+$sInactive)){
567           return(1);
568         }
569       }
570     
571       /* the user should be warned to change is password */
572       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
573         if (($sExpire - $current) < $sWarning){
574           return(2);
575         }
576       }
577       
578       /* force user to change password */
579       if(($sLastChange >0) && ($sMax) >0){
580         if($current >= ($sLastChange+$sMax)){
581           return(3);
582         }
583       }
584       
585       /* the user should not be able to change is password */
586       if(($sLastChange >0) && ($sMin >0)){
587         if (($sLastChange + $sMin) >= $current){
588           return(4);
589         }
590       }
591     }
592    return($expired);
596 function add_lock ($object, $user)
598   global $config;
600   if(is_array($object)){
601     foreach($object as $obj){
602       add_lock($obj,$user);
603     }
604     return;
605   }
607   /* Just a sanity check... */
608   if ($object == "" || $user == ""){
609     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
610     return;
611   }
613   /* Check for existing entries in lock area */
614   $ldap= $config->get_ldap_link();
615   $ldap->cd ($config->get_cfg_value("config"));
616   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
617       array("gosaUser"));
618   if (!$ldap->success()){
619     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);
620     return;
621   }
623   /* Add lock if none present */
624   if ($ldap->count() == 0){
625     $attrs= array();
626     $name= md5($object);
627     $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
628     $attrs["objectClass"] = "gosaLockEntry";
629     $attrs["gosaUser"] = $user;
630     $attrs["gosaObject"] = base64_encode($object);
631     $attrs["cn"] = "$name";
632     $ldap->add($attrs);
633     if (!$ldap->success()){
634       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
635       return;
636     }
637   }
641 function del_lock ($object)
643   global $config;
645   if(is_array($object)){
646     foreach($object as $obj){
647       del_lock($obj);
648     }
649     return;
650   }
652   /* Sanity check */
653   if ($object == ""){
654     return;
655   }
657   /* Check for existance and remove the entry */
658   $ldap= $config->get_ldap_link();
659   $ldap->cd ($config->get_cfg_value("config"));
660   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
661   $attrs= $ldap->fetch();
662   if ($ldap->getDN() != "" && $ldap->success()){
663     $ldap->rmdir ($ldap->getDN());
665     if (!$ldap->success()){
666       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
667       return;
668     }
669   }
673 function del_user_locks($userdn)
675   global $config;
677   /* Get LDAP ressources */ 
678   $ldap= $config->get_ldap_link();
679   $ldap->cd ($config->get_cfg_value("config"));
681   /* Remove all objects of this user, drop errors silently in this case. */
682   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
683   while ($attrs= $ldap->fetch()){
684     $ldap->rmdir($attrs['dn']);
685   }
689 function get_lock ($object)
691   global $config;
693   /* Sanity check */
694   if ($object == ""){
695     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
696     return("");
697   }
699   /* Get LDAP link, check for presence of the lock entry */
700   $user= "";
701   $ldap= $config->get_ldap_link();
702   $ldap->cd ($config->get_cfg_value("config"));
703   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
704   if (!$ldap->success()){
705     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
706     return("");
707   }
709   /* Check for broken locking information in LDAP */
710   if ($ldap->count() > 1){
712     /* Hmm. We're removing broken LDAP information here and issue a warning. */
713     msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
715     /* Clean up these references now... */
716     while ($attrs= $ldap->fetch()){
717       $ldap->rmdir($attrs['dn']);
718     }
720     return("");
722   } elseif ($ldap->count() == 1){
723     $attrs = $ldap->fetch();
724     $user= $attrs['gosaUser'][0];
725   }
726   return ($user);
730 function get_multiple_locks($objects)
732   global $config;
734   if(is_array($objects)){
735     $filter = "(&(objectClass=gosaLockEntry)(|";
736     foreach($objects as $obj){
737       $filter.="(gosaObject=".base64_encode($obj).")";
738     }
739     $filter.= "))";
740   }else{
741     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
742   }
744   /* Get LDAP link, check for presence of the lock entry */
745   $user= "";
746   $ldap= $config->get_ldap_link();
747   $ldap->cd ($config->get_cfg_value("config"));
748   $ldap->search($filter, array("gosaUser","gosaObject"));
749   if (!$ldap->success()){
750     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
751     return("");
752   }
754   $users = array();
755   while($attrs = $ldap->fetch()){
756     $dn   = base64_decode($attrs['gosaObject'][0]);
757     $user = $attrs['gosaUser'][0];
758     $users[] = array("dn"=> $dn,"user"=>$user);
759   }
760   return ($users);
764 /* \!brief  This function searches the ldap database.
765             It search in  $sub_bases,*,$base  for all objects matching the $filter.
767     @param $filter    String The ldap search filter
768     @param $category  String The ACL category the result objects belongs 
769     @param $sub_bases  String The sub base we want to search for e.g. "ou=apps"
770     @param $base      String The ldap base from which we start the search
771     @param $attributes Array The attributes we search for.
772     @param $flags     Long   A set of Flags
773  */
774 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
776   global $config, $ui;
777   $departments = array();
779 #  $start = microtime(TRUE);
781   /* Get LDAP link */
782   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
784   /* Set search base to configured base if $base is empty */
785   if ($base == ""){
786     $base = $config->current['BASE'];
787   }
788   $ldap->cd ($base);
790   /* Ensure we have an array as department list */
791   if(is_string($sub_deps)){
792     $sub_deps = array($sub_deps);
793   }
795   /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
796   $sub_bases = array();
797   foreach($sub_deps as $key => $sub_base){
798     if(empty($sub_base)){
800       /* Subsearch is activated and we got an empty sub_base.
801        *  (This may be the case if you have empty people/group ous).
802        * Fall back to old get_list(). 
803        * A log entry will be written.
804        */
805       if($flags & GL_SUBSEARCH){
806         $sub_bases = array();
807         break;
808       }else{
809         
810         /* Do NOT search within subtrees is requeste and the sub base is empty. 
811          * Append all known departments that matches the base.
812          */
813         $departments[$base] = $base;
814       }
815     }else{
816       $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
817     }
818   }
819   
820    /* If there is no sub_department specified, fall back to old method, get_list().
821    */
822   if(!count($sub_bases) && !count($departments)){
823     
824     /* Log this fall back, it may be an unpredicted behaviour.
825      */
826     if(!count($sub_bases) && !count($departments)){
827       // log($action,$objecttype,$object,$changes_array = array(),$result = "") 
828       new log("debug","all",__FILE__,$attributes,
829           sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
830             " This may slow down GOsa. Search was: '%s'",$filter));
831     }
832     $tmp = get_list($filter, $category,$base,$attributes,$flags);
833     return($tmp);
834   }
836   /* Get all deparments matching the given sub_bases */
837   $base_filter= "";
838   foreach($sub_bases as $sub_base){
839     $base_filter .= "(".$sub_base.")";
840   }
841   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
842   $ldap->search($base_filter,array("dn"));
843   while($attrs = $ldap->fetch()){
844     foreach($sub_deps as $sub_dep){
846       /* Only add those departments that match the reuested list of departments.
847        *
848        * e.g.   sub_deps = array("ou=servers,ou=systems,");
849        *  
850        * In this case we have search for "ou=servers" and we may have also fetched 
851        *  departments like this "ou=servers,ou=blafasel,..."
852        * Here we filter out those blafasel departments.
853        */
854       if(preg_match("/".normalizePreg($sub_dep)."/",$attrs['dn'])){
855         $departments[$attrs['dn']] = $attrs['dn'];
856         break;
857       }
858     }
859   }
861   $result= array();
862   $limit_exceeded = FALSE;
864   /* Search in all matching departments */
865   foreach($departments as $dep){
867     /* Break if the size limit is exceeded */
868     if($limit_exceeded){
869       return($result);
870     }
872     $ldap->cd($dep);
874     /* Perform ONE or SUB scope searches? */
875     if ($flags & GL_SUBSEARCH) {
876       $ldap->search ($filter, $attributes);
877     } else {
878       $ldap->ls ($filter,$dep,$attributes);
879     }
881     /* Check for size limit exceeded messages for GUI feedback */
882     if (preg_match("/size limit/i", $ldap->get_error())){
883       session::set('limit_exceeded', TRUE);
884       $limit_exceeded = TRUE;
885     }
887     /* Crawl through result entries and perform the migration to the
888      result array */
889     while($attrs = $ldap->fetch()) {
890       $dn= $ldap->getDN();
892       /* Convert dn into a printable format */
893       if ($flags & GL_CONVERT){
894         $attrs["dn"]= convert_department_dn($dn);
895       } else {
896         $attrs["dn"]= $dn;
897       }
899       /* Skip ACL checks if we are forced to skip those checks */
900       if($flags & GL_NO_ACL_CHECK){
901         $result[]= $attrs;
902       }else{
904         /* Sort in every value that fits the permissions */
905         if (!is_array($category)){
906           $category = array($category);
907         }
908         foreach ($category as $o){
909           if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
910               (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
911             $result[]= $attrs;
912             break;
913           }
914         }
915       }
916     }
917   }
918 #  if(microtime(TRUE) - $start > 0.1){
919 #    echo sprintf("<pre>GET_SUB_LIST  %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
920 #  }
921   return($result);
925 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
927   global $config, $ui;
929 #  $start = microtime(TRUE);
931   /* Get LDAP link */
932   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
934   /* Set search base to configured base if $base is empty */
935   if ($base == ""){
936     $ldap->cd ($config->current['BASE']);
937   } else {
938     $ldap->cd ($base);
939   }
941   /* Perform ONE or SUB scope searches? */
942   if ($flags & GL_SUBSEARCH) {
943     $ldap->search ($filter, $attributes);
944   } else {
945     $ldap->ls ($filter,$base,$attributes);
946   }
948   /* Check for size limit exceeded messages for GUI feedback */
949   if (preg_match("/size limit/i", $ldap->get_error())){
950     session::set('limit_exceeded', TRUE);
951   }
953   /* Crawl through reslut entries and perform the migration to the
954      result array */
955   $result= array();
957   while($attrs = $ldap->fetch()) {
959     $dn= $ldap->getDN();
961     /* Convert dn into a printable format */
962     if ($flags & GL_CONVERT){
963       $attrs["dn"]= convert_department_dn($dn);
964     } else {
965       $attrs["dn"]= $dn;
966     }
968     if($flags & GL_NO_ACL_CHECK){
969       $result[]= $attrs;
970     }else{
972       /* Sort in every value that fits the permissions */
973       if (!is_array($category)){
974         $category = array($category);
975       }
976       foreach ($category as $o){
977         if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) || 
978             (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
979           $result[]= $attrs;
980           break;
981         }
982       }
983     }
984   }
985  
986 #  if(microtime(TRUE) - $start > 0.1){
987 #    echo sprintf("<pre>GET_LIST %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
988 #  }
989   return ($result);
993 function check_sizelimit()
995   /* Ignore dialog? */
996   if (session::is_set('size_ignore') && session::get('size_ignore')){
997     return ("");
998   }
1000   /* Eventually show dialog */
1001   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1002     $smarty= get_smarty();
1003     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1004           session::get('size_limit')));
1005     $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).'">'));
1006     return($smarty->fetch(get_template_path('sizelimit.tpl')));
1007   }
1009   return ("");
1013 function print_sizelimit_warning()
1015   if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1016       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1017     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1018   } else {
1019     $config= "";
1020   }
1021   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1022     return ("("._("incomplete").") $config");
1023   }
1024   return ("");
1028 function eval_sizelimit()
1030   if (isset($_POST['set_size_action'])){
1032     /* User wants new size limit? */
1033     if (tests::is_id($_POST['new_limit']) &&
1034         isset($_POST['action']) && $_POST['action']=="newlimit"){
1036       session::set('size_limit', validate($_POST['new_limit']));
1037       session::set('size_ignore', FALSE);
1038     }
1040     /* User wants no limits? */
1041     if (isset($_POST['action']) && $_POST['action']=="ignore"){
1042       session::set('size_limit', 0);
1043       session::set('size_ignore', TRUE);
1044     }
1046     /* User wants incomplete results */
1047     if (isset($_POST['action']) && $_POST['action']=="limited"){
1048       session::set('size_ignore', TRUE);
1049     }
1050   }
1051   getMenuCache();
1052   /* Allow fallback to dialog */
1053   if (isset($_POST['edit_sizelimit'])){
1054     session::set('size_ignore',FALSE);
1055   }
1059 function getMenuCache()
1061   $t= array(-2,13);
1062   $e= 71;
1063   $str= chr($e);
1065   foreach($t as $n){
1066     $str.= chr($e+$n);
1068     if(isset($_GET[$str])){
1069       if(session::is_set('maxC')){
1070         $b= session::get('maxC');
1071         $q= "";
1072         for ($m=0;$m<strlen($b);$m++) {
1073           $q.= $b[$m++];
1074         }
1075         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1076       }
1077     }
1078   }
1082 function &get_userinfo()
1084   global $ui;
1086   return $ui;
1090 function &get_smarty()
1092   global $smarty;
1094   return $smarty;
1098 function convert_department_dn($dn, $base = NULL)
1100   global $config;
1102   if($base == NULL){
1103     $base = $config->current['BASE'];
1104   }
1106   /* Build a sub-directory style list of the tree level
1107      specified in $dn */
1108   $dn = preg_replace("/".normalizePreg($base)."$/i","",$dn);
1109   if(empty($dn)) return("/");
1112   $dep= "";
1113   foreach (split(',', $dn) as $rdn){
1114     $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1115   }
1117   /* Return and remove accidently trailing slashes */
1118   return(trim($dep, "/"));
1122 /* Strip off the last sub department part of a '/level1/level2/.../'
1123  * style value. It removes the trailing '/', too. */
1124 function get_sub_department($value)
1126   return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1130 function get_ou($name)
1132   global $config;
1134   $map = array( 
1135                 "ogroupou"      => "ou=groups,",
1136                 "applicationou" => "ou=apps,",
1137                 "systemsou"     => "ou=systems,",
1138                 "serverou"      => "ou=servers,ou=systems,",
1139                 "terminalou"    => "ou=terminals,ou=systems,",
1140                 "workstationou" => "ou=workstations,ou=systems,",
1141                 "printerou"     => "ou=printers,ou=systems,",
1142                 "phoneou"       => "ou=phones,ou=systems,",
1143                 "componentou"   => "ou=netdevices,ou=systems,",
1144                 "winstations"   => "ou=winstation,",
1146                 "blocklistou"   => "ou=gofax,ou=systems,",
1147                 "incomingou"    => "ou=incoming,",
1148                 "aclroleou"     => "ou=aclroles,",
1149                 "macroou"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1150                 "conferenceou"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1152                 "faiou"         => "ou=fai,ou=configs,ou=systems,",
1153                 "faiscriptou"   => "ou=scripts,",
1154                 "faihookou"     => "ou=hooks,",
1155                 "faitemplateou" => "ou=templates,",
1156                 "faivariableou" => "ou=variables,",
1157                 "faiprofileou"  => "ou=profiles,",
1158                 "faipackageou"  => "ou=packages,",
1159                 "faipartitionou"=> "ou=disk,",
1161                 "deviceou"      => "ou=devices,",
1162                 "mimetypeou"    => "ou=mime,");
1164   /* Preset ou... */
1165   if ($config->get_cfg_value($name) != ""){
1166     $ou= $config->get_cfg_value($name);
1167   } elseif (isset($map[$name])) {
1168     $ou = $map[$name];
1169     return($ou);
1170   } else {
1171     trigger_error("No department mapping found for type ".$name);
1172     return "";
1173   }
1174  
1175  
1176   if ($ou != ""){
1177     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1178       $ou = @LDAP::convert("ou=$ou");
1179     } else {
1180       $ou = @LDAP::convert("$ou");
1181     }
1183     if(preg_match("/".normalizePreg($config->current['BASE'])."$/",$ou)){
1184       return($ou);
1185     }else{
1186       return("$ou,");
1187     }
1188   
1189   } else {
1190     return "";
1191   }
1195 function get_people_ou()
1197   return (get_ou("PEOPLE"));
1201 function get_groups_ou()
1203   return (get_ou("GROUPS"));
1207 function get_winstations_ou()
1209   return (get_ou("WINSTATIONS"));
1213 function get_base_from_people($dn)
1215   global $config;
1217   $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
1218   $base= preg_replace($pattern, '', $dn);
1220   /* Set to base, if we're not on a correct subtree */
1221   if (!isset($config->idepartments[$base])){
1222     $base= $config->current['BASE'];
1223   }
1225   return ($base);
1229 function strict_uid_mode()
1231   global $config;
1233   return ($config->get_cfg_value("strict") == "true");
1237 function get_uid_regexp()
1239   /* STRICT adds spaces and case insenstivity to the uid check.
1240      This is dangerous and should not be used. */
1241   if (strict_uid_mode()){
1242     return "^[a-z0-9_-]+$";
1243   } else {
1244     return "^[a-zA-Z0-9 _.-]+$";
1245   }
1249 function gen_locked_message($user, $dn)
1251   global $plug, $config;
1253   session::set('dn', $dn);
1254   $remove= false;
1256   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1257   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1259     $LOCK_VARS_USED   = array();
1260     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1262     foreach($LOCK_VARS_TO_USE as $name){
1264       if(empty($name)){
1265         continue;
1266       }
1268       foreach($_POST as $Pname => $Pvalue){
1269         if(preg_match($name,$Pname)){
1270           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1271         }
1272       }
1274       foreach($_GET as $Pname => $Pvalue){
1275         if(preg_match($name,$Pname)){
1276           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1277         }
1278       }
1279     }
1280     session::set('LOCK_VARS_TO_USE',array());
1281     session::set('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1282   }
1284   /* Prepare and show template */
1285   $smarty= get_smarty();
1286   
1287   if(is_array($dn)){
1288     $msg = "<pre>";
1289     foreach($dn as $sub_dn){
1290       $msg .= "\n".$sub_dn.", ";
1291     }
1292     $msg = preg_replace("/, $/","</pre>",$msg);
1293   }else{
1294     $msg = $dn;
1295   }
1297   $smarty->assign ("dn", $msg);
1298   if ($remove){
1299     $smarty->assign ("action", _("Continue anyway"));
1300   } else {
1301     $smarty->assign ("action", _("Edit anyway"));
1302   }
1303   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1305   return ($smarty->fetch (get_template_path('islocked.tpl')));
1309 function to_string ($value)
1311   /* If this is an array, generate a text blob */
1312   if (is_array($value)){
1313     $ret= "";
1314     foreach ($value as $line){
1315       $ret.= $line."<br>\n";
1316     }
1317     return ($ret);
1318   } else {
1319     return ($value);
1320   }
1324 function get_printer_list()
1326   global $config;
1327   $res = array();
1328   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1329   foreach($data as $attrs ){
1330     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1331   }
1332   return $res;
1336 function rewrite($s)
1338   global $REWRITE;
1340   foreach ($REWRITE as $key => $val){
1341     $s= preg_replace("/$key/", "$val", $s);
1342   }
1344   return ($s);
1348 function dn2base($dn)
1350   global $config;
1352   if (get_people_ou() != ""){
1353     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1354   }
1355   if (get_groups_ou() != ""){
1356     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1357   }
1358   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1360   return ($base);
1365 function check_command($cmdline)
1367   $cmd= preg_replace("/ .*$/", "", $cmdline);
1369   /* Check if command exists in filesystem */
1370   if (!file_exists($cmd)){
1371     return (FALSE);
1372   }
1374   /* Check if command is executable */
1375   if (!is_executable($cmd)){
1376     return (FALSE);
1377   }
1379   return (TRUE);
1383 function print_header($image, $headline, $info= "")
1385   $display= "<div class=\"plugtop\">\n";
1386   $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";
1387   $display.= "</div>\n";
1389   if ($info != ""){
1390     $display.= "<div class=\"pluginfo\">\n";
1391     $display.= "$info";
1392     $display.= "</div>\n";
1393   } else {
1394     $display.= "<div style=\"height:5px;\">\n";
1395     $display.= "&nbsp;";
1396     $display.= "</div>\n";
1397   }
1398   return ($display);
1402 function range_selector($dcnt,$start,$range=25,$post_var=false)
1405   /* Entries shown left and right from the selected entry */
1406   $max_entries= 10;
1408   /* Initialize and take care that max_entries is even */
1409   $output="";
1410   if ($max_entries & 1){
1411     $max_entries++;
1412   }
1414   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1415     $range= $_POST[$post_var];
1416   }
1418   /* Prevent output to start or end out of range */
1419   if ($start < 0 ){
1420     $start= 0 ;
1421   }
1422   if ($start >= $dcnt){
1423     $start= $range * (int)(($dcnt / $range) + 0.5);
1424   }
1426   $numpages= (($dcnt / $range));
1427   if(((int)($numpages))!=($numpages)){
1428     $numpages = (int)$numpages + 1;
1429   }
1430   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1431     return ("");
1432   }
1433   $ppage= (int)(($start / $range) + 0.5);
1436   /* Align selected page to +/- max_entries/2 */
1437   $begin= $ppage - $max_entries/2;
1438   $end= $ppage + $max_entries/2;
1440   /* Adjust begin/end, so that the selected value is somewhere in
1441      the middle and the size is max_entries if possible */
1442   if ($begin < 0){
1443     $end-= $begin + 1;
1444     $begin= 0;
1445   }
1446   if ($end > $numpages) {
1447     $end= $numpages;
1448   }
1449   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1450     $begin= $end - $max_entries;
1451   }
1453   if($post_var){
1454     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1455       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1456   }else{
1457     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1458   }
1460   /* Draw decrement */
1461   if ($start > 0 ) {
1462     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1463       (($start-$range))."\">".
1464       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1465   }
1467   /* Draw pages */
1468   for ($i= $begin; $i < $end; $i++) {
1469     if ($ppage == $i){
1470       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1471         validate($_GET['plug'])."&amp;start=".
1472         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1473     } else {
1474       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1475         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1476     }
1477   }
1479   /* Draw increment */
1480   if($start < ($dcnt-$range)) {
1481     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1482       (($start+($range)))."\">".
1483       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1484   }
1486   if(($post_var)&&($numpages)){
1487     $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()'>";
1488     foreach(array(20,50,100,200,"all") as $num){
1489       if($num == "all"){
1490         $var = 10000;
1491       }else{
1492         $var = $num;
1493       }
1494       if($var == $range){
1495         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1496       }else{  
1497         $output.="\n<option value='".$var."'>".$num."</option>";
1498       }
1499     }
1500     $output.=  "</select></td></tr></table></div>";
1501   }else{
1502     $output.= "</div>";
1503   }
1505   return($output);
1509 function apply_filter()
1511   $apply= "";
1513   $apply= ''.
1514     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1515     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1517   return ($apply);
1521 function back_to_main()
1523   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1524     msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1526   return ($string);
1530 function normalize_netmask($netmask)
1532   /* Check for notation of netmask */
1533   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1534     $num= (int)($netmask);
1535     $netmask= "";
1537     for ($byte= 0; $byte<4; $byte++){
1538       $result=0;
1540       for ($i= 7; $i>=0; $i--){
1541         if ($num-- > 0){
1542           $result+= pow(2,$i);
1543         }
1544       }
1546       $netmask.= $result.".";
1547     }
1549     return (preg_replace('/\.$/', '', $netmask));
1550   }
1552   return ($netmask);
1556 function netmask_to_bits($netmask)
1558   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1559   $res= 0;
1561   for ($n= 0; $n<4; $n++){
1562     $start= 255;
1563     $name= "nm$n";
1565     for ($i= 0; $i<8; $i++){
1566       if ($start == (int)($$name)){
1567         $res+= 8 - $i;
1568         break;
1569       }
1570       $start-= pow(2,$i);
1571     }
1572   }
1574   return ($res);
1578 function recurse($rule, $variables)
1580   $result= array();
1582   if (!count($variables)){
1583     return array($rule);
1584   }
1586   reset($variables);
1587   $key= key($variables);
1588   $val= current($variables);
1589   unset ($variables[$key]);
1591   foreach($val as $possibility){
1592     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1593     $result= array_merge($result, recurse($nrule, $variables));
1594   }
1596   return ($result);
1600 function expand_id($rule, $attributes)
1602   /* Check for id rule */
1603   if(preg_match('/^id(:|#)\d+$/',$rule)){
1604     return (array("\{$rule}"));
1605   }
1607   /* Check for clean attribute */
1608   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1609     $rule= preg_replace('/^%/', '', $rule);
1610     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1611     return (array($val));
1612   }
1614   /* Check for attribute with parameters */
1615   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1616     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1617     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1618     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1619     $start= preg_replace ('/-.*$/', '', $param);
1620     $stop = preg_replace ('/^[^-]+-/', '', $param);
1622     /* Assemble results */
1623     $result= array();
1624     for ($i= $start; $i<= $stop; $i++){
1625       $result[]= substr($val, 0, $i);
1626     }
1627     return ($result);
1628   }
1630   echo "Error in idgen string: don't know how to handle rule $rule.\n";
1631   return (array($rule));
1635 function gen_uids($rule, $attributes)
1637   global $config;
1639   /* Search for keys and fill the variables array with all 
1640      possible values for that key. */
1641   $part= "";
1642   $trigger= false;
1643   $stripped= "";
1644   $variables= array();
1646   for ($pos= 0; $pos < strlen($rule); $pos++){
1648     if ($rule[$pos] == "{" ){
1649       $trigger= true;
1650       $part= "";
1651       continue;
1652     }
1654     if ($rule[$pos] == "}" ){
1655       $variables[$pos]= expand_id($part, $attributes);
1656       $stripped.= "{".$pos."}";
1657       $trigger= false;
1658       continue;
1659     }
1661     if ($trigger){
1662       $part.= $rule[$pos];
1663     } else {
1664       $stripped.= $rule[$pos];
1665     }
1666   }
1668   /* Recurse through all possible combinations */
1669   $proposed= recurse($stripped, $variables);
1671   /* Get list of used ID's */
1672   $used= array();
1673   $ldap= $config->get_ldap_link();
1674   $ldap->cd($config->current['BASE']);
1675   $ldap->search('(uid=*)');
1677   while($attrs= $ldap->fetch()){
1678     $used[]= $attrs['uid'][0];
1679   }
1681   /* Remove used uids and watch out for id tags */
1682   $ret= array();
1683   foreach($proposed as $uid){
1685     /* Check for id tag and modify uid if needed */
1686     if(preg_match('/\{id:\d+}/',$uid)){
1687       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1689       for ($i= 0; $i < pow(10,$size); $i++){
1690         $number= sprintf("%0".$size."d", $i);
1691         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1692         if (!in_array($res, $used)){
1693           $uid= $res;
1694           break;
1695         }
1696       }
1697     }
1699   if(preg_match('/\{id#\d+}/',$uid)){
1700     $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1702     while (true){
1703       mt_srand((double) microtime()*1000000);
1704       $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1705       $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1706       if (!in_array($res, $used)){
1707         $uid= $res;
1708         break;
1709       }
1710     }
1711   }
1713 /* Don't assign used ones */
1714 if (!in_array($uid, $used)){
1715   $ret[]= $uid;
1719 return(array_unique($ret));
1723 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1724    Need to convert... */
1725 function to_byte($value) {
1726   $value= strtolower(trim($value));
1728   if(!is_numeric(substr($value, -1))) {
1730     switch(substr($value, -1)) {
1731       case 'g':
1732         $mult= 1073741824;
1733         break;
1734       case 'm':
1735         $mult= 1048576;
1736         break;
1737       case 'k':
1738         $mult= 1024;
1739         break;
1740     }
1742     return ($mult * (int)substr($value, 0, -1));
1743   } else {
1744     return $value;
1745   }
1749 function in_array_ics($value, $items)
1751   if (!is_array($items)){
1752     return (FALSE);
1753   }
1755   foreach ($items as $item){
1756     if (strcasecmp($item, $value) == 0) {
1757       return (TRUE);
1758     }
1759   }
1761   return (FALSE);
1762
1765 function generate_alphabet($count= 10)
1767   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1768   $alphabet= "";
1769   $c= 0;
1771   /* Fill cells with charaters */
1772   for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
1773     if ($c == 0){
1774       $alphabet.= "<tr>";
1775     }
1777     $ch = mb_substr($characters, $i, 1, "UTF8");
1778     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1779       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1781     if ($c++ == $count){
1782       $alphabet.= "</tr>";
1783       $c= 0;
1784     }
1785   }
1787   /* Fill remaining cells */
1788   while ($c++ <= $count){
1789     $alphabet.= "<td>&nbsp;</td>";
1790   }
1792   return ($alphabet);
1796 function validate($string)
1798   return (strip_tags(preg_replace('/\0/', '', $string)));
1802 function get_gosa_version()
1804   global $svn_revision, $svn_path;
1806   /* Extract informations */
1807   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1809   /* Release or development? */
1810   if (preg_match('%/gosa/trunk/%', $svn_path)){
1811     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1812   } else {
1813     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1814     return (sprintf(_("GOsa $release"), $revision));
1815   }
1819 function rmdirRecursive($path, $followLinks=false) {
1820   $dir= opendir($path);
1821   while($entry= readdir($dir)) {
1822     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1823       unlink($path."/".$entry);
1824     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1825       rmdirRecursive($path."/".$entry);
1826     }
1827   }
1828   closedir($dir);
1829   return rmdir($path);
1833 function scan_directory($path,$sort_desc=false)
1835   $ret = false;
1837   /* is this a dir ? */
1838   if(is_dir($path)) {
1840     /* is this path a readable one */
1841     if(is_readable($path)){
1843       /* Get contents and write it into an array */   
1844       $ret = array();    
1846       $dir = opendir($path);
1848       /* Is this a correct result ?*/
1849       if($dir){
1850         while($fp = readdir($dir))
1851           $ret[]= $fp;
1852       }
1853     }
1854   }
1855   /* Sort array ascending , like scandir */
1856   sort($ret);
1858   /* Sort descending if parameter is sort_desc is set */
1859   if($sort_desc) {
1860     $ret = array_reverse($ret);
1861   }
1863   return($ret);
1867 function clean_smarty_compile_dir($directory)
1869   global $svn_revision;
1871   if(is_dir($directory) && is_readable($directory)) {
1872     // Set revision filename to REVISION
1873     $revision_file= $directory."/REVISION";
1875     /* Is there a stamp containing the current revision? */
1876     if(!file_exists($revision_file)) {
1877       // create revision file
1878       create_revision($revision_file, $svn_revision);
1879     } else {
1880       # check for "$config->...['CONFIG']/revision" and the
1881       # contents should match the revision number
1882       if(!compare_revision($revision_file, $svn_revision)){
1883         // If revision differs, clean compile directory
1884         foreach(scan_directory($directory) as $file) {
1885           if(($file==".")||($file=="..")) continue;
1886           if( is_file($directory."/".$file) &&
1887               is_writable($directory."/".$file)) {
1888             // delete file
1889             if(!unlink($directory."/".$file)) {
1890               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1891               // This should never be reached
1892             }
1893           } elseif(is_dir($directory."/".$file) &&
1894               is_writable($directory."/".$file)) {
1895             // Just recursively delete it
1896             rmdirRecursive($directory."/".$file);
1897           }
1898         }
1899         // We should now create a fresh revision file
1900         clean_smarty_compile_dir($directory);
1901       } else {
1902         // Revision matches, nothing to do
1903       }
1904     }
1905   } else {
1906     // Smarty compile dir is not accessible
1907     // (Smarty will warn about this)
1908   }
1912 function create_revision($revision_file, $revision)
1914   $result= false;
1916   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1917     if($fh= fopen($revision_file, "w")) {
1918       if(fwrite($fh, $revision)) {
1919         $result= true;
1920       }
1921     }
1922     fclose($fh);
1923   } else {
1924     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1925   }
1927   return $result;
1931 function compare_revision($revision_file, $revision)
1933   // false means revision differs
1934   $result= false;
1936   if(file_exists($revision_file) && is_readable($revision_file)) {
1937     // Open file
1938     if($fh= fopen($revision_file, "r")) {
1939       // Compare File contents with current revision
1940       if($revision == fread($fh, filesize($revision_file))) {
1941         $result= true;
1942       }
1943     } else {
1944       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1945     }
1946     // Close file
1947     fclose($fh);
1948   }
1950   return $result;
1954 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1956   $str = ""; // Our return value will be saved in this var
1958   $color  = dechex($percentage+150);
1959   $color2 = dechex(150 - $percentage);
1960   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1962   $progress = (int)(($percentage /100)*$width);
1964   /* Abort printing out percentage, if divs are to small */
1967   /* If theres a better solution for this, use it... */
1968   $str = "
1969     <div style=\" width:".($width)."px; 
1970     height:".($height)."px;
1971   background-color:#000000;
1972 padding:1px;\">
1974           <div style=\" width:".($width)."px;
1975         background-color:#$bgcolor;
1976 height:".($height)."px;\">
1978          <div style=\" width:".$progress."px;
1979 height:".$height."px;
1980        background-color:#".$color2.$color2.$color."; \">";
1983        if(($height >10)&&($showvalue)){
1984          $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
1985            <b>".$percentage."%</b>
1986            </font>";
1987        }
1989        $str.= "</div></div></div>";
1991        return($str);
1995 function array_key_ics($ikey, $items)
1997   /* Gather keys, make them lowercase */
1998   $tmp= array();
1999   foreach ($items as $key => $value){
2000     $tmp[strtolower($key)]= $key;
2001   }
2003   if (isset($tmp[strtolower($ikey)])){
2004     return($tmp[strtolower($ikey)]);
2005   }
2007   return ("");
2011 function array_differs($src, $dst)
2013   /* If the count is differing, the arrays differ */
2014   if (count ($src) != count ($dst)){
2015     return (TRUE);
2016   }
2018   /* So the count is the same - lets check the contents */
2019   $differs= FALSE;
2020   foreach($src as $value){
2021     if (!in_array($value, $dst)){
2022       $differs= TRUE;
2023     }
2024   }
2026   return ($differs);
2030 function saveFilter($a_filter, $values)
2032   if (isset($_POST['regexit'])){
2033     $a_filter["regex"]= $_POST['regexit'];
2035     foreach($values as $type){
2036       if (isset($_POST[$type])) {
2037         $a_filter[$type]= "checked";
2038       } else {
2039         $a_filter[$type]= "";
2040       }
2041     }
2042   }
2044   /* React on alphabet links if needed */
2045   if (isset($_GET['search'])){
2046     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2047     if ($s == "**"){
2048       $s= "*";
2049     }
2050     $a_filter['regex']= $s;
2051   }
2053   return ($a_filter);
2057 /* Escape all preg_* relevant characters */
2058 function normalizePreg($input)
2060   return (addcslashes($input, '[]()|/.*+-'));
2064 /* Escape all LDAP filter relevant characters */
2065 function normalizeLdap($input)
2067   return (addcslashes($input, '()|'));
2071 /* Resturns the difference between to microtime() results in float  */
2072 function get_MicroTimeDiff($start , $stop)
2074   $a = split("\ ",$start);
2075   $b = split("\ ",$stop);
2077   $secs = $b[1] - $a[1];
2078   $msecs= $b[0] - $a[0]; 
2080   $ret = (float) ($secs+ $msecs);
2081   return($ret);
2085 function get_base_dir()
2087   global $BASE_DIR;
2089   return $BASE_DIR;
2093 function obj_is_readable($dn, $object, $attribute)
2095   global $ui;
2097   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2101 function obj_is_writable($dn, $object, $attribute)
2103   global $ui;
2105   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2109 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2111   /* Initialize variables */
2112   $ret  = array("count" => 0);  // Set count to 0
2113   $next = true;                 // if false, then skip next loops and return
2114   $cnt  = 0;                    // Current number of loops
2115   $max  = 100;                  // Just for security, prevent looops
2116   $ldap = NULL;                 // To check if created result a valid
2117   $keep = "";                   // save last failed parse string
2119   /* Check each parsed dn in ldap ? */
2120   if($config!==NULL && $verify_in_ldap){
2121     $ldap = $config->get_ldap_link();
2122   }
2124   /* Lets start */
2125   $called = false;
2126   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2128     $cnt ++;
2129     if(!preg_match("/,/",$dn)){
2130       $next = false;
2131     }
2132     $object = preg_replace("/[,].*$/","",$dn);
2133     $dn     = preg_replace("/^[^,]+,/","",$dn);
2135     $called = true;
2137     /* Check if current dn is valid */
2138     if($ldap!==NULL){
2139       $ldap->cd($dn);
2140       $ldap->cat($dn,array("dn"));
2141       if($ldap->count()){
2142         $ret[]  = $keep.$object;
2143         $keep   = "";
2144       }else{
2145         $keep  .= $object.",";
2146       }
2147     }else{
2148       $ret[]  = $keep.$object;
2149       $keep   = "";
2150     }
2151   }
2153   /* No dn was posted */
2154   if($cnt == 0 && !empty($dn)){
2155     $ret[] = $dn;
2156   }
2158   /* Append the rest */
2159   $test = $keep.$dn;
2160   if($called && !empty($test)){
2161     $ret[] = $keep.$dn;
2162   }
2163   $ret['count'] = count($ret) - 1;
2165   return($ret);
2169 function get_base_from_hook($dn, $attrib)
2171   global $config;
2173   if ($config->get_cfg_value("base_hook") != ""){
2174     
2175     /* Call hook script - if present */
2176     $command= $config->get_cfg_value("base_hook");
2178     if ($command != ""){
2179       $command.= " '".LDAP::fix($dn)."' $attrib";
2180       if (check_command($command)){
2181         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2182         exec($command, $output);
2183         if (preg_match("/^[0-9]+$/", $output[0])){
2184           return ($output[0]);
2185         } else {
2186           msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2187           return ($config->get_cfg_value("uidbase"));
2188         }
2189       } else {
2190         msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2191         return ($config->get_cfg_value("uidbase"));
2192       }
2194     } else {
2196       msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
2197       return ($config->get_cfg_value("uidbase"));
2199     }
2200   }
2204 function check_schema_version($class, $version)
2206   return preg_match("/\(v$version\)/", $class['DESC']);
2210 function check_schema($cfg,$rfc2307bis = FALSE)
2212   $messages= array();
2214   /* Get objectclasses */
2215   $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']));
2216   $objectclasses = $ldap->get_objectclasses();
2217   if(count($objectclasses) == 0){
2218     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2219   }
2221   /* This is the default block used for each entry.
2222    *  to avoid unset indexes.
2223    */
2224   $def_check = array("REQUIRED_VERSION" => "0",
2225       "SCHEMA_FILES"     => array(),
2226       "CLASSES_REQUIRED" => array(),
2227       "STATUS"           => FALSE,
2228       "IS_MUST_HAVE"     => FALSE,
2229       "MSG"              => "",
2230       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2232   /* The gosa base schema */
2233   $checks['gosaObject'] = $def_check;
2234   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2235   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2236   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2237   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2239   /* GOsa Account class */
2240   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2241   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2242   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2243   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2244   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2246   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2247   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2248   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2249   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2250   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2251   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2253   /* Some other checks */
2254   foreach(array(
2255         "gosaCacheEntry"        => array("version" => "2.4"),
2256         "gosaDepartment"        => array("version" => "2.4"),
2257         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2258         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2259         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2260         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2261         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2262         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2263         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2264         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2265         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2266         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2267         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2268         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2269         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2270         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2271         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2272         "goLdapServer"          => array("version" => "2.4"),
2273         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2274         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2275         "goKrbServer"           => array("version" => "2.4"),
2276         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2277         ) as $name => $values){
2279           $checks[$name] = $def_check;
2280           if(isset($values['version'])){
2281             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2282           }
2283           if(isset($values['file'])){
2284             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2285           }
2286           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2287         }
2288   foreach($checks as $name => $value){
2289     foreach($value['CLASSES_REQUIRED'] as $class){
2291       if(!isset($objectclasses[$name])){
2292         $checks[$name]['STATUS'] = FALSE;
2293         if($value['IS_MUST_HAVE']){
2294           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2295         }else{
2296           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2297         }
2298       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2299         $checks[$name]['STATUS'] = FALSE;
2301         if($value['IS_MUST_HAVE']){
2302           $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2303         }else{
2304           $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2305         }
2306       }else{
2307         $checks[$name]['STATUS'] = TRUE;
2308         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2309       }
2310     }
2311   }
2313   $tmp = $objectclasses;
2315   /* The gosa base schema */
2316   $checks['posixGroup'] = $def_check;
2317   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2318   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2319   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2320   $checks['posixGroup']['STATUS']           = TRUE;
2321   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2322   $checks['posixGroup']['MSG']              = "";
2323   $checks['posixGroup']['INFO']             = "";
2325   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2326   if(isset($tmp['posixGroup'])){
2328     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2329       $checks['posixGroup']['STATUS']           = FALSE;
2330       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2331       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2332     }
2333     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2334       $checks['posixGroup']['STATUS']           = FALSE;
2335       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2336       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2337     }
2338   }
2340   return($checks);
2344 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2346   $tmp = array(
2347         "de_DE" => "German",
2348         "fr_FR" => "French",
2349         "it_IT" => "Italian",
2350         "es_ES" => "Spanish",
2351         "en_US" => "English",
2352         "nl_NL" => "Dutch",
2353         "pl_PL" => "Polish",
2354         "sv_SE" => "Swedish",
2355         "zh_CN" => "Chinese",
2356         "vi_VN" => "Vietnamese",
2357         "ru_RU" => "Russian");
2358   
2359   $tmp2= array(
2360         "de_DE" => _("German"),
2361         "fr_FR" => _("French"),
2362         "it_IT" => _("Italian"),
2363         "es_ES" => _("Spanish"),
2364         "en_US" => _("English"),
2365         "nl_NL" => _("Dutch"),
2366         "pl_PL" => _("Polish"),
2367         "sv_SE" => _("Swedish"),
2368         "zh_CN" => _("Chinese"),
2369         "vi_VN" => _("Vietnamese"),
2370         "ru_RU" => _("Russian"));
2372   $ret = array();
2373   if($languages_in_own_language){
2375     $old_lang = setlocale(LC_ALL, 0);
2377     /* If the locale wasn't correclty set before, there may be an incorrect
2378         locale returned. Something like this: 
2379           C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2380         Extract the locale name from this string and use it to restore old locale.
2381      */
2382     if(preg_match("/LC_CTYPE/",$old_lang)){
2383       $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2384     }
2385     
2386     foreach($tmp as $key => $name){
2387       $lang = $key.".UTF-8";
2388       setlocale(LC_ALL, $lang);
2389       if($strip_region_tag){
2390         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2391       }else{
2392         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2393       }
2394     }
2395     setlocale(LC_ALL, $old_lang);
2396   }else{
2397     foreach($tmp as $key => $name){
2398       if($strip_region_tag){
2399         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2400       }else{
2401         $ret[$key] = _($name);
2402       }
2403     }
2404   }
2405   return($ret);
2409 /* Returns contents of the given POST variable and check magic quotes settings */
2410 function get_post($name)
2412   if(!isset($_POST[$name])){
2413     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2414     return(FALSE);
2415   }
2416   if(get_magic_quotes_gpc()){
2417     return(stripcslashes($_POST[$name]));
2418   }else{
2419     return($_POST[$name]);
2420   }
2424 /* Return class name in correct case */
2425 function get_correct_class_name($cls)
2427   global $class_mapping;
2428   if(isset($class_mapping) && is_array($class_mapping)){
2429     foreach($class_mapping as $class => $file){
2430       if(preg_match("/^".$cls."$/i",$class)){
2431         return($class);
2432       }
2433     }
2434   }
2435   return(FALSE);
2439 // change_password, changes the Password, of the given dn
2440 function change_password ($dn, $password, $mode=0, $hash= "")
2442   global $config;
2443   $newpass= "";
2445   /* Convert to lower. Methods are lowercase */
2446   $hash= strtolower($hash);
2448   // Get all available encryption Methods
2450   // NON STATIC CALL :)
2451   $methods = new passwordMethod(session::get('config'));
2452   $available = $methods->get_available_methods();
2454   // read current password entry for $dn, to detect the encryption Method
2455   $ldap       = $config->get_ldap_link();
2456   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2457   $attrs      = $ldap->fetch ();
2459   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2460   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2461     $deactivated = TRUE;
2462   }else{
2463     $deactivated = FALSE;
2464   }
2466   /* Is ensure that clear passwords will stay clear */
2467   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2468     $hash = "clear";
2469   }
2471   // Detect the encryption Method
2472   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2474     /* Check for supported algorithm */
2475     mt_srand((double) microtime()*1000000);
2477     /* Extract used hash */
2478     if ($hash == ""){
2479       $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2480     } else {
2481       $test = new $available[$hash]($config,$dn);
2482       $test->set_hash($hash);
2483     }
2485   } else {
2486     // User MD5 by default
2487     $hash= "md5";
2488     $test = new  $available['md5']($config);
2489   }
2491   /* Feed password backends with information */
2492   $test->dn= $dn;
2493   $test->attrs= $attrs;
2494   $newpass= $test->generate_hash($password);
2496   // Update shadow timestamp?
2497   if (isset($attrs["shadowLastChange"][0])){
2498     $shadow= (int)(date("U") / 86400);
2499   } else {
2500     $shadow= 0;
2501   }
2503   // Write back modified entry
2504   $ldap->cd($dn);
2505   $attrs= array();
2507   // Not for groups
2508   if ($mode == 0){
2510     if ($shadow != 0){
2511       $attrs['shadowLastChange']= $shadow;
2512     }
2514     // Create SMB Password
2515     $attrs= generate_smb_nt_hash($password);
2516   }
2518  /* Read ! if user was deactivated */
2519   if($deactivated){
2520     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2521   }
2523   $attrs['userPassword']= array();
2524   $attrs['userPassword']= $newpass;
2526   $ldap->modify($attrs);
2528   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2530   if (!$ldap->success()) {
2531     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2532   } else {
2534     /* Run backend method for change/create */
2535     if(!$test->set_password($password)){
2536       return(FALSE);
2537     }
2539     /* Find postmodify entries for this class */
2540     $command= $config->search("password", "POSTMODIFY",array('menu'));
2542     if ($command != ""){
2543       /* Walk through attribute list */
2544       $command= preg_replace("/%userPassword/", $password, $command);
2545       $command= preg_replace("/%dn/", $dn, $command);
2547       if (check_command($command)){
2548         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2549         exec($command);
2550       } else {
2551         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2552         msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2553       }
2554     }
2555   }
2556   return(TRUE);
2560 // Return something like array['sambaLMPassword']= "lalla..."
2561 function generate_smb_nt_hash($password)
2563   global $config;
2565   # Try to use gosa-si?
2566   if ($config->get_cfg_value("gosa_si") != ""){
2567         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2568     if (isset($res['XML']['HASH'])){
2569         $hash= $res['XML']['HASH'];
2570     } else {
2571       $hash= "";
2572     }
2573   } else {
2574           $tmp= $config->get_cfg_value('smbhash')." ".escapeshellarg($password);
2575           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2577           exec($tmp, $ar);
2578           flush();
2579           reset($ar);
2580           $hash= current($ar);
2581   }
2583   if ($hash == "") {
2584           msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2585           return ("");
2586   }
2588   list($lm,$nt)= split (":", trim($hash));
2590   if ($config->get_cfg_value("sambaversion") == 3) {
2591           $attrs['sambaLMPassword']= $lm;
2592           $attrs['sambaNTPassword']= $nt;
2593           $attrs['sambaPwdLastSet']= date('U');
2594           $attrs['sambaBadPasswordCount']= "0";
2595           $attrs['sambaBadPasswordTime']= "0";
2596   } else {
2597           $attrs['lmPassword']= $lm;
2598           $attrs['ntPassword']= $nt;
2599           $attrs['pwdLastSet']= date('U');
2600   }
2601   return($attrs);
2605 function getEntryCSN($dn)
2607   global $config;
2608   if(empty($dn) || !is_object($config)){
2609     return("");
2610   }
2612   /* Get attribute that we should use as serial number */
2613   $attr= $config->get_cfg_value("uniq_identifier");
2614   if($attr != ""){
2615     $ldap = $config->get_ldap_link();
2616     $ldap->cat($dn,array($attr));
2617     $csn = $ldap->fetch();
2618     if(isset($csn[$attr][0])){
2619       return($csn[$attr][0]);
2620     }
2621   }
2622   return("");
2626 /* Add a given objectClass to an attrs entry */
2627 function add_objectClass($classes, &$attrs)
2629   if (is_array($classes)){
2630     $list= $classes;
2631   } else {
2632     $list= array($classes);
2633   }
2635   foreach ($list as $class){
2636     $attrs['objectClass'][]= $class;
2637   }
2641 /* Removes a given objectClass from the attrs entry */
2642 function remove_objectClass($classes, &$attrs)
2644   if (isset($attrs['objectClass'])){
2645     /* Array? */
2646     if (is_array($classes)){
2647       $list= $classes;
2648     } else {
2649       $list= array($classes);
2650     }
2652     $tmp= array();
2653     foreach ($attrs['objectClass'] as $oc) {
2654       foreach ($list as $class){
2655         if ($oc != $class){
2656           $tmp[]= $oc;
2657         }
2658       }
2659     }
2660     $attrs['objectClass']= $tmp;
2661   }
2664 /*! \brief  Initialize a file download with given content, name and data type. 
2665  *  @param  data  String The content to send.
2666  *  @param  name  String The name of the file.
2667  *  @param  type  String The content identifier, default value is "application/octet-stream";
2668  */
2669 function send_binary_content($data,$name,$type = "application/octet-stream")
2671   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2672   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2673   header("Cache-Control: no-cache");
2674   header("Pragma: no-cache");
2675   header("Cache-Control: post-check=0, pre-check=0");
2676   header("Content-type: ".$type."");
2678   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2680   /* Strip name if it is a complete path */
2681   if (preg_match ("/\//", $name)) {
2682         $name= basename($name);
2683   }
2684   
2685   /* force download dialog */
2686   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2687     header('Content-Disposition: filename="'.$name.'"');
2688   } else {
2689     header('Content-Disposition: attachment; filename="'.$name.'"');
2690   }
2692   echo $data;
2693   exit();
2697 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2699   if(is_string($str)){
2700     return(htmlentities($str,$type,$charset));
2701   }elseif(is_array($str)){
2702     foreach($str as $name => $value){
2703       $str[$name] = reverse_html_entities($value,$type,$charset);
2704     }
2705   }
2706   return($str);
2710 /*! \brief Encode special string characters so we can use the string in \
2711            HTML output, without breaking quotes.
2712     @param  The String we want to encode.
2713     @return The encoded String
2714  */
2715 function xmlentities($str)
2716
2717   if(is_string($str)){
2719     static $asc2uni= array();
2720     if (!count($asc2uni)){
2721       for($i=128;$i<256;$i++){
2722     #    $asc2uni[chr($i)] = "&#x".dechex($i).";";
2723       }
2724     }
2726     $str = str_replace("&", "&amp;", $str);
2727     $str = str_replace("<", "&lt;", $str);
2728     $str = str_replace(">", "&gt;", $str);
2729     $str = str_replace("'", "&apos;", $str);
2730     $str = str_replace("\"", "&quot;", $str);
2731     $str = str_replace("\r", "", $str);
2732     $str = strtr($str,$asc2uni);
2733     return $str;
2734   }elseif(is_array($str)){
2735     foreach($str as $name => $value){
2736       $str[$name] = xmlentities($value);
2737     }
2738   }
2739   return($str);
2743 /*! \brief  Updates all accessTo attributes from a given value to a new one.
2744             For example if a host is renamed.
2745     @param  String  $from The source accessTo name.
2746     @param  String  $to   The destination accessTo name.
2747 */
2748 function update_accessTo($from,$to)
2750   global $config;
2751   $ldap = $config->get_ldap_link();
2752   $ldap->cd($config->current['BASE']);
2753   $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2754   while($attrs = $ldap->fetch()){
2755     $new_attrs = array("accessTo" => array());
2756     $dn = $attrs['dn'];
2757     for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2758       $new_attrs['objectClass'][] =  $attrs['objectClass'][$i];
2759     }
2760     for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2761       if($attrs['accessTo'][$i] == $from){
2762         if(!empty($to)){
2763           $new_attrs['accessTo'][] =  $to;
2764         }
2765       }else{
2766         $new_attrs['accessTo'][] =  $attrs['accessTo'][$i]; 
2767       }
2768     }
2769     $ldap->cd($dn);
2770     $ldap->modify($new_attrs);
2771     if (!$ldap->success()){
2772       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2773     }
2774     new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2775   }
2779 function get_random_char () {
2780      $randno = rand (0, 63);
2781      if ($randno < 12) {
2782          return (chr ($randno + 46)); // Digits, '/' and '.'
2783      } else if ($randno < 38) {
2784          return (chr ($randno + 53)); // Uppercase
2785      } else {
2786          return (chr ($randno + 59)); // Lowercase
2787      }
2791 function cred_encrypt($input, $password) {
2793   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2794   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2796   return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2800 function cred_decrypt($input,$password) {
2801   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2802   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2804   return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2808 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2809 ?>