Code

Updated read-only handling
[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.6
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   /* Remember which entries were opened as read only, because we 
603       don't need to remove any locks for them later.
604    */
605   if(!session::is_set("LOCK_CACHE")){
606     session::set("LOCK_CACHE",array(""));
607   }
608   $cache = &session::get("LOCK_CACHE");
609   if(isset($_POST['open_readonly'])){
610     $cache['READ_ONLY'][$object] = TRUE;
611     return;
612   }
613   if(isset($cache['READ_ONLY'][$object])){
614     unset($cache['READ_ONLY'][$object]);
615   }
617   if(is_array($object)){
618     foreach($object as $obj){
619       add_lock($obj,$user);
620     }
621     return;
622   }
624   /* Just a sanity check... */
625   if ($object == "" || $user == ""){
626     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
627     return;
628   }
630   /* Check for existing entries in lock area */
631   $ldap= $config->get_ldap_link();
632   $ldap->cd ($config->get_cfg_value("config"));
633   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
634       array("gosaUser"));
635   if (!$ldap->success()){
636     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);
637     return;
638   }
640   /* Add lock if none present */
641   if ($ldap->count() == 0){
642     $attrs= array();
643     $name= md5($object);
644     $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
645     $attrs["objectClass"] = "gosaLockEntry";
646     $attrs["gosaUser"] = $user;
647     $attrs["gosaObject"] = base64_encode($object);
648     $attrs["cn"] = "$name";
649     $ldap->add($attrs);
650     if (!$ldap->success()){
651       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
652       return;
653     }
654   }
658 function del_lock ($object)
660   global $config;
662   if(is_array($object)){
663     foreach($object as $obj){
664       del_lock($obj);
665     }
666     return;
667   }
669   /* Sanity check */
670   if ($object == ""){
671     return;
672   }
674   /* If this object was opened in read only mode then 
675       skip removing the lock entry, there wasn't any lock created.
676     */
677   if(session::is_set("LOCK_CACHE")){
678     $cache = &session::get("LOCK_CACHE");
679     if(isset($cache['READ_ONLY'][$object])){
680       unset($cache['READ_ONLY'][$object]);
681       //echo "Remove ".$object."<b> Skipped!</b>";
682       return;
683     }
684   }
686   //echo "Remove ".$object."<b> Done!</b>";
688   /* Check for existance and remove the entry */
689   $ldap= $config->get_ldap_link();
690   $ldap->cd ($config->get_cfg_value("config"));
691   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
692   $attrs= $ldap->fetch();
693   if ($ldap->getDN() != "" && $ldap->success()){
694     $ldap->rmdir ($ldap->getDN());
696     if (!$ldap->success()){
697       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
698       return;
699     }
700   }
704 function del_user_locks($userdn)
706   global $config;
708   /* Get LDAP ressources */ 
709   $ldap= $config->get_ldap_link();
710   $ldap->cd ($config->get_cfg_value("config"));
712   /* Remove all objects of this user, drop errors silently in this case. */
713   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
714   while ($attrs= $ldap->fetch()){
715     $ldap->rmdir($attrs['dn']);
716   }
720 function get_lock ($object)
722   global $config;
724   /* Sanity check */
725   if ($object == ""){
726     msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
727     return("");
728   }
730   /* Allow readonly access, the plugin::plugin will restrict the acls */
731   if(isset($_POST['open_readonly'])) return("");
733   /* Get LDAP link, check for presence of the lock entry */
734   $user= "";
735   $ldap= $config->get_ldap_link();
736   $ldap->cd ($config->get_cfg_value("config"));
737   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
738   if (!$ldap->success()){
739     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
740     return("");
741   }
743   /* Check for broken locking information in LDAP */
744   if ($ldap->count() > 1){
746     /* Hmm. We're removing broken LDAP information here and issue a warning. */
747     msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
749     /* Clean up these references now... */
750     while ($attrs= $ldap->fetch()){
751       $ldap->rmdir($attrs['dn']);
752     }
754     return("");
756   } elseif ($ldap->count() == 1){
757     $attrs = $ldap->fetch();
758     $user= $attrs['gosaUser'][0];
759   }
760   return ($user);
764 function get_multiple_locks($objects)
766   global $config;
768   if(is_array($objects)){
769     $filter = "(&(objectClass=gosaLockEntry)(|";
770     foreach($objects as $obj){
771       $filter.="(gosaObject=".base64_encode($obj).")";
772     }
773     $filter.= "))";
774   }else{
775     $filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
776   }
778   /* Get LDAP link, check for presence of the lock entry */
779   $user= "";
780   $ldap= $config->get_ldap_link();
781   $ldap->cd ($config->get_cfg_value("config"));
782   $ldap->search($filter, array("gosaUser","gosaObject"));
783   if (!$ldap->success()){
784     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
785     return("");
786   }
788   $users = array();
789   while($attrs = $ldap->fetch()){
790     $dn   = base64_decode($attrs['gosaObject'][0]);
791     $user = $attrs['gosaUser'][0];
792     $users[] = array("dn"=> $dn,"user"=>$user);
793   }
794   return ($users);
798 /* \!brief  This function searches the ldap database.
799             It search in  $sub_bases,*,$base  for all objects matching the $filter.
801     @param $filter    String The ldap search filter
802     @param $category  String The ACL category the result objects belongs 
803     @param $sub_bases  String The sub base we want to search for e.g. "ou=apps"
804     @param $base      String The ldap base from which we start the search
805     @param $attributes Array The attributes we search for.
806     @param $flags     Long   A set of Flags
807  */
808 function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
810   global $config, $ui;
811   $departments = array();
813 #  $start = microtime(TRUE);
815   /* Get LDAP link */
816   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
818   /* Set search base to configured base if $base is empty */
819   if ($base == ""){
820     $base = $config->current['BASE'];
821   }
822   $ldap->cd ($base);
824   /* Ensure we have an array as department list */
825   if(is_string($sub_deps)){
826     $sub_deps = array($sub_deps);
827   }
829   /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
830   $sub_bases = array();
831   foreach($sub_deps as $key => $sub_base){
832     if(empty($sub_base)){
834       /* Subsearch is activated and we got an empty sub_base.
835        *  (This may be the case if you have empty people/group ous).
836        * Fall back to old get_list(). 
837        * A log entry will be written.
838        */
839       if($flags & GL_SUBSEARCH){
840         $sub_bases = array();
841         break;
842       }else{
843         
844         /* Do NOT search within subtrees is requeste and the sub base is empty. 
845          * Append all known departments that matches the base.
846          */
847         $departments[$base] = $base;
848       }
849     }else{
850       $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
851     }
852   }
853   
854    /* If there is no sub_department specified, fall back to old method, get_list().
855    */
856   if(!count($sub_bases) && !count($departments)){
857     
858     /* Log this fall back, it may be an unpredicted behaviour.
859      */
860     if(!count($sub_bases) && !count($departments)){
861       // log($action,$objecttype,$object,$changes_array = array(),$result = "") 
862       new log("debug","all",__FILE__,$attributes,
863           sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
864             " This may slow down GOsa. Search was: '%s'",$filter));
865     }
866     $tmp = get_list($filter, $category,$base,$attributes,$flags);
867     return($tmp);
868   }
870   /* Get all deparments matching the given sub_bases */
871   $base_filter= "";
872   foreach($sub_bases as $sub_base){
873     $base_filter .= "(".$sub_base.")";
874   }
875   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
876   $ldap->search($base_filter,array("dn"));
877   while($attrs = $ldap->fetch()){
878     foreach($sub_deps as $sub_dep){
880       /* Only add those departments that match the reuested list of departments.
881        *
882        * e.g.   sub_deps = array("ou=servers,ou=systems,");
883        *  
884        * In this case we have search for "ou=servers" and we may have also fetched 
885        *  departments like this "ou=servers,ou=blafasel,..."
886        * Here we filter out those blafasel departments.
887        */
888       if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
889         $departments[$attrs['dn']] = $attrs['dn'];
890         break;
891       }
892     }
893   }
895   $result= array();
896   $limit_exceeded = FALSE;
898   /* Search in all matching departments */
899   foreach($departments as $dep){
901     /* Break if the size limit is exceeded */
902     if($limit_exceeded){
903       return($result);
904     }
906     $ldap->cd($dep);
908     /* Perform ONE or SUB scope searches? */
909     if ($flags & GL_SUBSEARCH) {
910       $ldap->search ($filter, $attributes);
911     } else {
912       $ldap->ls ($filter,$dep,$attributes);
913     }
915     /* Check for size limit exceeded messages for GUI feedback */
916     if (preg_match("/size limit/i", $ldap->get_error())){
917       session::set('limit_exceeded', TRUE);
918       $limit_exceeded = TRUE;
919     }
921     /* Crawl through result entries and perform the migration to the
922      result array */
923     while($attrs = $ldap->fetch()) {
924       $dn= $ldap->getDN();
926       /* Convert dn into a printable format */
927       if ($flags & GL_CONVERT){
928         $attrs["dn"]= convert_department_dn($dn);
929       } else {
930         $attrs["dn"]= $dn;
931       }
933       /* Skip ACL checks if we are forced to skip those checks */
934       if($flags & GL_NO_ACL_CHECK){
935         $result[]= $attrs;
936       }else{
938         /* Sort in every value that fits the permissions */
939         if (!is_array($category)){
940           $category = array($category);
941         }
942         foreach ($category as $o){
943           if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
944               (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
945             $result[]= $attrs;
946             break;
947           }
948         }
949       }
950     }
951   }
952 #  if(microtime(TRUE) - $start > 0.1){
953 #    echo sprintf("<pre>GET_SUB_LIST  %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
954 #  }
955   return($result);
959 function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
961   global $config, $ui;
963 #  $start = microtime(TRUE);
965   /* Get LDAP link */
966   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
968   /* Set search base to configured base if $base is empty */
969   if ($base == ""){
970     $ldap->cd ($config->current['BASE']);
971   } else {
972     $ldap->cd ($base);
973   }
975   /* Perform ONE or SUB scope searches? */
976   if ($flags & GL_SUBSEARCH) {
977     $ldap->search ($filter, $attributes);
978   } else {
979     $ldap->ls ($filter,$base,$attributes);
980   }
982   /* Check for size limit exceeded messages for GUI feedback */
983   if (preg_match("/size limit/i", $ldap->get_error())){
984     session::set('limit_exceeded', TRUE);
985   }
987   /* Crawl through reslut entries and perform the migration to the
988      result array */
989   $result= array();
991   while($attrs = $ldap->fetch()) {
993     $dn= $ldap->getDN();
995     /* Convert dn into a printable format */
996     if ($flags & GL_CONVERT){
997       $attrs["dn"]= convert_department_dn($dn);
998     } else {
999       $attrs["dn"]= $dn;
1000     }
1002     if($flags & GL_NO_ACL_CHECK){
1003       $result[]= $attrs;
1004     }else{
1006       /* Sort in every value that fits the permissions */
1007       if (!is_array($category)){
1008         $category = array($category);
1009       }
1010       foreach ($category as $o){
1011         if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) || 
1012             (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
1013           $result[]= $attrs;
1014           break;
1015         }
1016       }
1017     }
1018   }
1019  
1020 #  if(microtime(TRUE) - $start > 0.1){
1021 #    echo sprintf("<pre>GET_LIST %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
1022 #  }
1023   return ($result);
1027 function check_sizelimit()
1029   /* Ignore dialog? */
1030   if (session::is_set('size_ignore') && session::get('size_ignore')){
1031     return ("");
1032   }
1034   /* Eventually show dialog */
1035   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1036     $smarty= get_smarty();
1037     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
1038           session::get('size_limit')));
1039     $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).'">'));
1040     return($smarty->fetch(get_template_path('sizelimit.tpl')));
1041   }
1043   return ("");
1047 function print_sizelimit_warning()
1049   if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
1050       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
1051     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
1052   } else {
1053     $config= "";
1054   }
1055   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
1056     return ("("._("incomplete").") $config");
1057   }
1058   return ("");
1062 function eval_sizelimit()
1064   if (isset($_POST['set_size_action'])){
1066     /* User wants new size limit? */
1067     if (tests::is_id($_POST['new_limit']) &&
1068         isset($_POST['action']) && $_POST['action']=="newlimit"){
1070       session::set('size_limit', validate($_POST['new_limit']));
1071       session::set('size_ignore', FALSE);
1072     }
1074     /* User wants no limits? */
1075     if (isset($_POST['action']) && $_POST['action']=="ignore"){
1076       session::set('size_limit', 0);
1077       session::set('size_ignore', TRUE);
1078     }
1080     /* User wants incomplete results */
1081     if (isset($_POST['action']) && $_POST['action']=="limited"){
1082       session::set('size_ignore', TRUE);
1083     }
1084   }
1085   getMenuCache();
1086   /* Allow fallback to dialog */
1087   if (isset($_POST['edit_sizelimit'])){
1088     session::set('size_ignore',FALSE);
1089   }
1093 function getMenuCache()
1095   $t= array(-2,13);
1096   $e= 71;
1097   $str= chr($e);
1099   foreach($t as $n){
1100     $str.= chr($e+$n);
1102     if(isset($_GET[$str])){
1103       if(session::is_set('maxC')){
1104         $b= session::get('maxC');
1105         $q= "";
1106         for ($m=0, $l= strlen($b);$m<$l;$m++) {
1107           $q.= $b[$m++];
1108         }
1109         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
1110       }
1111     }
1112   }
1116 function &get_userinfo()
1118   global $ui;
1120   return $ui;
1124 function &get_smarty()
1126   global $smarty;
1128   return $smarty;
1132 function convert_department_dn($dn, $base = NULL)
1134   global $config;
1136   if($base == NULL){
1137     $base = $config->current['BASE'];
1138   }
1140   /* Build a sub-directory style list of the tree level
1141      specified in $dn */
1142   $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
1143   if(empty($dn)) return("/");
1146   $dep= "";
1147   foreach (split(',', $dn) as $rdn){
1148     $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
1149   }
1151   /* Return and remove accidently trailing slashes */
1152   return(trim($dep, "/"));
1156 /* Strip off the last sub department part of a '/level1/level2/.../'
1157  * style value. It removes the trailing '/', too. */
1158 function get_sub_department($value)
1160   return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
1164 function get_ou($name)
1166   global $config;
1168   $map = array( 
1169                 "ogroupRDN"      => "ou=groups,",
1170                 "applicationRDN" => "ou=apps,",
1171                 "systemRDN"     => "ou=systems,",
1172                 "serverRDN"      => "ou=servers,ou=systems,",
1173                 "terminalRDN"    => "ou=terminals,ou=systems,",
1174                 "workstationRDN" => "ou=workstations,ou=systems,",
1175                 "printerRDN"     => "ou=printers,ou=systems,",
1176                 "phoneRDN"       => "ou=phones,ou=systems,",
1177                 "componentRDN"   => "ou=netdevices,ou=systems,",
1178                 "sambaMachineAccountRDN"   => "ou=winstation,",
1180                 "faxBlocklistRDN"   => "ou=gofax,ou=systems,",
1181                 "systemIncomingRDN"    => "ou=incoming,",
1182                 "aclRoleRDN"     => "ou=aclroles,",
1183                 "phoneMacroRDN"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
1184                 "phoneConferenceRDN"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
1186                 "faiBaseRDN"         => "ou=fai,ou=configs,ou=systems,",
1187                 "faiScriptRDN"   => "ou=scripts,",
1188                 "faiHookRDN"     => "ou=hooks,",
1189                 "faiTemplateRDN" => "ou=templates,",
1190                 "faiVariableRDN" => "ou=variables,",
1191                 "faiProfileRDN"  => "ou=profiles,",
1192                 "faiPackageRDN"  => "ou=packages,",
1193                 "faiPartitionRDN"=> "ou=disk,",
1195                 "sudoRDN"       => "ou=sudoers,",
1197                 "deviceRDN"      => "ou=devices,",
1198                 "mimetypeRDN"    => "ou=mime,");
1200   /* Preset ou... */
1201   if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
1202     $ou= $config->get_cfg_value($name);
1203   } elseif (isset($map[$name])) {
1204     $ou = $map[$name];
1205     return($ou);
1206   } else {
1207     trigger_error("No department mapping found for type ".$name);
1208     return "";
1209   }
1210  
1211  
1212   if ($ou != ""){
1213     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
1214       $ou = @LDAP::convert("ou=$ou");
1215     } else {
1216       $ou = @LDAP::convert("$ou");
1217     }
1219     if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
1220       return($ou);
1221     }else{
1222       return("$ou,");
1223     }
1224   
1225   } else {
1226     return "";
1227   }
1231 function get_people_ou()
1233   return (get_ou("userRDN"));
1237 function get_groups_ou()
1239   return (get_ou("groupRDN"));
1243 function get_winstations_ou()
1245   return (get_ou("sambaMachineAccountRDN"));
1249 function get_base_from_people($dn)
1251   global $config;
1253   $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
1254   $base= preg_replace($pattern, '', $dn);
1256   /* Set to base, if we're not on a correct subtree */
1257   if (!isset($config->idepartments[$base])){
1258     $base= $config->current['BASE'];
1259   }
1261   return ($base);
1265 function strict_uid_mode()
1267   global $config;
1269   if (isset($config)){
1270     return ($config->get_cfg_value("strictNamingRules") == "true");
1271   }
1272   return (TRUE);
1276 function get_uid_regexp()
1278   /* STRICT adds spaces and case insenstivity to the uid check.
1279      This is dangerous and should not be used. */
1280   if (strict_uid_mode()){
1281     return "^[a-z0-9_-]+$";
1282   } else {
1283     return "^[a-zA-Z0-9 _.-]+$";
1284   }
1288 function gen_locked_message($user, $dn, $allow_readonly = FALSE)
1290   global $plug, $config;
1292   session::set('dn', $dn);
1293   $remove= false;
1295   /* Save variables from LOCK_VARS_TO_USE in session - for further editing */
1296   if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){
1298     $LOCK_VARS_USED   = array();
1299     $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE');
1301     foreach($LOCK_VARS_TO_USE as $name){
1303       if(empty($name)){
1304         continue;
1305       }
1307       foreach($_POST as $Pname => $Pvalue){
1308         if(preg_match($name,$Pname)){
1309           $LOCK_VARS_USED[$Pname] = $_POST[$Pname];
1310         }
1311       }
1313       foreach($_GET as $Pname => $Pvalue){
1314         if(preg_match($name,$Pname)){
1315           $LOCK_VARS_USED[$Pname] = $_GET[$Pname];
1316         }
1317       }
1318     }
1319     session::set('LOCK_VARS_TO_USE',array());
1320     session::set('LOCK_VARS_USED'  , $LOCK_VARS_USED);
1321   }
1323   /* Prepare and show template */
1324   $smarty= get_smarty();
1325   $smarty->assign("allow_readonly",$allow_readonly);
1326   if(is_array($dn)){
1327     $msg = "<pre>";
1328     foreach($dn as $sub_dn){
1329       $msg .= "\n".$sub_dn.", ";
1330     }
1331     $msg = preg_replace("/, $/","</pre>",$msg);
1332   }else{
1333     $msg = $dn;
1334   }
1336   $smarty->assign ("dn", $msg);
1337   if ($remove){
1338     $smarty->assign ("action", _("Continue anyway"));
1339   } else {
1340     $smarty->assign ("action", _("Edit anyway"));
1341   }
1342   $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
1344   return ($smarty->fetch (get_template_path('islocked.tpl')));
1348 function to_string ($value)
1350   /* If this is an array, generate a text blob */
1351   if (is_array($value)){
1352     $ret= "";
1353     foreach ($value as $line){
1354       $ret.= $line."<br>\n";
1355     }
1356     return ($ret);
1357   } else {
1358     return ($value);
1359   }
1363 function get_printer_list()
1365   global $config;
1366   $res = array();
1367   $data = get_list('(objectClass=gotoPrinter)',"printer",$config->current['BASE'], array('cn'), GL_SUBSEARCH);
1368   foreach($data as $attrs ){
1369     $res[$attrs['cn'][0]] = $attrs['cn'][0];
1370   }
1371   return $res;
1375 function rewrite($s)
1377   global $REWRITE;
1379   foreach ($REWRITE as $key => $val){
1380     $s= str_replace("$key", "$val", $s);
1381   }
1383   return ($s);
1387 function dn2base($dn)
1389   global $config;
1391   if (get_people_ou() != ""){
1392     $dn= preg_replace('/,'.get_people_ou().'/i' , ',', $dn);
1393   }
1394   if (get_groups_ou() != ""){
1395     $dn= preg_replace('/,'.get_groups_ou().'/i' , ',', $dn);
1396   }
1397   $base= preg_replace ('/^[^,]+,/i', '', $dn);
1399   return ($base);
1404 function check_command($cmdline)
1406   $cmd= preg_replace("/ .*$/", "", $cmdline);
1408   /* Check if command exists in filesystem */
1409   if (!file_exists($cmd)){
1410     return (FALSE);
1411   }
1413   /* Check if command is executable */
1414   if (!is_executable($cmd)){
1415     return (FALSE);
1416   }
1418   return (TRUE);
1422 function print_header($image, $headline, $info= "")
1424   $display= "<div class=\"plugtop\">\n";
1425   $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";
1426   $display.= "</div>\n";
1428   if ($info != ""){
1429     $display.= "<div class=\"pluginfo\">\n";
1430     $display.= "$info";
1431     $display.= "</div>\n";
1432   } else {
1433     $display.= "<div style=\"height:5px;\">\n";
1434     $display.= "&nbsp;";
1435     $display.= "</div>\n";
1436   }
1437   return ($display);
1441 function range_selector($dcnt,$start,$range=25,$post_var=false)
1444   /* Entries shown left and right from the selected entry */
1445   $max_entries= 10;
1447   /* Initialize and take care that max_entries is even */
1448   $output="";
1449   if ($max_entries & 1){
1450     $max_entries++;
1451   }
1453   if((!empty($post_var))&&(isset($_POST[$post_var]))){
1454     $range= $_POST[$post_var];
1455   }
1457   /* Prevent output to start or end out of range */
1458   if ($start < 0 ){
1459     $start= 0 ;
1460   }
1461   if ($start >= $dcnt){
1462     $start= $range * (int)(($dcnt / $range) + 0.5);
1463   }
1465   $numpages= (($dcnt / $range));
1466   if(((int)($numpages))!=($numpages)){
1467     $numpages = (int)$numpages + 1;
1468   }
1469   if ((((int)$numpages) <= 1 )&&(!$post_var)){
1470     return ("");
1471   }
1472   $ppage= (int)(($start / $range) + 0.5);
1475   /* Align selected page to +/- max_entries/2 */
1476   $begin= $ppage - $max_entries/2;
1477   $end= $ppage + $max_entries/2;
1479   /* Adjust begin/end, so that the selected value is somewhere in
1480      the middle and the size is max_entries if possible */
1481   if ($begin < 0){
1482     $end-= $begin + 1;
1483     $begin= 0;
1484   }
1485   if ($end > $numpages) {
1486     $end= $numpages;
1487   }
1488   if (($end - $begin) < $max_entries && ($end - $max_entries) > 0){
1489     $begin= $end - $max_entries;
1490   }
1492   if($post_var){
1493     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>
1494       <table summary='' width='100%'><tr><td style='width:25%'></td><td style='text-align:center;'>";
1495   }else{
1496     $output.= "<div style='border:1px solid #E0E0E0; background-color:#FFFFFF;'>";
1497   }
1499   /* Draw decrement */
1500   if ($start > 0 ) {
1501     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1502       (($start-$range))."\">".
1503       "<img class=\"center\" alt=\"\" src=\"images/back.png\" border=0 align=\"middle\"></a>";
1504   }
1506   /* Draw pages */
1507   for ($i= $begin; $i < $end; $i++) {
1508     if ($ppage == $i){
1509       $output.= "<a style=\"vertical-align:middle;background-color:#D0D0D0;\" href=\"main.php?plug=".
1510         validate($_GET['plug'])."&amp;start=".
1511         ($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1512     } else {
1513       $output.= "<a style=\"vertical-align:middle;\" href=\"main.php?plug=".validate($_GET['plug']).
1514         "&amp;start=".($i*$range)."\">&nbsp;".($i+1)."&nbsp;</a>";
1515     }
1516   }
1518   /* Draw increment */
1519   if($start < ($dcnt-$range)) {
1520     $output.="  <a href= \"main.php?plug=".validate($_GET['plug'])."&amp;start=".
1521       (($start+($range)))."\">".
1522       "<img class=\"center\" alt=\"\" src=\"images/forward.png\" border=\"0\" align=\"middle\"></a>";
1523   }
1525   if(($post_var)&&($numpages)){
1526     $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()'>";
1527     foreach(array(20,50,100,200,"all") as $num){
1528       if($num == "all"){
1529         $var = 10000;
1530       }else{
1531         $var = $num;
1532       }
1533       if($var == $range){
1534         $output.="\n<option selected='selected' value='".$var."'>".$num."</option>";
1535       }else{  
1536         $output.="\n<option value='".$var."'>".$num."</option>";
1537       }
1538     }
1539     $output.=  "</select></td></tr></table></div>";
1540   }else{
1541     $output.= "</div>";
1542   }
1544   return($output);
1548 function apply_filter()
1550   $apply= "";
1552   $apply= ''.
1553     '<table summary=""  width="100%"  style="background:#EEEEEE;border-top:1px solid #B0B0B0;"><tr><td width="100%" align="right">'.
1554     '<input type="submit" name="apply" value="'._("Apply filter").'"></td></tr></table>';
1556   return ($apply);
1560 function back_to_main()
1562   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
1563     msgPool::backButton().'"></p><input type="hidden" name="ignore">';
1565   return ($string);
1569 function normalize_netmask($netmask)
1571   /* Check for notation of netmask */
1572   if (!preg_match('/^([0-9]+\.){3}[0-9]+$/', $netmask)){
1573     $num= (int)($netmask);
1574     $netmask= "";
1576     for ($byte= 0; $byte<4; $byte++){
1577       $result=0;
1579       for ($i= 7; $i>=0; $i--){
1580         if ($num-- > 0){
1581           $result+= pow(2,$i);
1582         }
1583       }
1585       $netmask.= $result.".";
1586     }
1588     return (preg_replace('/\.$/', '', $netmask));
1589   }
1591   return ($netmask);
1595 function netmask_to_bits($netmask)
1597   list($nm0, $nm1, $nm2, $nm3)= split('\.', $netmask);
1598   $res= 0;
1600   for ($n= 0; $n<4; $n++){
1601     $start= 255;
1602     $name= "nm$n";
1604     for ($i= 0; $i<8; $i++){
1605       if ($start == (int)($$name)){
1606         $res+= 8 - $i;
1607         break;
1608       }
1609       $start-= pow(2,$i);
1610     }
1611   }
1613   return ($res);
1617 function recurse($rule, $variables)
1619   $result= array();
1621   if (!count($variables)){
1622     return array($rule);
1623   }
1625   reset($variables);
1626   $key= key($variables);
1627   $val= current($variables);
1628   unset ($variables[$key]);
1630   foreach($val as $possibility){
1631     $nrule= str_replace("{$key}", $possibility, $rule);
1632     $result= array_merge($result, recurse($nrule, $variables));
1633   }
1635   return ($result);
1639 function expand_id($rule, $attributes)
1641   /* Check for id rule */
1642   if(preg_match('/^id(:|#)\d+$/',$rule)){
1643     return (array("\{$rule}"));
1644   }
1646   /* Check for clean attribute */
1647   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
1648     $rule= preg_replace('/^%/', '', $rule);
1649     $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
1650     return (array($val));
1651   }
1653   /* Check for attribute with parameters */
1654   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
1655     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
1656     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
1657     $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
1658     $start= preg_replace ('/-.*$/', '', $param);
1659     $stop = preg_replace ('/^[^-]+-/', '', $param);
1661     /* Assemble results */
1662     $result= array();
1663     for ($i= $start; $i<= $stop; $i++){
1664       $result[]= substr($val, 0, $i);
1665     }
1666     return ($result);
1667   }
1669   echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
1670   return (array($rule));
1674 function gen_uids($rule, $attributes)
1676   global $config;
1678   /* Search for keys and fill the variables array with all 
1679      possible values for that key. */
1680   $part= "";
1681   $trigger= false;
1682   $stripped= "";
1683   $variables= array();
1685   for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
1687     if ($rule[$pos] == "{" ){
1688       $trigger= true;
1689       $part= "";
1690       continue;
1691     }
1693     if ($rule[$pos] == "}" ){
1694       $variables[$pos]= expand_id($part, $attributes);
1695       $stripped.= "{".$pos."}";
1696       $trigger= false;
1697       continue;
1698     }
1700     if ($trigger){
1701       $part.= $rule[$pos];
1702     } else {
1703       $stripped.= $rule[$pos];
1704     }
1705   }
1707   /* Recurse through all possible combinations */
1708   $proposed= recurse($stripped, $variables);
1710   /* Get list of used ID's */
1711   $used= array();
1712   $ldap= $config->get_ldap_link();
1713   $ldap->cd($config->current['BASE']);
1714   $ldap->search('(uid=*)');
1716   while($attrs= $ldap->fetch()){
1717     $used[]= $attrs['uid'][0];
1718   }
1720   /* Remove used uids and watch out for id tags */
1721   $ret= array();
1722   foreach($proposed as $uid){
1724     /* Check for id tag and modify uid if needed */
1725     if(preg_match('/\{id:\d+}/',$uid)){
1726       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
1728       for ($i= 0, $p= pow(10,$size); $i < $p; $i++){
1729         $number= sprintf("%0".$size."d", $i);
1730         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
1731         if (!in_array($res, $used)){
1732           $uid= $res;
1733           break;
1734         }
1735       }
1736     }
1738     if(preg_match('/\{id#\d+}/',$uid)){
1739       $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
1741       while (true){
1742         mt_srand((double) microtime()*1000000);
1743         $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
1744         $res= preg_replace('/{id#(\d+)}/', $number, $uid);
1745         if (!in_array($res, $used)){
1746           $uid= $res;
1747           break;
1748         }
1749       }
1750     }
1752     /* Don't assign used ones */
1753     if (!in_array($uid, $used)){
1754       $ret[]= $uid;
1755     }
1756   }
1758   return(array_unique($ret));
1762 /* Sadly values like memory_limit are perpended by K, M, G, etc.
1763    Need to convert... */
1764 function to_byte($value) {
1765   $value= strtolower(trim($value));
1767   if(!is_numeric(substr($value, -1))) {
1769     switch(substr($value, -1)) {
1770       case 'g':
1771         $mult= 1073741824;
1772         break;
1773       case 'm':
1774         $mult= 1048576;
1775         break;
1776       case 'k':
1777         $mult= 1024;
1778         break;
1779     }
1781     return ($mult * (int)substr($value, 0, -1));
1782   } else {
1783     return $value;
1784   }
1788 function in_array_ics($value, $items)
1790         return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
1794 function generate_alphabet($count= 10)
1796   $characters= _("*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
1797   $alphabet= "";
1798   $c= 0;
1800   /* Fill cells with charaters */
1801   for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
1802     if ($c == 0){
1803       $alphabet.= "<tr>";
1804     }
1806     $ch = mb_substr($characters, $i, 1, "UTF8");
1807     $alphabet.= "<td><a class=\"alphaselect\" href=\"main.php?plug=".
1808       validate($_GET['plug'])."&amp;search=".$ch."\">&nbsp;".$ch."&nbsp;</a></td>";
1810     if ($c++ == $count){
1811       $alphabet.= "</tr>";
1812       $c= 0;
1813     }
1814   }
1816   /* Fill remaining cells */
1817   while ($c++ <= $count){
1818     $alphabet.= "<td>&nbsp;</td>";
1819   }
1821   return ($alphabet);
1825 function validate($string)
1827   return (strip_tags(str_replace('\0', '', $string)));
1831 function get_gosa_version()
1833   global $svn_revision, $svn_path;
1835   /* Extract informations */
1836   $revision= preg_replace('/^[^0-9]*([0-9]+)[^0-9]*$/', '\1', $svn_revision);
1838   /* Release or development? */
1839   if (preg_match('%/gosa/trunk/%', $svn_path)){
1840     return (sprintf(_("GOsa development snapshot (Rev %s)"), $revision));
1841   } else {
1842     $release= preg_replace('%^.*/([^/]+)/include/functions.inc.*$%', '\1', $svn_path);
1843     return (sprintf(_("GOsa $release"), $revision));
1844   }
1848 function rmdirRecursive($path, $followLinks=false) {
1849   $dir= opendir($path);
1850   while($entry= readdir($dir)) {
1851     if(is_file($path."/".$entry) || ((!$followLinks) && is_link($path."/".$entry))) {
1852       unlink($path."/".$entry);
1853     } elseif (is_dir($path."/".$entry) && $entry!='.' && $entry!='..') {
1854       rmdirRecursive($path."/".$entry);
1855     }
1856   }
1857   closedir($dir);
1858   return rmdir($path);
1862 function scan_directory($path,$sort_desc=false)
1864   $ret = false;
1866   /* is this a dir ? */
1867   if(is_dir($path)) {
1869     /* is this path a readable one */
1870     if(is_readable($path)){
1872       /* Get contents and write it into an array */   
1873       $ret = array();    
1875       $dir = opendir($path);
1877       /* Is this a correct result ?*/
1878       if($dir){
1879         while($fp = readdir($dir))
1880           $ret[]= $fp;
1881       }
1882     }
1883   }
1884   /* Sort array ascending , like scandir */
1885   sort($ret);
1887   /* Sort descending if parameter is sort_desc is set */
1888   if($sort_desc) {
1889     $ret = array_reverse($ret);
1890   }
1892   return($ret);
1896 function clean_smarty_compile_dir($directory)
1898   global $svn_revision;
1900   if(is_dir($directory) && is_readable($directory)) {
1901     // Set revision filename to REVISION
1902     $revision_file= $directory."/REVISION";
1904     /* Is there a stamp containing the current revision? */
1905     if(!file_exists($revision_file)) {
1906       // create revision file
1907       create_revision($revision_file, $svn_revision);
1908     } else {
1909       # check for "$config->...['CONFIG']/revision" and the
1910       # contents should match the revision number
1911       if(!compare_revision($revision_file, $svn_revision)){
1912         // If revision differs, clean compile directory
1913         foreach(scan_directory($directory) as $file) {
1914           if(($file==".")||($file=="..")) continue;
1915           if( is_file($directory."/".$file) &&
1916               is_writable($directory."/".$file)) {
1917             // delete file
1918             if(!unlink($directory."/".$file)) {
1919               msg_dialog::display(_("Internal error"), sprintf(_("File '%s' could not be deleted."), $directory."/".$file), ERROR_DIALOG);
1920               // This should never be reached
1921             }
1922           } elseif(is_dir($directory."/".$file) &&
1923               is_writable($directory."/".$file)) {
1924             // Just recursively delete it
1925             rmdirRecursive($directory."/".$file);
1926           }
1927         }
1928         // We should now create a fresh revision file
1929         clean_smarty_compile_dir($directory);
1930       } else {
1931         // Revision matches, nothing to do
1932       }
1933     }
1934   } else {
1935     // Smarty compile dir is not accessible
1936     // (Smarty will warn about this)
1937   }
1941 function create_revision($revision_file, $revision)
1943   $result= false;
1945   if(is_dir(dirname($revision_file)) && is_writable(dirname($revision_file))) {
1946     if($fh= fopen($revision_file, "w")) {
1947       if(fwrite($fh, $revision)) {
1948         $result= true;
1949       }
1950     }
1951     fclose($fh);
1952   } else {
1953     msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1954   }
1956   return $result;
1960 function compare_revision($revision_file, $revision)
1962   // false means revision differs
1963   $result= false;
1965   if(file_exists($revision_file) && is_readable($revision_file)) {
1966     // Open file
1967     if($fh= fopen($revision_file, "r")) {
1968       // Compare File contents with current revision
1969       if($revision == fread($fh, filesize($revision_file))) {
1970         $result= true;
1971       }
1972     } else {
1973       msg_dialog::display(_("Internal error"), _("Cannot write to revision file!"), ERROR_DIALOG);
1974     }
1975     // Close file
1976     fclose($fh);
1977   }
1979   return $result;
1983 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
1985   $str = ""; // Our return value will be saved in this var
1987   $color  = dechex($percentage+150);
1988   $color2 = dechex(150 - $percentage);
1989   $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
1991   $progress = (int)(($percentage /100)*$width);
1993   /* If theres a better solution for this, use it... */
1994   $str = "\n   <div style=\" width:".($width)."px; ";
1995   $str.= "\n       height:".($height)."px; ";
1996   $str.= "\n       background-color:#000000; ";
1997   $str.= "\n       padding:1px;\" > ";
1999   $str.= "\n     <div style=\" width:".($width)."px; ";
2000   $str.= "\n         background-color:#$bgcolor; ";
2001   $str.= "\n         height:".($height)."px;\" > ";
2003   if(($height >10)&&($showvalue)){
2004     $str.= "\n   <font style=\"font-size:".($height-2)."px; ";
2005     $str.= "\n     color:#FF0000; align:middle; ";
2006     $str.= "\n     padding-left:".((int)(($width*0.4)))."px; \"> ";
2007     $str.= "\n     <b>".$percentage."%</b> ";
2008     $str.= "\n   </font> ";
2009   }
2011   $str.= "\n       <div style=\" width:".$progress."px; ";
2012   $str.= "\n         height:".$height."px; ";
2013   $str.= "\n         background-color:#".$color2.$color2.$color."; \" >";
2014   $str.= "\n       </div>";
2015   $str.= "\n     </div>";
2016   $str.= "\n   </div>";
2018   return($str);
2022 function array_key_ics($ikey, $items)
2024   $tmp= array_change_key_case($items, CASE_LOWER);
2025   $ikey= strtolower($ikey);
2026   if (isset($tmp[$ikey])){
2027     return($tmp[$ikey]);
2028   }
2030   return ('');
2034 function array_differs($src, $dst)
2036   /* If the count is differing, the arrays differ */
2037   if (count ($src) != count ($dst)){
2038     return (TRUE);
2039   }
2041   return (count(array_diff($src, $dst)) != 0);
2045 function saveFilter($a_filter, $values)
2047   if (isset($_POST['regexit'])){
2048     $a_filter["regex"]= $_POST['regexit'];
2050     foreach($values as $type){
2051       if (isset($_POST[$type])) {
2052         $a_filter[$type]= "checked";
2053       } else {
2054         $a_filter[$type]= "";
2055       }
2056     }
2057   }
2059   /* React on alphabet links if needed */
2060   if (isset($_GET['search'])){
2061     $s= mb_substr(validate($_GET['search']), 0, 1, "UTF8")."*";
2062     if ($s == "**"){
2063       $s= "*";
2064     }
2065     $a_filter['regex']= $s;
2066   }
2068   return ($a_filter);
2072 /* Escape all LDAP filter relevant characters */
2073 function normalizeLdap($input)
2075   return (addcslashes($input, '()|'));
2079 /* Resturns the difference between to microtime() results in float  */
2080 function get_MicroTimeDiff($start , $stop)
2082   $a = split("\ ",$start);
2083   $b = split("\ ",$stop);
2085   $secs = $b[1] - $a[1];
2086   $msecs= $b[0] - $a[0]; 
2088   $ret = (float) ($secs+ $msecs);
2089   return($ret);
2093 function get_base_dir()
2095   global $BASE_DIR;
2097   return $BASE_DIR;
2101 function obj_is_readable($dn, $object, $attribute)
2103   global $ui;
2105   return preg_match('/r/', $ui->get_permissions($dn, $object, $attribute));
2109 function obj_is_writable($dn, $object, $attribute)
2111   global $ui;
2113   return preg_match('/w/', $ui->get_permissions($dn, $object, $attribute));
2117 function gosa_ldap_explode_dn($dn,$config = NULL,$verify_in_ldap=false)
2119   /* Initialize variables */
2120   $ret  = array("count" => 0);  // Set count to 0
2121   $next = true;                 // if false, then skip next loops and return
2122   $cnt  = 0;                    // Current number of loops
2123   $max  = 100;                  // Just for security, prevent looops
2124   $ldap = NULL;                 // To check if created result a valid
2125   $keep = "";                   // save last failed parse string
2127   /* Check each parsed dn in ldap ? */
2128   if($config!==NULL && $verify_in_ldap){
2129     $ldap = $config->get_ldap_link();
2130   }
2132   /* Lets start */
2133   $called = false;
2134   while(preg_match("/,/",$dn) && $next &&  $cnt < $max){
2136     $cnt ++;
2137     if(!preg_match("/,/",$dn)){
2138       $next = false;
2139     }
2140     $object = preg_replace("/[,].*$/","",$dn);
2141     $dn     = preg_replace("/^[^,]+,/","",$dn);
2143     $called = true;
2145     /* Check if current dn is valid */
2146     if($ldap!==NULL){
2147       $ldap->cd($dn);
2148       $ldap->cat($dn,array("dn"));
2149       if($ldap->count()){
2150         $ret[]  = $keep.$object;
2151         $keep   = "";
2152       }else{
2153         $keep  .= $object.",";
2154       }
2155     }else{
2156       $ret[]  = $keep.$object;
2157       $keep   = "";
2158     }
2159   }
2161   /* No dn was posted */
2162   if($cnt == 0 && !empty($dn)){
2163     $ret[] = $dn;
2164   }
2166   /* Append the rest */
2167   $test = $keep.$dn;
2168   if($called && !empty($test)){
2169     $ret[] = $keep.$dn;
2170   }
2171   $ret['count'] = count($ret) - 1;
2173   return($ret);
2177 function get_base_from_hook($dn, $attrib)
2179   global $config;
2181   if ($config->get_cfg_value("baseIdHook") != ""){
2182     
2183     /* Call hook script - if present */
2184     $command= $config->get_cfg_value("baseIdHook");
2186     if ($command != ""){
2187       $command.= " '".LDAP::fix($dn)."' $attrib";
2188       if (check_command($command)){
2189         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2190         exec($command, $output);
2191         if (preg_match("/^[0-9]+$/", $output[0])){
2192           return ($output[0]);
2193         } else {
2194           msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2195           return ($config->get_cfg_value("uidNumberBase"));
2196         }
2197       } else {
2198         msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2199         return ($config->get_cfg_value("uidNumberBase"));
2200       }
2202     } else {
2204       msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
2205       return ($config->get_cfg_value("uidNumberBase"));
2207     }
2208   }
2212 function check_schema_version($class, $version)
2214   return preg_match("/\(v$version\)/", $class['DESC']);
2218 function check_schema($cfg,$rfc2307bis = FALSE)
2220   $messages= array();
2222   /* Get objectclasses */
2223   $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
2224   $objectclasses = $ldap->get_objectclasses();
2225   if(count($objectclasses) == 0){
2226     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
2227   }
2229   /* This is the default block used for each entry.
2230    *  to avoid unset indexes.
2231    */
2232   $def_check = array("REQUIRED_VERSION" => "0",
2233       "SCHEMA_FILES"     => array(),
2234       "CLASSES_REQUIRED" => array(),
2235       "STATUS"           => FALSE,
2236       "IS_MUST_HAVE"     => FALSE,
2237       "MSG"              => "",
2238       "INFO"             => "");#_("There is currently no information specified for this schema extension."));
2240   /* The gosa base schema */
2241   $checks['gosaObject'] = $def_check;
2242   $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
2243   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2244   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
2245   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
2247   /* GOsa Account class */
2248   $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.1";
2249   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
2250   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
2251   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
2252   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
2254   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
2255   $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
2256   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
2257   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
2258   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
2259   $checks["gosaLockEntry"]["INFO"]             = _("Used to lock currently edited entries to avoid multiple changes at the same time.");
2261   /* Some other checks */
2262   foreach(array(
2263         "gosaCacheEntry"        => array("version" => "2.6.1"),
2264         "gosaDepartment"        => array("version" => "2.6.1"),
2265         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2266         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2267         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
2268         "gosaUserTemplate"      => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
2269         "gosaMailAccount"       => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa+samba3.schema"),
2270         "gosaProxyAccount"      => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
2271         "gosaApplication"       => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2272         "gosaApplicationGroup"  => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
2273         "GOhard"                => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2274         "gotoTerminal"          => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2275         "goServer"              => array("version" => "2.6.1","class" => "server","file" => "goserver.schema"),
2276         "goTerminalServer"      => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2277         "goShareServer"         => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2278         "goNtpServer"           => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2279         "goSyslogServer"        => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
2280         "goLdapServer"          => array("version" => "2.6.1"),
2281         "goCupsServer"          => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
2282         "goImapServer"          => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
2283         "goKrbServer"           => array("version" => "2.6.1"),
2284         "goFaxServer"           => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
2285         ) as $name => $values){
2287           $checks[$name] = $def_check;
2288           if(isset($values['version'])){
2289             $checks[$name]["REQUIRED_VERSION"] = $values['version'];
2290           }
2291           if(isset($values['file'])){
2292             $checks[$name]["SCHEMA_FILES"] = array($values['file']);
2293           }
2294           $checks[$name]["CLASSES_REQUIRED"] = array($name);
2295         }
2296   foreach($checks as $name => $value){
2297     foreach($value['CLASSES_REQUIRED'] as $class){
2299       if(!isset($objectclasses[$name])){
2300         $checks[$name]['STATUS'] = FALSE;
2301         if($value['IS_MUST_HAVE']){
2302           $checks[$name]['MSG']    = sprintf(_("Missing required object class '%s'!"),$class);
2303         }else{
2304           $checks[$name]['MSG']    = sprintf(_("Missing optional object class '%s'!"),$class);
2305         }
2306       }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){
2307         $checks[$name]['STATUS'] = FALSE;
2309         if($value['IS_MUST_HAVE']){
2310           $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2311         }else{
2312           $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class,                           $value['REQUIRED_VERSION']);
2313         }
2314       }else{
2315         $checks[$name]['STATUS'] = TRUE;
2316         $checks[$name]['MSG'] = sprintf(_("Class(es) available"));
2317       }
2318     }
2319   }
2321   $tmp = $objectclasses;
2323   /* The gosa base schema */
2324   $checks['posixGroup'] = $def_check;
2325   $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
2326   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
2327   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
2328   $checks['posixGroup']['STATUS']           = TRUE;
2329   $checks['posixGroup']['IS_MUST_HAVE']     = TRUE;
2330   $checks['posixGroup']['MSG']              = "";
2331   $checks['posixGroup']['INFO']             = "";
2333   /* Depending on selected rfc2307bis mode, we need different schema configurations */
2334   if(isset($tmp['posixGroup'])){
2336     if($rfc2307bis && isset($tmp['posixGroup']['STRUCTURAL'])){
2337       $checks['posixGroup']['STATUS']           = FALSE;
2338       $checks['posixGroup']['MSG']              = _("You have enabled the rfc2307bis option on the 'ldap setup' step, but your schema    configuration do not support this option.");
2339       $checks['posixGroup']['INFO']             = _("In order to use rfc2307bis conform groups the objectClass 'posixGroup' must be      AUXILIARY");
2340     }
2341     if(!$rfc2307bis && !isset($tmp['posixGroup']['STRUCTURAL'])){
2342       $checks['posixGroup']['STATUS']           = FALSE;
2343       $checks['posixGroup']['MSG']              = _("Your schema is configured to support the rfc2307bis group, but you have disabled this option on the 'ldap setup' step.");
2344       $checks['posixGroup']['INFO']             = _("The objectClass 'posixGroup' must be STRUCTURAL");
2345     }
2346   }
2348   return($checks);
2352 function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FALSE)
2354   $tmp = array(
2355         "de_DE" => "German",
2356         "fr_FR" => "French",
2357         "it_IT" => "Italian",
2358         "es_ES" => "Spanish",
2359         "en_US" => "English",
2360         "nl_NL" => "Dutch",
2361         "pl_PL" => "Polish",
2362         #"sv_SE" => "Swedish",
2363         "zh_CN" => "Chinese",
2364         "vi_VN" => "Vietnamese",
2365         "ru_RU" => "Russian");
2366   
2367   $tmp2= array(
2368         "de_DE" => _("German"),
2369         "fr_FR" => _("French"),
2370         "it_IT" => _("Italian"),
2371         "es_ES" => _("Spanish"),
2372         "en_US" => _("English"),
2373         "nl_NL" => _("Dutch"),
2374         "pl_PL" => _("Polish"),
2375         #"sv_SE" => _("Swedish"),
2376         "zh_CN" => _("Chinese"),
2377         "vi_VN" => _("Vietnamese"),
2378         "ru_RU" => _("Russian"));
2380   $ret = array();
2381   if($languages_in_own_language){
2383     $old_lang = setlocale(LC_ALL, 0);
2385     /* If the locale wasn't correclty set before, there may be an incorrect
2386         locale returned. Something like this: 
2387           C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
2388         Extract the locale name from this string and use it to restore old locale.
2389      */
2390     if(preg_match("/LC_CTYPE/",$old_lang)){
2391       $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
2392     }
2393     
2394     foreach($tmp as $key => $name){
2395       $lang = $key.".UTF-8";
2396       setlocale(LC_ALL, $lang);
2397       if($strip_region_tag){
2398         $ret[preg_replace("/^([^_]*).*$/","\\1",$key)] = _($name)." (".$tmp2[$key].")";
2399       }else{
2400         $ret[$key] = _($name)." &nbsp;(".$tmp2[$key].")";
2401       }
2402     }
2403     setlocale(LC_ALL, $old_lang);
2404   }else{
2405     foreach($tmp as $key => $name){
2406       if($strip_region_tag){
2407         $ret[preg_replace("/^([^_]*).*/","\\1",$key)] = _($name);
2408       }else{
2409         $ret[$key] = _($name);
2410       }
2411     }
2412   }
2413   return($ret);
2417 /* Returns contents of the given POST variable and check magic quotes settings */
2418 function get_post($name)
2420   if(!isset($_POST[$name])){
2421     trigger_error("Requested POST value (".$name.") does not exists, you should add a check to prevent this message.");
2422     return(FALSE);
2423   }
2424   if(get_magic_quotes_gpc()){
2425     return(stripcslashes($_POST[$name]));
2426   }else{
2427     return($_POST[$name]);
2428   }
2432 /* Return class name in correct case */
2433 function get_correct_class_name($cls)
2435   global $class_mapping;
2436   if(isset($class_mapping) && is_array($class_mapping)){
2437     foreach($class_mapping as $class => $file){
2438       if(preg_match("/^".$cls."$/i",$class)){
2439         return($class);
2440       }
2441     }
2442   }
2443   return(FALSE);
2447 // change_password, changes the Password, of the given dn
2448 function change_password ($dn, $password, $mode=0, $hash= "")
2450   global $config;
2451   $newpass= "";
2453   /* Convert to lower. Methods are lowercase */
2454   $hash= strtolower($hash);
2456   // Get all available encryption Methods
2458   // NON STATIC CALL :)
2459   $methods = new passwordMethod(session::get('config'));
2460   $available = $methods->get_available_methods();
2462   // read current password entry for $dn, to detect the encryption Method
2463   $ldap       = $config->get_ldap_link();
2464   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
2465   $attrs      = $ldap->fetch ();
2467   /* Is ensure that clear passwords will stay clear */
2468   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
2469     $hash = "clear";
2470   }
2472   // Detect the encryption Method
2473   if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){
2475     /* Check for supported algorithm */
2476     mt_srand((double) microtime()*1000000);
2478     /* Extract used hash */
2479     if ($hash == ""){
2480       $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
2481     } else {
2482       $test = new $available[$hash]($config,$dn);
2483       $test->set_hash($hash);
2484     }
2486   } else {
2487     // User MD5 by default
2488     $hash= "md5";
2489     $test = new  $available['md5']($config);
2490   }
2492   if($test instanceOf passwordMethod){
2494     $deactivated = $test->is_locked($config,$dn);
2496     /* Feed password backends with information */
2497     $test->dn= $dn;
2498     $test->attrs= $attrs;
2499     $newpass= $test->generate_hash($password);
2501     // Update shadow timestamp?
2502     if (isset($attrs["shadowLastChange"][0])){
2503       $shadow= (int)(date("U") / 86400);
2504     } else {
2505       $shadow= 0;
2506     }
2508     // Write back modified entry
2509     $ldap->cd($dn);
2510     $attrs= array();
2512     // Not for groups
2513     if ($mode == 0){
2515       if ($shadow != 0){
2516         $attrs['shadowLastChange']= $shadow;
2517       }
2519       // Create SMB Password
2520       $attrs= generate_smb_nt_hash($password);
2521     }
2523     $attrs['userPassword']= array();
2524     $attrs['userPassword']= $newpass;
2526     $ldap->modify($attrs);
2528     /* Read ! if user was deactivated */
2529     if($deactivated){
2530       $test->lock_account($config,$dn);
2531     }
2533     new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
2535     if (!$ldap->success()) {
2536       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
2537     } else {
2539       /* Run backend method for change/create */
2540       if(!$test->set_password($password)){
2541         return(FALSE);
2542       }
2544       /* Find postmodify entries for this class */
2545       $command= $config->search("password", "POSTMODIFY",array('menu'));
2547       if ($command != ""){
2548         /* Walk through attribute list */
2549         $command= preg_replace("/%userPassword/", $password, $command);
2550         $command= preg_replace("/%dn/", $dn, $command);
2552         if (check_command($command)){
2553           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
2554           exec($command);
2555         } else {
2556           $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
2557           msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
2558         }
2559       }
2560     }
2561     return(TRUE);
2562   }
2566 // Return something like array['sambaLMPassword']= "lalla..."
2567 function generate_smb_nt_hash($password)
2569   global $config;
2571   # Try to use gosa-si?
2572   if ($config->get_cfg_value("gosaSupportURI") != ""){
2573         $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
2574     if (isset($res['XML']['HASH'])){
2575         $hash= $res['XML']['HASH'];
2576     } else {
2577       $hash= "";
2578     }
2579   } else {
2580           $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
2581           @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
2583           exec($tmp, $ar);
2584           flush();
2585           reset($ar);
2586           $hash= current($ar);
2587   }
2589   if ($hash == "") {
2590           msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
2591           return ("");
2592   }
2594   list($lm,$nt)= split (":", trim($hash));
2596   if ($config->get_cfg_value("sambaversion") == 3) {
2597           $attrs['sambaLMPassword']= $lm;
2598           $attrs['sambaNTPassword']= $nt;
2599           $attrs['sambaPwdLastSet']= date('U');
2600           $attrs['sambaBadPasswordCount']= "0";
2601           $attrs['sambaBadPasswordTime']= "0";
2602   } else {
2603           $attrs['lmPassword']= $lm;
2604           $attrs['ntPassword']= $nt;
2605           $attrs['pwdLastSet']= date('U');
2606   }
2607   return($attrs);
2611 function getEntryCSN($dn)
2613   global $config;
2614   if(empty($dn) || !is_object($config)){
2615     return("");
2616   }
2618   /* Get attribute that we should use as serial number */
2619   $attr= $config->get_cfg_value("modificationDetectionAttribute");
2620   if($attr != ""){
2621     $ldap = $config->get_ldap_link();
2622     $ldap->cat($dn,array($attr));
2623     $csn = $ldap->fetch();
2624     if(isset($csn[$attr][0])){
2625       return($csn[$attr][0]);
2626     }
2627   }
2628   return("");
2632 /* Add a given objectClass to an attrs entry */
2633 function add_objectClass($classes, &$attrs)
2635   if (is_array($classes)){
2636     $list= $classes;
2637   } else {
2638     $list= array($classes);
2639   }
2641   foreach ($list as $class){
2642     $attrs['objectClass'][]= $class;
2643   }
2647 /* Removes a given objectClass from the attrs entry */
2648 function remove_objectClass($classes, &$attrs)
2650   if (isset($attrs['objectClass'])){
2651     /* Array? */
2652     if (is_array($classes)){
2653       $list= $classes;
2654     } else {
2655       $list= array($classes);
2656     }
2658     $tmp= array();
2659     foreach ($attrs['objectClass'] as $oc) {
2660       foreach ($list as $class){
2661         if (strtolower($oc) != strtolower($class)){
2662           $tmp[]= $oc;
2663         }
2664       }
2665     }
2666     $attrs['objectClass']= $tmp;
2667   }
2670 /*! \brief  Initialize a file download with given content, name and data type. 
2671  *  @param  data  String The content to send.
2672  *  @param  name  String The name of the file.
2673  *  @param  type  String The content identifier, default value is "application/octet-stream";
2674  */
2675 function send_binary_content($data,$name,$type = "application/octet-stream")
2677   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2678   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
2679   header("Cache-Control: no-cache");
2680   header("Pragma: no-cache");
2681   header("Cache-Control: post-check=0, pre-check=0");
2682   header("Content-type: ".$type."");
2684   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
2686   /* Strip name if it is a complete path */
2687   if (preg_match ("/\//", $name)) {
2688         $name= basename($name);
2689   }
2690   
2691   /* force download dialog */
2692   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
2693     header('Content-Disposition: filename="'.$name.'"');
2694   } else {
2695     header('Content-Disposition: attachment; filename="'.$name.'"');
2696   }
2698   echo $data;
2699   exit();
2703 function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
2705   if(is_string($str)){
2706     return(htmlentities($str,$type,$charset));
2707   }elseif(is_array($str)){
2708     foreach($str as $name => $value){
2709       $str[$name] = reverse_html_entities($value,$type,$charset);
2710     }
2711   }
2712   return($str);
2716 /*! \brief Encode special string characters so we can use the string in \
2717            HTML output, without breaking quotes.
2718     @param  The String we want to encode.
2719     @return The encoded String
2720  */
2721 function xmlentities($str)
2722
2723   if(is_string($str)){
2725     static $asc2uni= array();
2726     if (!count($asc2uni)){
2727       for($i=128;$i<256;$i++){
2728     #    $asc2uni[chr($i)] = "&#x".dechex($i).";";
2729       }
2730     }
2732     $str = str_replace("&", "&amp;", $str);
2733     $str = str_replace("<", "&lt;", $str);
2734     $str = str_replace(">", "&gt;", $str);
2735     $str = str_replace("'", "&apos;", $str);
2736     $str = str_replace("\"", "&quot;", $str);
2737     $str = str_replace("\r", "", $str);
2738     $str = strtr($str,$asc2uni);
2739     return $str;
2740   }elseif(is_array($str)){
2741     foreach($str as $name => $value){
2742       $str[$name] = xmlentities($value);
2743     }
2744   }
2745   return($str);
2749 /*! \brief  Updates all accessTo attributes from a given value to a new one.
2750             For example if a host is renamed.
2751     @param  String  $from The source accessTo name.
2752     @param  String  $to   The destination accessTo name.
2753 */
2754 function update_accessTo($from,$to)
2756   global $config;
2757   $ldap = $config->get_ldap_link();
2758   $ldap->cd($config->current['BASE']);
2759   $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
2760   while($attrs = $ldap->fetch()){
2761     $new_attrs = array("accessTo" => array());
2762     $dn = $attrs['dn'];
2763     for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
2764       $new_attrs['objectClass'][] =  $attrs['objectClass'][$i];
2765     }
2766     for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
2767       if($attrs['accessTo'][$i] == $from){
2768         if(!empty($to)){
2769           $new_attrs['accessTo'][] =  $to;
2770         }
2771       }else{
2772         $new_attrs['accessTo'][] =  $attrs['accessTo'][$i]; 
2773       }
2774     }
2775     $ldap->cd($dn);
2776     $ldap->modify($new_attrs);
2777     if (!$ldap->success()){
2778       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
2779     }
2780     new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
2781   }
2785 function get_random_char () {
2786      $randno = rand (0, 63);
2787      if ($randno < 12) {
2788          return (chr ($randno + 46)); // Digits, '/' and '.'
2789      } else if ($randno < 38) {
2790          return (chr ($randno + 53)); // Uppercase
2791      } else {
2792          return (chr ($randno + 59)); // Lowercase
2793      }
2797 function cred_encrypt($input, $password) {
2799   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2800   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2802   return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
2806 function cred_decrypt($input,$password) {
2807   $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
2808   $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
2810   return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
2814 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2815 ?>