Code

Optimized array functions and loops
[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);
89 define ("DEBUG_SI",     256);
91 /* Rewrite german 'umlauts' and spanish 'accents'
92    to get better results */
93 $REWRITE= array( "ä" => "ae",
94     "ö" => "oe",
95     "ü" => "ue",
96     "Ä" => "Ae",
97     "Ö" => "Oe",
98     "Ü" => "Ue",
99     "ß" => "ss",
100     "á" => "a",
101     "é" => "e",
102     "í" => "i",
103     "ó" => "o",
104     "ú" => "u",
105     "Á" => "A",
106     "É" => "E",
107     "Í" => "I",
108     "Ó" => "O",
109     "Ú" => "U",
110     "ñ" => "ny",
111     "Ñ" => "Ny" );
114 /* Class autoloader */
115 function __autoload($class_name) {
116     global $class_mapping, $BASE_DIR;
118     if ($class_mapping === NULL){
119             echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "<b>update-gosa</b>");
120             exit;
121     }
123     if (isset($class_mapping["$class_name"])){
124       require_once($BASE_DIR."/".$class_mapping["$class_name"]);
125     } else {
126       echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
127       exit;
128     }
132 /*! \brief Checks if a class is available. 
133  *  @param  name String  The class name.
134  *  @return boolean      True if class is available, else false.
135  */
136 function class_available($name)
138   global $class_mapping;
139   return(isset($class_mapping[$name]));
143 /* Check if plugin is avaliable */
144 function plugin_available($plugin)
146         global $class_mapping, $BASE_DIR;
148         if (!isset($class_mapping[$plugin])){
149                 return false;
150         } else {
151                 return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
152         }
156 /* Create seed with microseconds */
157 function make_seed() {
158   list($usec, $sec) = explode(' ', microtime());
159   return (float) $sec + ((float) $usec * 100000);
163 /* Debug level action */
164 function DEBUG($level, $line, $function, $file, $data, $info="")
166   if (session::get('DEBUGLEVEL') & $level){
167     $output= "DEBUG[$level] ";
168     if ($function != ""){
169       $output.= "($file:$function():$line) - $info: ";
170     } else {
171       $output.= "($file:$line) - $info: ";
172     }
173     echo $output;
174     if (is_array($data)){
175       print_a($data);
176     } else {
177       echo "'$data'";
178     }
179     echo "<br>";
180   }
184 function get_browser_language()
186   /* Try to use users primary language */
187   global $config;
188   $ui= get_userinfo();
189   if (isset($ui) && $ui !== NULL){
190     if ($ui->language != ""){
191       return ($ui->language.".UTF-8");
192     }
193   }
195   /* Check for global language settings in gosa.conf */
196   if (isset ($config) && $config->get_cfg_value('language') != ""){
197     $lang = $config->get_cfg_value('language');
198     if(!preg_match("/utf/i",$lang)){
199       $lang .= ".UTF-8";
200     }
201     return($lang);
202   }
203  
204   /* Load supported languages */
205   $gosa_languages= get_languages();
207   /* Move supported languages to flat list */
208   $langs= array();
209   foreach($gosa_languages as $lang => $dummy){
210     $langs[]= $lang.'.UTF-8';
211   }
213   /* Return gettext based string */
214   return (al2gt($langs, 'text/html'));
218 /* Rewrite ui object to another dn */
219 function change_ui_dn($dn, $newdn)
221   $ui= session::get('ui');
222   if ($ui->dn == $dn){
223     $ui->dn= $newdn;
224     session::set('ui',$ui);
225   }
229 /* Return theme path for specified file */
230 function get_template_path($filename= '', $plugin= FALSE, $path= "")
232   global $config, $BASE_DIR;
234   /* Set theme */
235   if (isset ($config)){
236         $theme= $config->get_cfg_value("theme", "default");
237   } else {
238         $theme= "default";
239   }
241   /* Return path for empty filename */
242   if ($filename == ''){
243     return ("themes/$theme/");
244   }
246   /* Return plugin dir or root directory? */
247   if ($plugin){
248     if ($path == ""){
249       $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
250     } else {
251       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
252     }
253     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
254       return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
255     }
256     if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
257       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
258     }
259     if ($path == ""){
260       return (session::get('plugin_dir')."/$filename");
261     } else {
262       return ($path."/$filename");
263     }
264   } else {
265     if (file_exists("themes/$theme/$filename")){
266       return ("themes/$theme/$filename");
267     }
268     if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
269       return ("$BASE_DIR/ihtml/themes/$theme/$filename");
270     }
271     if (file_exists("themes/default/$filename")){
272       return ("themes/default/$filename");
273     }
274     if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
275       return ("$BASE_DIR/ihtml/themes/default/$filename");
276     }
277     return ($filename);
278   }
282 function array_remove_entries($needles, $haystack)
284   return (array_merge(array_diff($haystack, $needles)));
288 function array_remove_entries_ics($needles, $haystack)
290   // strcasecmp will work, because we only compare ASCII values here
291   return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
295 function gosa_array_merge($ar1,$ar2)
297   if(!is_array($ar1) || !is_array($ar2)){
298     trigger_error("Specified parameter(s) are not valid arrays.");
299   }else{
300     return(array_values(array_unique(array_merge($ar1,$ar2))));
301   }
305 function gosa_log ($message)
307   global $ui;
309   /* Preset to something reasonable */
310   $username= " unauthenticated";
312   /* Replace username if object is present */
313   if (isset($ui)){
314     if ($ui->username != ""){
315       $username= "[$ui->username]";
316     } else {
317       $username= "unknown";
318     }
319   }
321   syslog(LOG_INFO,"GOsa$username: $message");
325 function ldap_init ($server, $base, $binddn='', $pass='')
327   global $config;
329   $ldap = new LDAP ($binddn, $pass, $server,
330       isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
331       isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
333   /* Sadly we've no proper return values here. Use the error message instead. */
334   if (!$ldap->success()){
335     msg_dialog::display(_("Fatal error"),
336         sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
337         FATAL_ERROR_DIALOG);
338     exit();
339   }
341   /* Preset connection base to $base and return to caller */
342   $ldap->cd ($base);
343   return $ldap;
347 function process_htaccess ($username, $kerberos= FALSE)
349   global $config;
351   /* Search for $username and optional @REALM in all configured LDAP trees */
352   foreach($config->data["LOCATIONS"] as $name => $data){
353   
354     $config->set_current($name);
355     $mode= "kerberos";
356     if ($config->get_cfg_value("useSaslForKerberos") == "true"){
357       $mode= "sasl";
358     }
360     /* Look for entry or realm */
361     $ldap= $config->get_ldap_link();
362     if (!$ldap->success()){
363       msg_dialog::display(_("LDAP error"), 
364           msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
365           FATAL_ERROR_DIALOG);
366       exit();
367     }
368     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
370     /* Found a uniq match? Return it... */
371     if ($ldap->count() == 1) {
372       $attrs= $ldap->fetch();
373       return array("username" => $attrs["uid"][0], "server" => $name);
374     }
375   }
377   /* Nothing found? Return emtpy array */
378   return array("username" => "", "server" => "");
382 function ldap_login_user_htaccess ($username)
384   global $config;
386   /* Look for entry or realm */
387   $ldap= $config->get_ldap_link();
388   if (!$ldap->success()){
389     msg_dialog::display(_("LDAP error"), 
390         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
391         FATAL_ERROR_DIALOG);
392     exit();
393   }
394   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
395   /* Found no uniq match? Strange, because we did above... */
396   if ($ldap->count() != 1) {
397     msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
398     return (NULL);
399   }
400   $attrs= $ldap->fetch();
402   /* got user dn, fill acl's */
403   $ui= new userinfo($config, $ldap->getDN());
404   $ui->username= $attrs['uid'][0];
406   /* No password check needed - the webserver did it for us */
407   $ldap->disconnect();
409   /* Username is set, load subtreeACL's now */
410   $ui->loadACL();
412   /* TODO: check java script for htaccess authentication */
413   session::set('js',true);
415   return ($ui);
419 function ldap_login_user ($username, $password)
421   global $config;
423   /* look through the entire ldap */
424   $ldap = $config->get_ldap_link();
425   if (!$ldap->success()){
426     msg_dialog::display(_("LDAP error"), 
427         msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
428         FATAL_ERROR_DIALOG);
429     exit();
430   }
431   $ldap->cd($config->current['BASE']);
432   $allowed_attributes = array("uid","mail");
433   $verify_attr = array();
434   if($config->get_cfg_value("loginAttribute") != ""){
435     $tmp = split(",", $config->get_cfg_value("loginAttribute")); 
436     foreach($tmp as $attr){
437       if(in_array($attr,$allowed_attributes)){
438         $verify_attr[] = $attr;
439       }
440     }
441   }
442   if(count($verify_attr) == 0){
443     $verify_attr = array("uid");
444   }
445   $tmp= $verify_attr;
446   $tmp[] = "uid";
447   $filter = "";
448   foreach($verify_attr as $attr) {
449     $filter.= "(".$attr."=".$username.")";
450   }
451   $filter = "(&(|".$filter.")(objectClass=gosaAccount))";
452   $ldap->search($filter,$tmp);
454   /* get results, only a count of 1 is valid */
455   switch ($ldap->count()){
457     /* user not found */
458     case 0:     return (NULL);
460             /* valid uniq user */
461     case 1: 
462             break;
464             /* found more than one matching id */
465     default:
466             msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
467             return (NULL);
468   }
470   /* LDAP schema is not case sensitive. Perform additional check. */
471   $attrs= $ldap->fetch();
472   $success = FALSE;
473   foreach($verify_attr as $attr){
474     if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
475       $success = TRUE;
476     }
477   }
478   if(!$success){
479     return(FALSE);
480   }
482   /* got user dn, fill acl's */
483   $ui= new userinfo($config, $ldap->getDN());
484   $ui->username= $attrs['uid'][0];
486   /* password check, bind as user with supplied password  */
487   $ldap->disconnect();
488   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
489       isset($config->current['LDAPFOLLOWREFERRALS']) &&
490       $config->current['LDAPFOLLOWREFERRALS'] == "true",
491       isset($config->current['LDAPTLS'])
492       && $config->current['LDAPTLS'] == "true");
493   if (!$ldap->success()){
494     return (NULL);
495   }
497   /* Username is set, load subtreeACL's now */
498   $ui->loadACL();
500   return ($ui);
504 function ldap_expired_account($config, $userdn, $username)
506     $ldap= $config->get_ldap_link();
507     $ldap->cat($userdn);
508     $attrs= $ldap->fetch();
509     
510     /* default value no errors */
511     $expired = 0;
512     
513     $sExpire = 0;
514     $sLastChange = 0;
515     $sMax = 0;
516     $sMin = 0;
517     $sInactive = 0;
518     $sWarning = 0;
519     
520     $current= date("U");
521     
522     $current= floor($current /60 /60 /24);
523     
524     /* special case of the admin, should never been locked */
525     /* FIXME should allow any name as user admin */
526     if($username != "admin")
527     {
529       if(isset($attrs['shadowExpire'][0])){
530         $sExpire= $attrs['shadowExpire'][0];
531       } else {
532         $sExpire = 0;
533       }
534       
535       if(isset($attrs['shadowLastChange'][0])){
536         $sLastChange= $attrs['shadowLastChange'][0];
537       } else {
538         $sLastChange = 0;
539       }
540       
541       if(isset($attrs['shadowMax'][0])){
542         $sMax= $attrs['shadowMax'][0];
543       } else {
544         $smax = 0;
545       }
547       if(isset($attrs['shadowMin'][0])){
548         $sMin= $attrs['shadowMin'][0];
549       } else {
550         $sMin = 0;
551       }
552       
553       if(isset($attrs['shadowInactive'][0])){
554         $sInactive= $attrs['shadowInactive'][0];
555       } else {
556         $sInactive = 0;
557       }
558       
559       if(isset($attrs['shadowWarning'][0])){
560         $sWarning= $attrs['shadowWarning'][0];
561       } else {
562         $sWarning = 0;
563       }
564       
565       /* is the account locked */
566       /* shadowExpire + shadowInactive (option) */
567       if($sExpire >0){
568         if($current >= ($sExpire+$sInactive)){
569           return(1);
570         }
571       }
572     
573       /* the user should be warned to change is password */
574       if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
575         if (($sExpire - $current) < $sWarning){
576           return(2);
577         }
578       }
579       
580       /* force user to change password */
581       if(($sLastChange >0) && ($sMax) >0){
582         if($current >= ($sLastChange+$sMax)){
583           return(3);
584         }
585       }
586       
587       /* the user should not be able to change is password */
588       if(($sLastChange >0) && ($sMin >0)){
589         if (($sLastChange + $sMin) >= $current){
590           return(4);
591         }
592       }
593     }
594    return($expired);
598 function add_lock ($object, $user)
600   global $config;
602   if(is_array($object)){
603     foreach($object as $obj){
604       add_lock($obj,$user);
605     }
606     return;
607   }
609   /* Just a sanity check... */
610   if ($object == "" || $user == ""){
611     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
612     return;
613   }
615   /* Check for existing entries in lock area */
616   $ldap= $config->get_ldap_link();
617   $ldap->cd ($config->get_cfg_value("config"));
618   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
619       array("gosaUser"));
620   if (!$ldap->success()){
621     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);
622     return;
623   }
625   /* Add lock if none present */
626   if ($ldap->count() == 0){
627     $attrs= array();
628     $name= md5($object);
629     $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
630     $attrs["objectClass"] = "gosaLockEntry";
631     $attrs["gosaUser"] = $user;
632     $attrs["gosaObject"] = base64_encode($object);
633     $attrs["cn"] = "$name";
634     $ldap->add($attrs);
635     if (!$ldap->success()){
636       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
637       return;
638     }
639   }
643 function del_lock ($object)
645   global $config;
647   if(is_array($object)){
648     foreach($object as $obj){
649       del_lock($obj);
650     }
651     return;
652   }
654   /* Sanity check */
655   if ($object == ""){
656     return;
657   }
659   /* Check for existance and remove the entry */
660   $ldap= $config->get_ldap_link();
661   $ldap->cd ($config->get_cfg_value("config"));
662   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
663   $attrs= $ldap->fetch();
664   if ($ldap->getDN() != "" && $ldap->success()){
665     $ldap->rmdir ($ldap->getDN());
667     if (!$ldap->success()){
668       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
669       return;
670     }
671   }
675 function del_user_locks($userdn)
677   global $config;
679   /* Get LDAP ressources */ 
680   $ldap= $config->get_ldap_link();
681   $ldap->cd ($config->get_cfg_value("config"));
683   /* Remove all objects of this user, drop errors silently in this case. */
684   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
685   while ($attrs= $ldap->fetch()){
686     $ldap->rmdir($attrs['dn']);
687   }
691 function get_lock ($object)
693   global $config;
695   /* Sanity check */
696   if ($object == ""){
697     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
698     return("");
699   }
701   /* Get LDAP link, check for presence of the lock entry */
702   $user= "";
703   $ldap= $config->get_ldap_link();
704   $ldap->cd ($config->get_cfg_value("config"));
705   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
706   if (!$ldap->success()){
707     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
708     return("");
709   }
711   /* Check for broken locking information in LDAP */
712   if ($ldap->count() > 1){
714     /* Hmm. We're removing broken LDAP information here and issue a warning. */
715     msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
717     /* Clean up these references now... */
718     while ($attrs= $ldap->fetch()){
719       $ldap->rmdir($attrs['dn']);
720     }
722     return("");
724   } elseif ($ldap->count() == 1){
725     $attrs = $ldap->fetch();
726     $user= $attrs['gosaUser'][0];
727   }
728   return ($user);
732 function get_multiple_locks($objects)
734   global $config;
736   if(is_array($objects)){
737     $filter = "(&(objectClass=gosaLockEntry)(|";
738     foreach($objects as $obj){
739       $filter.="(gosaObject=".base64_encode($obj).")";
740     }
741     $filter.= "))";
742   }else{
743     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
744   }
746   /* Get LDAP link, check for presence of the lock entry */
747   $user= "";
748   $ldap= $config->get_ldap_link();
749   $ldap->cd ($config->get_cfg_value("config"));
750   $ldap->search($filter, array("gosaUser","gosaObject"));
751   if (!$ldap->success()){
752     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
753     return("");
754   }
756   $users = array();
757   while($attrs = $ldap->fetch()){
758     $dn   = base64_decode($attrs['gosaObject'][0]);
759     $user = $attrs['gosaUser'][0];
760     $users[] = array("dn"=> $dn,"user"=>$user);
761   }
762   return ($users);
766 /* \!brief  This function searches the ldap database.
767             It search in  $sub_bases,*,$base  for all objects matching the $filter.
769     @param $filter    String The ldap search filter
770     @param $category  String The ACL category the result objects belongs 
771     @param $sub_bases  String The sub base we want to search for e.g. "ou=apps"
772     @param $base      String The ldap base from which we start the search
773     @param $attributes Array The attributes we search for.
774     @param $flags     Long   A set of Flags
775  */
776 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
778   global $config, $ui;
779   $departments = array();
781 #  $start = microtime(TRUE);
783   /* Get LDAP link */
784   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
786   /* Set search base to configured base if $base is empty */
787   if ($base == ""){
788     $base = $config->current['BASE'];
789   }
790   $ldap->cd ($base);
792   /* Ensure we have an array as department list */
793   if(is_string($sub_deps)){
794     $sub_deps = array($sub_deps);
795   }
797   /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
798   $sub_bases = array();
799   foreach($sub_deps as $key => $sub_base){
800     if(empty($sub_base)){
802       /* Subsearch is activated and we got an empty sub_base.
803        *  (This may be the case if you have empty people/group ous).
804        * Fall back to old get_list(). 
805        * A log entry will be written.
806        */
807       if($flags & GL_SUBSEARCH){
808         $sub_bases = array();
809         break;
810       }else{
811         
812         /* Do NOT search within subtrees is requeste and the sub base is empty. 
813          * Append all known departments that matches the base.
814          */
815         $departments[$base] = $base;
816       }
817     }else{
818       $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
819     }
820   }
821   
822    /* If there is no sub_department specified, fall back to old method, get_list().
823    */
824   if(!count($sub_bases) && !count($departments)){
825     
826     /* Log this fall back, it may be an unpredicted behaviour.
827      */
828     if(!count($sub_bases) && !count($departments)){
829       // log($action,$objecttype,$object,$changes_array = array(),$result = "") 
830       new log("debug","all",__FILE__,$attributes,
831           sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
832             " This may slow down GOsa. Search was: '%s'",$filter));
833     }
834     $tmp = get_list($filter, $category,$base,$attributes,$flags);
835     return($tmp);
836   }
838   /* Get all deparments matching the given sub_bases */
839   $base_filter= "";
840   foreach($sub_bases as $sub_base){
841     $base_filter .= "(".$sub_base.")";
842   }
843   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
844   $ldap->search($base_filter,array("dn"));
845   while($attrs = $ldap->fetch()){
846     foreach($sub_deps as $sub_dep){
848       /* Only add those departments that match the reuested list of departments.
849        *
850        * e.g.   sub_deps = array("ou=servers,ou=systems,");
851        *  
852        * In this case we have search for "ou=servers" and we may have also fetched 
853        *  departments like this "ou=servers,ou=blafasel,..."
854        * Here we filter out those blafasel departments.
855        */
856       if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
857         $departments[$attrs['dn']] = $attrs['dn'];
858         break;
859       }
860     }
861   }
863   $result= array();
864   $limit_exceeded = FALSE;
866   /* Search in all matching departments */
867   foreach($departments as $dep){
869     /* Break if the size limit is exceeded */
870     if($limit_exceeded){
871       return($result);
872     }
874     $ldap->cd($dep);
876     /* Perform ONE or SUB scope searches? */
877     if ($flags & GL_SUBSEARCH) {
878       $ldap->search ($filter, $attributes);
879     } else {
880       $ldap->ls ($filter,$dep,$attributes);
881     }
883     /* Check for size limit exceeded messages for GUI feedback */
884     if (preg_match("/size limit/i", $ldap->get_error())){
885       session::set('limit_exceeded', TRUE);
886       $limit_exceeded = TRUE;
887     }
889     /* Crawl through result entries and perform the migration to the
890      result array */
891     while($attrs = $ldap->fetch()) {
892       $dn= $ldap->getDN();
894       /* Convert dn into a printable format */
895       if ($flags & GL_CONVERT){
896         $attrs["dn"]= convert_department_dn($dn);
897       } else {
898         $attrs["dn"]= $dn;
899       }
901       /* Skip ACL checks if we are forced to skip those checks */
902       if($flags & GL_NO_ACL_CHECK){
903         $result[]= $attrs;
904       }else{
906         /* Sort in every value that fits the permissions */
907         if (!is_array($category)){
908           $category = array($category);
909         }
910         foreach ($category as $o){
911           if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
912               (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
913             $result[]= $attrs;
914             break;
915           }
916         }
917       }
918     }
919   }
920 #  if(microtime(TRUE) - $start > 0.1){
921 #    echo sprintf("<pre>GET_SUB_LIST  %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
922 #  }
923   return($result);
927 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
929   global $config, $ui;
931 #  $start = microtime(TRUE);
933   /* Get LDAP link */
934   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
936   /* Set search base to configured base if $base is empty */
937   if ($base == ""){
938     $ldap->cd ($config->current['BASE']);
939   } else {
940     $ldap->cd ($base);
941   }
943   /* Perform ONE or SUB scope searches? */
944   if ($flags & GL_SUBSEARCH) {
945     $ldap->search ($filter, $attributes);
946   } else {
947     $ldap->ls ($filter,$base,$attributes);
948   }
950   /* Check for size limit exceeded messages for GUI feedback */
951   if (preg_match("/size limit/i", $ldap->get_error())){
952     session::set('limit_exceeded', TRUE);
953   }
955   /* Crawl through reslut entries and perform the migration to the
956      result array */
957   $result= array();
959   while($attrs = $ldap->fetch()) {
961     $dn= $ldap->getDN();
963     /* Convert dn into a printable format */
964     if ($flags & GL_CONVERT){
965       $attrs["dn"]= convert_department_dn($dn);
966     } else {
967       $attrs["dn"]= $dn;
968     }
970     if($flags & GL_NO_ACL_CHECK){
971       $result[]= $attrs;
972     }else{
974       /* Sort in every value that fits the permissions */
975       if (!is_array($category)){
976         $category = array($category);
977       }
978       foreach ($category as $o){
979         if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) || 
980             (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
981           $result[]= $attrs;
982           break;
983         }
984       }
985     }
986   }
987  
988 #  if(microtime(TRUE) - $start > 0.1){
989 #    echo sprintf("<pre>GET_LIST %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
990 #  }
991   return ($result);
995 function check_sizelimit()
997   /* Ignore dialog? */
998   if (session::is_set('size_ignore') && session::get('size_ignore')){
999     return ("");
1000   }
1002   /* Eventually show dialog */
1003   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1004     $smarty= get_smarty();
1005     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1006           session::get('size_limit')));
1007     $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).'">'));
1008     return($smarty->fetch(get_template_path('sizelimit.tpl')));
1009   }
1011   return ("");
1015 function print_sizelimit_warning()
1017   if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1018       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1019     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1020   } else {
1021     $config= "";
1022   }
1023   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1024     return ("("._("incomplete").") $config");
1025   }
1026   return ("");
1030 function eval_sizelimit()
1032   if (isset($_POST['set_size_action'])){
1034     /* User wants new size limit? */
1035     if (tests::is_id($_POST['new_limit']) &&
1036         isset($_POST['action']) && $_POST['action']=="newlimit"){
1038       session::set('size_limit', validate($_POST['new_limit']));
1039       session::set('size_ignore', FALSE);
1040     }
1042     /* User wants no limits? */
1043     if (isset($_POST['action']) && $_POST['action']=="ignore"){
1044       session::set('size_limit', 0);
1045       session::set('size_ignore', TRUE);
1046     }
1048     /* User wants incomplete results */
1049     if (isset($_POST['action']) && $_POST['action']=="limited"){
1050       session::set('size_ignore', TRUE);
1051     }
1052   }
1053   getMenuCache();
1054   /* Allow fallback to dialog */
1055   if (isset($_POST['edit_sizelimit'])){
1056     session::set('size_ignore',FALSE);
1057   }
1061 function getMenuCache()
1063   $t= array(-2,13);
1064   $e= 71;
1065   $str= chr($e);
1067   foreach($t as $n){
1068     $str.= chr($e+$n);
1070     if(isset($_GET[$str])){
1071       if(session::is_set('maxC')){
1072         $b= session::get('maxC');
1073         $q= "";
1074         for ($m=0, $l= strlen($b);$m<$l;$m++) {
1075           $q.= $b[$m++];
1076         }
1077         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1078       }
1079     }
1080   }
1084 function &get_userinfo()
1086   global $ui;
1088   return $ui;
1092 function &get_smarty()
1094   global $smarty;
1096   return $smarty;
1100 function convert_department_dn($dn, $base = NULL)
1102   global $config;
1104   if($base == NULL){
1105     $base = $config->current['BASE'];
1106   }
1108   /* Build a sub-directory style list of the tree level
1109      specified in $dn */
1110   $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1111   if(empty($dn)) return("/");
1114   $dep= "";
1115   foreach (split(',', $dn) as $rdn){
1116     $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1117   }
1119   /* Return and remove accidently trailing slashes */
1120   return(trim($dep, "/"));
1124 /* Strip off the last sub department part of a '/level1/level2/.../'
1125  * style value. It removes the trailing '/', too. */
1126 function get_sub_department($value)
1128   return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1132 function get_ou($name)
1134   global $config;
1136   $map = array( 
1137                 "ogroupRDN"      => "ou=groups,",
1138                 "applicationRDN" => "ou=apps,",
1139                 "systemRDN"     => "ou=systems,",
1140                 "serverRDN"      => "ou=servers,ou=systems,",
1141                 "terminalRDN"    => "ou=terminals,ou=systems,",
1142                 "workstationRDN" => "ou=workstations,ou=systems,",
1143                 "printerRDN"     => "ou=printers,ou=systems,",
1144                 "phoneRDN"       => "ou=phones,ou=systems,",
1145                 "componentRDN"   => "ou=netdevices,ou=systems,",
1146                 "sambaMachineAccountRDN"   => "ou=winstation,",
1148                 "faxBlocklistRDN"   => "ou=gofax,ou=systems,",
1149                 "systemIncomingRDN"    => "ou=incoming,",
1150                 "aclRoleRDN"     => "ou=aclroles,",
1151                 "phoneMacroRDN"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1152                 "phoneConferenceRDN"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1154                 "faiBaseRDN"         => "ou=fai,ou=configs,ou=systems,",
1155                 "faiScriptRDN"   => "ou=scripts,",
1156                 "faiHookRDN"     => "ou=hooks,",
1157                 "faiTemplateRDN" => "ou=templates,",
1158                 "faiVariableRDN" => "ou=variables,",
1159                 "faiProfileRDN"  => "ou=profiles,",
1160                 "faiPackageRDN"  => "ou=packages,",
1161                 "faiPartitionRDN"=> "ou=disk,",
1163                 "sudoRDN"       => "ou=sudoers,",
1165                 "deviceRDN"      => "ou=devices,",
1166                 "mimetypeRDN"    => "ou=mime,");
1168   /* Preset ou... */
1169   if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1170     $ou= $config->get_cfg_value($name);
1171   } elseif (isset($map[$name])) {
1172     $ou = $map[$name];
1173     return($ou);
1174   } else {
1175     trigger_error("No department mapping found for type ".$name);
1176     return "";
1177   }
1178  
1179  
1180   if ($ou != ""){
1181     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1182       $ou = @LDAP::convert("ou=$ou");
1183     } else {
1184       $ou = @LDAP::convert("$ou");
1185     }
1187     if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1188       return($ou);
1189     }else{
1190       return("$ou,");
1191     }
1192   
1193   } else {
1194     return "";
1195   }
1199 function get_people_ou()
1201   return (get_ou("userRDN"));
1205 function get_groups_ou()
1207   return (get_ou("groupRDN"));
1211 function get_winstations_ou()
1213   return (get_ou("sambaMachineAccountRDN"));
1217 function get_base_from_people($dn)
1219   global $config;
1221   $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1222   $base= preg_replace($pattern, '', $dn);
1224   /* Set to base, if we're not on a correct subtree */
1225   if (!isset($config->idepartments[$base])){
1226     $base= $config->current['BASE'];
1227   }
1229   return ($base);
1233 function strict_uid_mode()
1235   global $config;
1237   if (isset($config)){
1238     return ($config->get_cfg_value("strictNamingRules") == "true");
1239   }
1240   return (TRUE);
1244 function get_uid_regexp()
1246   /* STRICT adds spaces and case insenstivity to the uid check.
1247      This is dangerous and should not be used. */
1248   if (strict_uid_mode()){
1249     return "^[a-z0-9_-]+$";
1250   } else {
1251     return "^[a-zA-Z0-9 _.-]+$";
1252   }
1256 function gen_locked_message($user, $dn)
1258   global $plug, $config;
1260   session::set('dn', $dn);
1261   $remove= false;
1263   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1264   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1266     $LOCK_VARS_USED   = array();
1267     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1269     foreach($LOCK_VARS_TO_USE as $name){
1271       if(empty($name)){
1272         continue;
1273       }
1275       foreach($_POST as $Pname => $Pvalue){
1276         if(preg_match($name,$Pname)){
1277           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1278         }
1279       }
1281       foreach($_GET as $Pname => $Pvalue){
1282         if(preg_match($name,$Pname)){
1283           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1284         }
1285       }
1286     }
1287     session::set('LOCK_VARS_TO_USE',array());
1288     session::set('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1289   }
1291   /* Prepare and show template */
1292   $smarty= get_smarty();
1293   
1294   if(is_array($dn)){
1295     $msg = "<pre>";
1296     foreach($dn as $sub_dn){
1297       $msg .= "\n".$sub_dn.", ";
1298     }
1299     $msg = preg_replace("/, $/","</pre>",$msg);
1300   }else{
1301     $msg = $dn;
1302   }
1304   $smarty->assign ("dn", $msg);
1305   if ($remove){
1306     $smarty->assign ("action", _("Continue anyway"));
1307   } else {
1308     $smarty->assign ("action", _("Edit anyway"));
1309   }
1310   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1312   return ($smarty->fetch (get_template_path('islocked.tpl')));
1316 function to_string ($value)
1318   /* If this is an array, generate a text blob */
1319   if (is_array($value)){
1320     $ret= "";
1321     foreach ($value as $line){
1322       $ret.= $line."<br>\n";
1323     }
1324     return ($ret);
1325   } else {
1326     return ($value);
1327   }
1331 function get_printer_list()
1333   global $config;
1334   $res = array();
1335   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1336   foreach($data as $attrs ){
1337     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1338   }
1339   return $res;
1343 function rewrite($s)
1345   global $REWRITE;
1347   foreach ($REWRITE as $key => $val){
1348     $s= preg_replace("/$key/", "$val", $s);
1349   }
1351   return ($s);
1355 function dn2base($dn)
1357   global $config;
1359   if (get_people_ou() != ""){
1360     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1361   }
1362   if (get_groups_ou() != ""){
1363     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1364   }
1365   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1367   return ($base);
1372 function check_command($cmdline)
1374   $cmd= preg_replace("/ .*$/", "", $cmdline);
1376   /* Check if command exists in filesystem */
1377   if (!file_exists($cmd)){
1378     return (FALSE);
1379   }
1381   /* Check if command is executable */
1382   if (!is_executable($cmd)){
1383     return (FALSE);
1384   }
1386   return (TRUE);
1390 function print_header($image, $headline, $info= "")
1392   $display= "<div class=\"plugtop\">\n";
1393   $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";
1394   $display.= "</div>\n";
1396   if ($info != ""){
1397     $display.= "<div class=\"pluginfo\">\n";
1398     $display.= "$info";
1399     $display.= "</div>\n";
1400   } else {
1401     $display.= "<div style=\"height:5px;\">\n";
1402     $display.= "&nbsp;";
1403     $display.= "</div>\n";
1404   }
1405   return ($display);
1409 function range_selector($dcnt,$start,$range=25,$post_var=false)
1412   /* Entries shown left and right from the selected entry */
1413   $max_entries= 10;
1415   /* Initialize and take care that max_entries is even */
1416   $output="";
1417   if ($max_entries & 1){
1418     $max_entries++;
1419   }
1421   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1422     $range= $_POST[$post_var];
1423   }
1425   /* Prevent output to start or end out of range */
1426   if ($start < 0 ){
1427     $start= 0 ;
1428   }
1429   if ($start >= $dcnt){
1430     $start= $range * (int)(($dcnt / $range) + 0.5);
1431   }
1433   $numpages= (($dcnt / $range));
1434   if(((int)($numpages))!=($numpages)){
1435     $numpages = (int)$numpages + 1;
1436   }
1437   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1438     return ("");
1439   }
1440   $ppage= (int)(($start / $range) + 0.5);
1443   /* Align selected page to +/- max_entries/2 */
1444   $begin= $ppage - $max_entries/2;
1445   $end= $ppage + $max_entries/2;
1447   /* Adjust begin/end, so that the selected value is somewhere in
1448      the middle and the size is max_entries if possible */
1449   if ($begin < 0){
1450     $end-= $begin + 1;
1451     $begin= 0;
1452   }
1453   if ($end > $numpages) {
1454     $end= $numpages;
1455   }
1456   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1457     $begin= $end - $max_entries;
1458   }
1460   if($post_var){
1461     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1462       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1463   }else{
1464     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1465   }
1467   /* Draw decrement */
1468   if ($start > 0 ) {
1469     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1470       (($start-$range))."\">".
1471       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1472   }
1474   /* Draw pages */
1475   for ($i= $begin; $i < $end; $i++) {
1476     if ($ppage == $i){
1477       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1478         validate($_GET['plug'])."&amp;start=".
1479         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1480     } else {
1481       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1482         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1483     }
1484   }
1486   /* Draw increment */
1487   if($start < ($dcnt-$range)) {
1488     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1489       (($start+($range)))."\">".
1490       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1491   }
1493   if(($post_var)&&($numpages)){
1494     $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()'>";
1495     foreach(array(20,50,100,200,"all") as $num){
1496       if($num == "all"){
1497         $var = 10000;
1498       }else{
1499         $var = $num;
1500       }
1501       if($var == $range){
1502         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1503       }else{  
1504         $output.="\n<option value='".$var."'>".$num."</option>";
1505       }
1506     }
1507     $output.=  "</select></td></tr></table></div>";
1508   }else{
1509     $output.= "</div>";
1510   }
1512   return($output);
1516 function apply_filter()
1518   $apply= "";
1520   $apply= ''.
1521     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1522     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1524   return ($apply);
1528 function back_to_main()
1530   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1531     msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1533   return ($string);
1537 function normalize_netmask($netmask)
1539   /* Check for notation of netmask */
1540   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1541     $num= (int)($netmask);
1542     $netmask= "";
1544     for ($byte= 0; $byte<4; $byte++){
1545       $result=0;
1547       for ($i= 7; $i>=0; $i--){
1548         if ($num-- > 0){
1549           $result+= pow(2,$i);
1550         }
1551       }
1553       $netmask.= $result.".";
1554     }
1556     return (preg_replace('/\.$/', '', $netmask));
1557   }
1559   return ($netmask);
1563 function netmask_to_bits($netmask)
1565   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1566   $res= 0;
1568   for ($n= 0; $n<4; $n++){
1569     $start= 255;
1570     $name= "nm$n";
1572     for ($i= 0; $i<8; $i++){
1573       if ($start == (int)($$name)){
1574         $res+= 8 - $i;
1575         break;
1576       }
1577       $start-= pow(2,$i);
1578     }
1579   }
1581   return ($res);
1585 function recurse($rule, $variables)
1587   $result= array();
1589   if (!count($variables)){
1590     return array($rule);
1591   }
1593   reset($variables);
1594   $key= key($variables);
1595   $val= current($variables);
1596   unset ($variables[$key]);
1598   foreach($val as $possibility){
1599     $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
1600     $result= array_merge($result, recurse($nrule, $variables));
1601   }
1603   return ($result);
1607 function expand_id($rule, $attributes)
1609   /* Check for id rule */
1610   if(preg_match('/^id(:|#)\d+$/',$rule)){
1611     return (array("\{$rule}"));
1612   }
1614   /* Check for clean attribute */
1615   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1616     $rule= preg_replace('/^%/', '', $rule);
1617     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
1618     return (array($val));
1619   }
1621   /* Check for attribute with parameters */
1622   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1623     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1624     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1625     $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
1626     $start= preg_replace ('/-.*$/', '', $param);
1627     $stop = preg_replace ('/^[^-]+-/', '', $param);
1629     /* Assemble results */
1630     $result= array();
1631     for ($i= $start; $i<= $stop; $i++){
1632       $result[]= substr($val, 0, $i);
1633     }
1634     return ($result);
1635   }
1637   echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
1638   return (array($rule));
1642 function gen_uids($rule, $attributes)
1644   global $config;
1646   /* Search for keys and fill the variables array with all 
1647      possible values for that key. */
1648   $part= "";
1649   $trigger= false;
1650   $stripped= "";
1651   $variables= array();
1653   for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
1655     if ($rule[$pos] == "{" ){
1656       $trigger= true;
1657       $part= "";
1658       continue;
1659     }
1661     if ($rule[$pos] == "}" ){
1662       $variables[$pos]= expand_id($part, $attributes);
1663       $stripped.= "{".$pos."}";
1664       $trigger= false;
1665       continue;
1666     }
1668     if ($trigger){
1669       $part.= $rule[$pos];
1670     } else {
1671       $stripped.= $rule[$pos];
1672     }
1673   }
1675   /* Recurse through all possible combinations */
1676   $proposed= recurse($stripped, $variables);
1678   /* Get list of used ID's */
1679   $used= array();
1680   $ldap= $config->get_ldap_link();
1681   $ldap->cd($config->current['BASE']);
1682   $ldap->search('(uid=*)');
1684   while($attrs= $ldap->fetch()){
1685     $used[]= $attrs['uid'][0];
1686   }
1688   /* Remove used uids and watch out for id tags */
1689   $ret= array();
1690   foreach($proposed as $uid){
1692     /* Check for id tag and modify uid if needed */
1693     if(preg_match('/\{id:\d+}/',$uid)){
1694       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1696       for ($i= 0, $p= pow(10,$size); $i < $p; $i++){
1697         $number= sprintf("%0".$size."d", $i);
1698         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1699         if (!in_array($res, $used)){
1700           $uid= $res;
1701           break;
1702         }
1703       }
1704     }
1706     if(preg_match('/\{id#\d+}/',$uid)){
1707       $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1709       while (true){
1710         mt_srand((double) microtime()*1000000);
1711         $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1712         $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1713         if (!in_array($res, $used)){
1714           $uid= $res;
1715           break;
1716         }
1717       }
1718     }
1720     /* Don't assign used ones */
1721     if (!in_array($uid, $used)){
1722       $ret[]= $uid;
1723     }
1724   }
1726   return(array_unique($ret));
1730 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1731    Need to convert... */
1732 function to_byte($value) {
1733   $value= strtolower(trim($value));
1735   if(!is_numeric(substr($value, -1))) {
1737     switch(substr($value, -1)) {
1738       case 'g':
1739         $mult= 1073741824;
1740         break;
1741       case 'm':
1742         $mult= 1048576;
1743         break;
1744       case 'k':
1745         $mult= 1024;
1746         break;
1747     }
1749     return ($mult * (int)substr($value, 0, -1));
1750   } else {
1751     return $value;
1752   }
1756 function in_array_ics($value, $items)
1758         return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
1762 function generate_alphabet($count= 10)
1764   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1765   $alphabet= "";
1766   $c= 0;
1768   /* Fill cells with charaters */
1769   for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
1770     if ($c == 0){
1771       $alphabet.= "<tr>";
1772     }
1774     $ch = mb_substr($characters, $i, 1, "UTF8");
1775     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1776       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1778     if ($c++ == $count){
1779       $alphabet.= "</tr>";
1780       $c= 0;
1781     }
1782   }
1784   /* Fill remaining cells */
1785   while ($c++ <= $count){
1786     $alphabet.= "<td>&nbsp;</td>";
1787   }
1789   return ($alphabet);
1793 function validate($string)
1795   return (strip_tags(preg_replace('/\0/', '', $string)));
1799 function get_gosa_version()
1801   global $svn_revision, $svn_path;
1803   /* Extract informations */
1804   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1806   /* Release or development? */
1807   if (preg_match('%/gosa/trunk/%', $svn_path)){
1808     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1809   } else {
1810     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1811     return (sprintf(_("GOsa $release"), $revision));
1812   }
1816 function rmdirRecursive($path, $followLinks=false) {
1817   $dir= opendir($path);
1818   while($entry= readdir($dir)) {
1819     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1820       unlink($path."/".$entry);
1821     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1822       rmdirRecursive($path."/".$entry);
1823     }
1824   }
1825   closedir($dir);
1826   return rmdir($path);
1830 function scan_directory($path,$sort_desc=false)
1832   $ret = false;
1834   /* is this a dir ? */
1835   if(is_dir($path)) {
1837     /* is this path a readable one */
1838     if(is_readable($path)){
1840       /* Get contents and write it into an array */   
1841       $ret = array();    
1843       $dir = opendir($path);
1845       /* Is this a correct result ?*/
1846       if($dir){
1847         while($fp = readdir($dir))
1848           $ret[]= $fp;
1849       }
1850     }
1851   }
1852   /* Sort array ascending , like scandir */
1853   sort($ret);
1855   /* Sort descending if parameter is sort_desc is set */
1856   if($sort_desc) {
1857     $ret = array_reverse($ret);
1858   }
1860   return($ret);
1864 function clean_smarty_compile_dir($directory)
1866   global $svn_revision;
1868   if(is_dir($directory) && is_readable($directory)) {
1869     // Set revision filename to REVISION
1870     $revision_file= $directory."/REVISION";
1872     /* Is there a stamp containing the current revision? */
1873     if(!file_exists($revision_file)) {
1874       // create revision file
1875       create_revision($revision_file, $svn_revision);
1876     } else {
1877       # check for "$config->...['CONFIG']/revision" and the
1878       # contents should match the revision number
1879       if(!compare_revision($revision_file, $svn_revision)){
1880         // If revision differs, clean compile directory
1881         foreach(scan_directory($directory) as $file) {
1882           if(($file==".")||($file=="..")) continue;
1883           if( is_file($directory."/".$file) &&
1884               is_writable($directory."/".$file)) {
1885             // delete file
1886             if(!unlink($directory."/".$file)) {
1887               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1888               // This should never be reached
1889             }
1890           } elseif(is_dir($directory."/".$file) &&
1891               is_writable($directory."/".$file)) {
1892             // Just recursively delete it
1893             rmdirRecursive($directory."/".$file);
1894           }
1895         }
1896         // We should now create a fresh revision file
1897         clean_smarty_compile_dir($directory);
1898       } else {
1899         // Revision matches, nothing to do
1900       }
1901     }
1902   } else {
1903     // Smarty compile dir is not accessible
1904     // (Smarty will warn about this)
1905   }
1909 function create_revision($revision_file, $revision)
1911   $result= false;
1913   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1914     if($fh= fopen($revision_file, "w")) {
1915       if(fwrite($fh, $revision)) {
1916         $result= true;
1917       }
1918     }
1919     fclose($fh);
1920   } else {
1921     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1922   }
1924   return $result;
1928 function compare_revision($revision_file, $revision)
1930   // false means revision differs
1931   $result= false;
1933   if(file_exists($revision_file) && is_readable($revision_file)) {
1934     // Open file
1935     if($fh= fopen($revision_file, "r")) {
1936       // Compare File contents with current revision
1937       if($revision == fread($fh, filesize($revision_file))) {
1938         $result= true;
1939       }
1940     } else {
1941       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1942     }
1943     // Close file
1944     fclose($fh);
1945   }
1947   return $result;
1951 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1953   $str = ""; // Our return value will be saved in this var
1955   $color  = dechex($percentage+150);
1956   $color2 = dechex(150 - $percentage);
1957   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1959   $progress = (int)(($percentage /100)*$width);
1961   /* If theres a better solution for this, use it... */
1962   $str = "\n   <div style=\" width:".($width)."px; ";
1963   $str.= "\n       height:".($height)."px; ";
1964   $str.= "\n       background-color:#000000; ";
1965   $str.= "\n       padding:1px;\" > ";
1967   $str.= "\n     <div style=\" width:".($width)."px; ";
1968   $str.= "\n         background-color:#$bgcolor; ";
1969   $str.= "\n         height:".($height)."px;\" > ";
1971   if(($height >10)&&($showvalue)){
1972     $str.= "\n   <font style=\"font-size:".($height-2)."px; ";
1973     $str.= "\n     color:#FF0000; align:middle; ";
1974     $str.= "\n     padding-left:".((int)(($width*0.4)))."px; \"> ";
1975     $str.= "\n     <b>".$percentage."%</b> ";
1976     $str.= "\n   </font> ";
1977   }
1979   $str.= "\n       <div style=\" width:".$progress."px; ";
1980   $str.= "\n         height:".$height."px; ";
1981   $str.= "\n         background-color:#".$color2.$color2.$color."; \" >";
1982   $str.= "\n       </div>";
1983   $str.= "\n     </div>";
1984   $str.= "\n   </div>";
1986   return($str);
1990 function array_key_ics($ikey, $items)
1992   $tmp= array_change_key_case($itmes, CASE_LOWER);
1993   $ikey= strtolower($ikey);
1994   if (isset($tmp[$ikey])){
1995     return($tmp[$ikey]);
1996   }
1998   return ('');
2002 function array_differs($src, $dst)
2004   /* If the count is differing, the arrays differ */
2005   if (count ($src) != count ($dst)){
2006     return (TRUE);
2007   }
2009   return (count(array_diff($src, $dst)) == 0);
2013 function saveFilter($a_filter, $values)
2015   if (isset($_POST['regexit'])){
2016     $a_filter["regex"]= $_POST['regexit'];
2018     foreach($values as $type){
2019       if (isset($_POST[$type])) {
2020         $a_filter[$type]= "checked";
2021       } else {
2022         $a_filter[$type]= "";
2023       }
2024     }
2025   }
2027   /* React on alphabet links if needed */
2028   if (isset($_GET['search'])){
2029     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2030     if ($s == "**"){
2031       $s= "*";
2032     }
2033     $a_filter['regex']= $s;
2034   }
2036   return ($a_filter);
2040 /* Escape all LDAP filter relevant characters */
2041 function normalizeLdap($input)
2043   return (addcslashes($input, '()|'));
2047 /* Resturns the difference between to microtime() results in float  */
2048 function get_MicroTimeDiff($start , $stop)
2050   $a = split("\ ",$start);
2051   $b = split("\ ",$stop);
2053   $secs = $b[1] - $a[1];
2054   $msecs= $b[0] - $a[0]; 
2056   $ret = (float) ($secs+ $msecs);
2057   return($ret);
2061 function get_base_dir()
2063   global $BASE_DIR;
2065   return $BASE_DIR;
2069 function obj_is_readable($dn, $object, $attribute)
2071   global $ui;
2073   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2077 function obj_is_writable($dn, $object, $attribute)
2079   global $ui;
2081   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2085 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2087   /* Initialize variables */
2088   $ret  = array("count" => 0);  // Set count to 0
2089   $next = true;                 // if false, then skip next loops and return
2090   $cnt  = 0;                    // Current number of loops
2091   $max  = 100;                  // Just for security, prevent looops
2092   $ldap = NULL;                 // To check if created result a valid
2093   $keep = "";                   // save last failed parse string
2095   /* Check each parsed dn in ldap ? */
2096   if($config!==NULL && $verify_in_ldap){
2097     $ldap = $config->get_ldap_link();
2098   }
2100   /* Lets start */
2101   $called = false;
2102   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2104     $cnt ++;
2105     if(!preg_match("/,/",$dn)){
2106       $next = false;
2107     }
2108     $object = preg_replace("/[,].*$/","",$dn);
2109     $dn     = preg_replace("/^[^,]+,/","",$dn);
2111     $called = true;
2113     /* Check if current dn is valid */
2114     if($ldap!==NULL){
2115       $ldap->cd($dn);
2116       $ldap->cat($dn,array("dn"));
2117       if($ldap->count()){
2118         $ret[]  = $keep.$object;
2119         $keep   = "";
2120       }else{
2121         $keep  .= $object.",";
2122       }
2123     }else{
2124       $ret[]  = $keep.$object;
2125       $keep   = "";
2126     }
2127   }
2129   /* No dn was posted */
2130   if($cnt == 0 && !empty($dn)){
2131     $ret[] = $dn;
2132   }
2134   /* Append the rest */
2135   $test = $keep.$dn;
2136   if($called && !empty($test)){
2137     $ret[] = $keep.$dn;
2138   }
2139   $ret['count'] = count($ret) - 1;
2141   return($ret);
2145 function get_base_from_hook($dn, $attrib)
2147   global $config;
2149   if ($config->get_cfg_value("baseIdHook") != ""){
2150     
2151     /* Call hook script - if present */
2152     $command= $config->get_cfg_value("baseIdHook");
2154     if ($command != ""){
2155       $command.= " '".LDAP::fix($dn)."' $attrib";
2156       if (check_command($command)){
2157         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2158         exec($command, $output);
2159         if (preg_match("/^[0-9]+$/", $output[0])){
2160           return ($output[0]);
2161         } else {
2162           msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2163           return ($config->get_cfg_value("uidNumberBase"));
2164         }
2165       } else {
2166         msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2167         return ($config->get_cfg_value("uidNumberBase"));
2168       }
2170     } else {
2172       msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2173       return ($config->get_cfg_value("uidNumberBase"));
2175     }
2176   }
2180 function check_schema_version($class, $version)
2182   return preg_match("/\(v$version\)/", $class['DESC']);
2186 function check_schema($cfg,$rfc2307bis = FALSE)
2188   $messages= array();
2190   /* Get objectclasses */
2191   $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2192   $objectclasses = $ldap->get_objectclasses();
2193   if(count($objectclasses) == 0){
2194     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2195   }
2197   /* This is the default block used for each entry.
2198    *  to avoid unset indexes.
2199    */
2200   $def_check = array("REQUIRED_VERSION" => "0",
2201       "SCHEMA_FILES"     => array(),
2202       "CLASSES_REQUIRED" => array(),
2203       "STATUS"           => FALSE,
2204       "IS_MUST_HAVE"     => FALSE,
2205       "MSG"              => "",
2206       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2208   /* The gosa base schema */
2209   $checks['gosaObject'] = $def_check;
2210   $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
2211   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2212   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2213   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2215   /* GOsa Account class */
2216   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
2217   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2218   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2219   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2220   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2222   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2223   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
2224   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2225   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2226   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2227   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2229   /* Some other checks */
2230   foreach(array(
2231         "gosaCacheEntry"        => array("version" => "2.4"),
2232         "gosaDepartment"        => array("version" => "2.4"),
2233         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2234         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2235         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2236         "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
2237         "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2238         "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2239         "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2240         "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
2241         "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2242         "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
2243         "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
2244         "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2245         "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2246         "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2247         "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
2248         "goLdapServer"          => array("version" => "2.4"),
2249         "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
2250         "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2251         "goKrbServer"           => array("version" => "2.4"),
2252         "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2253         ) as $name => $values){
2255           $checks[$name] = $def_check;
2256           if(isset($values['version'])){
2257             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2258           }
2259           if(isset($values['file'])){
2260             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2261           }
2262           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2263         }
2264   foreach($checks as $name => $value){
2265     foreach($value['CLASSES_REQUIRED'] as $class){
2267       if(!isset($objectclasses[$name])){
2268         $checks[$name]['STATUS'] = FALSE;
2269         if($value['IS_MUST_HAVE']){
2270           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2271         }else{
2272           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2273         }
2274       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2275         $checks[$name]['STATUS'] = FALSE;
2277         if($value['IS_MUST_HAVE']){
2278           $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2279         }else{
2280           $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2281         }
2282       }else{
2283         $checks[$name]['STATUS'] = TRUE;
2284         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2285       }
2286     }
2287   }
2289   $tmp = $objectclasses;
2291   /* The gosa base schema */
2292   $checks['posixGroup'] = $def_check;
2293   $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
2294   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2295   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2296   $checks['posixGroup']['STATUS']           = TRUE;
2297   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2298   $checks['posixGroup']['MSG']              = "";
2299   $checks['posixGroup']['INFO']             = "";
2301   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2302   if(isset($tmp['posixGroup'])){
2304     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2305       $checks['posixGroup']['STATUS']           = FALSE;
2306       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2307       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2308     }
2309     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2310       $checks['posixGroup']['STATUS']           = FALSE;
2311       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2312       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2313     }
2314   }
2316   return($checks);
2320 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2322   $tmp = array(
2323         "de_DE" => "German",
2324         "fr_FR" => "French",
2325         "it_IT" => "Italian",
2326         "es_ES" => "Spanish",
2327         "en_US" => "English",
2328         "nl_NL" => "Dutch",
2329         "pl_PL" => "Polish",
2330         #"sv_SE" => "Swedish",
2331         "zh_CN" => "Chinese",
2332         "vi_VN" => "Vietnamese",
2333         "ru_RU" => "Russian");
2334   
2335   $tmp2= array(
2336         "de_DE" => _("German"),
2337         "fr_FR" => _("French"),
2338         "it_IT" => _("Italian"),
2339         "es_ES" => _("Spanish"),
2340         "en_US" => _("English"),
2341         "nl_NL" => _("Dutch"),
2342         "pl_PL" => _("Polish"),
2343         #"sv_SE" => _("Swedish"),
2344         "zh_CN" => _("Chinese"),
2345         "vi_VN" => _("Vietnamese"),
2346         "ru_RU" => _("Russian"));
2348   $ret = array();
2349   if($languages_in_own_language){
2351     $old_lang = setlocale(LC_ALL, 0);
2353     /* If the locale wasn't correclty set before, there may be an incorrect
2354         locale returned. Something like this: 
2355           C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2356         Extract the locale name from this string and use it to restore old locale.
2357      */
2358     if(preg_match("/LC_CTYPE/",$old_lang)){
2359       $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2360     }
2361     
2362     foreach($tmp as $key => $name){
2363       $lang = $key.".UTF-8";
2364       setlocale(LC_ALL, $lang);
2365       if($strip_region_tag){
2366         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2367       }else{
2368         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2369       }
2370     }
2371     setlocale(LC_ALL, $old_lang);
2372   }else{
2373     foreach($tmp as $key => $name){
2374       if($strip_region_tag){
2375         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2376       }else{
2377         $ret[$key] = _($name);
2378       }
2379     }
2380   }
2381   return($ret);
2385 /* Returns contents of the given POST variable and check magic quotes settings */
2386 function get_post($name)
2388   if(!isset($_POST[$name])){
2389     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2390     return(FALSE);
2391   }
2392   if(get_magic_quotes_gpc()){
2393     return(stripcslashes($_POST[$name]));
2394   }else{
2395     return($_POST[$name]);
2396   }
2400 /* Return class name in correct case */
2401 function get_correct_class_name($cls)
2403   global $class_mapping;
2404   if(isset($class_mapping) && is_array($class_mapping)){
2405     foreach($class_mapping as $class => $file){
2406       if(preg_match("/^".$cls."$/i",$class)){
2407         return($class);
2408       }
2409     }
2410   }
2411   return(FALSE);
2415 // change_password, changes the Password, of the given dn
2416 function change_password ($dn, $password, $mode=0, $hash= "")
2418   global $config;
2419   $newpass= "";
2421   /* Convert to lower. Methods are lowercase */
2422   $hash= strtolower($hash);
2424   // Get all available encryption Methods
2426   // NON STATIC CALL :)
2427   $methods = new passwordMethod(session::get('config'));
2428   $available = $methods->get_available_methods();
2430   // read current password entry for $dn, to detect the encryption Method
2431   $ldap       = $config->get_ldap_link();
2432   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2433   $attrs      = $ldap->fetch ();
2435   // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
2436   if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
2437     $deactivated = TRUE;
2438   }else{
2439     $deactivated = FALSE;
2440   }
2442   /* Is ensure that clear passwords will stay clear */
2443   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2444     $hash = "clear";
2445   }
2447   // Detect the encryption Method
2448   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2450     /* Check for supported algorithm */
2451     mt_srand((double) microtime()*1000000);
2453     /* Extract used hash */
2454     if ($hash == ""){
2455       $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2456     } else {
2457       $test = new $available[$hash]($config,$dn);
2458       $test->set_hash($hash);
2459     }
2461   } else {
2462     // User MD5 by default
2463     $hash= "md5";
2464     $test = new  $available['md5']($config);
2465   }
2467   /* Feed password backends with information */
2468   $test->dn= $dn;
2469   $test->attrs= $attrs;
2470   $newpass= $test->generate_hash($password);
2472   // Update shadow timestamp?
2473   if (isset($attrs["shadowLastChange"][0])){
2474     $shadow= (int)(date("U") / 86400);
2475   } else {
2476     $shadow= 0;
2477   }
2479   // Write back modified entry
2480   $ldap->cd($dn);
2481   $attrs= array();
2483   // Not for groups
2484   if ($mode == 0){
2486     if ($shadow != 0){
2487       $attrs['shadowLastChange']= $shadow;
2488     }
2490     // Create SMB Password
2491     $attrs= generate_smb_nt_hash($password);
2492   }
2494  /* Read ! if user was deactivated */
2495   if($deactivated){
2496     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
2497   }
2499   $attrs['userPassword']= array();
2500   $attrs['userPassword']= $newpass;
2502   $ldap->modify($attrs);
2504   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2506   if (!$ldap->success()) {
2507     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2508   } else {
2510     /* Run backend method for change/create */
2511     if(!$test->set_password($password)){
2512       return(FALSE);
2513     }
2515     /* Find postmodify entries for this class */
2516     $command= $config->search("password", "POSTMODIFY",array('menu'));
2518     if ($command != ""){
2519       /* Walk through attribute list */
2520       $command= preg_replace("/%userPassword/", $password, $command);
2521       $command= preg_replace("/%dn/", $dn, $command);
2523       if (check_command($command)){
2524         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2525         exec($command);
2526       } else {
2527         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2528         msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2529       }
2530     }
2531   }
2532   return(TRUE);
2536 // Return something like array['sambaLMPassword']= "lalla..."
2537 function generate_smb_nt_hash($password)
2539   global $config;
2541   # Try to use gosa-si?
2542   if ($config->get_cfg_value("gosaSupportURI") != ""){
2543         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2544     if (isset($res['XML']['HASH'])){
2545         $hash= $res['XML']['HASH'];
2546     } else {
2547       $hash= "";
2548     }
2549   } else {
2550           $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
2551           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2553           exec($tmp, $ar);
2554           flush();
2555           reset($ar);
2556           $hash= current($ar);
2557   }
2559   if ($hash == "") {
2560           msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2561           return ("");
2562   }
2564   list($lm,$nt)= split (":", trim($hash));
2566   if ($config->get_cfg_value("sambaversion") == 3) {
2567           $attrs['sambaLMPassword']= $lm;
2568           $attrs['sambaNTPassword']= $nt;
2569           $attrs['sambaPwdLastSet']= date('U');
2570           $attrs['sambaBadPasswordCount']= "0";
2571           $attrs['sambaBadPasswordTime']= "0";
2572   } else {
2573           $attrs['lmPassword']= $lm;
2574           $attrs['ntPassword']= $nt;
2575           $attrs['pwdLastSet']= date('U');
2576   }
2577   return($attrs);
2581 function getEntryCSN($dn)
2583   global $config;
2584   if(empty($dn) || !is_object($config)){
2585     return("");
2586   }
2588   /* Get attribute that we should use as serial number */
2589   $attr= $config->get_cfg_value("modificationDetectionAttribute");
2590   if($attr != ""){
2591     $ldap = $config->get_ldap_link();
2592     $ldap->cat($dn,array($attr));
2593     $csn = $ldap->fetch();
2594     if(isset($csn[$attr][0])){
2595       return($csn[$attr][0]);
2596     }
2597   }
2598   return("");
2602 /* Add a given objectClass to an attrs entry */
2603 function add_objectClass($classes, &$attrs)
2605   if (is_array($classes)){
2606     $list= $classes;
2607   } else {
2608     $list= array($classes);
2609   }
2611   foreach ($list as $class){
2612     $attrs['objectClass'][]= $class;
2613   }
2617 /* Removes a given objectClass from the attrs entry */
2618 function remove_objectClass($classes, &$attrs)
2620   if (isset($attrs['objectClass'])){
2621     /* Array? */
2622     if (is_array($classes)){
2623       $list= $classes;
2624     } else {
2625       $list= array($classes);
2626     }
2628     $tmp= array();
2629     foreach ($attrs['objectClass'] as $oc) {
2630       foreach ($list as $class){
2631         if (strtolower($oc) != strtolower($class)){
2632           $tmp[]= $oc;
2633         }
2634       }
2635     }
2636     $attrs['objectClass']= $tmp;
2637   }
2640 /*! \brief  Initialize a file download with given content, name and data type. 
2641  *  @param  data  String The content to send.
2642  *  @param  name  String The name of the file.
2643  *  @param  type  String The content identifier, default value is "application/octet-stream";
2644  */
2645 function send_binary_content($data,$name,$type = "application/octet-stream")
2647   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2648   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2649   header("Cache-Control: no-cache");
2650   header("Pragma: no-cache");
2651   header("Cache-Control: post-check=0, pre-check=0");
2652   header("Content-type: ".$type."");
2654   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2656   /* Strip name if it is a complete path */
2657   if (preg_match ("/\//", $name)) {
2658         $name= basename($name);
2659   }
2660   
2661   /* force download dialog */
2662   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2663     header('Content-Disposition: filename="'.$name.'"');
2664   } else {
2665     header('Content-Disposition: attachment; filename="'.$name.'"');
2666   }
2668   echo $data;
2669   exit();
2673 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2675   if(is_string($str)){
2676     return(htmlentities($str,$type,$charset));
2677   }elseif(is_array($str)){
2678     foreach($str as $name => $value){
2679       $str[$name] = reverse_html_entities($value,$type,$charset);
2680     }
2681   }
2682   return($str);
2686 /*! \brief Encode special string characters so we can use the string in \
2687            HTML output, without breaking quotes.
2688     @param  The String we want to encode.
2689     @return The encoded String
2690  */
2691 function xmlentities($str)
2692
2693   if(is_string($str)){
2695     static $asc2uni= array();
2696     if (!count($asc2uni)){
2697       for($i=128;$i<256;$i++){
2698     #    $asc2uni[chr($i)] = "&#x".dechex($i).";";
2699       }
2700     }
2702     $str = str_replace("&", "&amp;", $str);
2703     $str = str_replace("<", "&lt;", $str);
2704     $str = str_replace(">", "&gt;", $str);
2705     $str = str_replace("'", "&apos;", $str);
2706     $str = str_replace("\"", "&quot;", $str);
2707     $str = str_replace("\r", "", $str);
2708     $str = strtr($str,$asc2uni);
2709     return $str;
2710   }elseif(is_array($str)){
2711     foreach($str as $name => $value){
2712       $str[$name] = xmlentities($value);
2713     }
2714   }
2715   return($str);
2719 /*! \brief  Updates all accessTo attributes from a given value to a new one.
2720             For example if a host is renamed.
2721     @param  String  $from The source accessTo name.
2722     @param  String  $to   The destination accessTo name.
2723 */
2724 function update_accessTo($from,$to)
2726   global $config;
2727   $ldap = $config->get_ldap_link();
2728   $ldap->cd($config->current['BASE']);
2729   $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2730   while($attrs = $ldap->fetch()){
2731     $new_attrs = array("accessTo" => array());
2732     $dn = $attrs['dn'];
2733     for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2734       $new_attrs['objectClass'][] =  $attrs['objectClass'][$i];
2735     }
2736     for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2737       if($attrs['accessTo'][$i] == $from){
2738         if(!empty($to)){
2739           $new_attrs['accessTo'][] =  $to;
2740         }
2741       }else{
2742         $new_attrs['accessTo'][] =  $attrs['accessTo'][$i]; 
2743       }
2744     }
2745     $ldap->cd($dn);
2746     $ldap->modify($new_attrs);
2747     if (!$ldap->success()){
2748       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2749     }
2750     new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2751   }
2755 function get_random_char () {
2756      $randno = rand (0, 63);
2757      if ($randno < 12) {
2758          return (chr ($randno + 46)); // Digits, '/' and '.'
2759      } else if ($randno < 38) {
2760          return (chr ($randno + 53)); // Uppercase
2761      } else {
2762          return (chr ($randno + 59)); // Lowercase
2763      }
2767 function cred_encrypt($input, $password) {
2769   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2770   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2772   return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2776 function cred_decrypt($input,$password) {
2777   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2778   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2780   return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2784 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2785 ?>