Code

Fixed Workstation Startup
[gosa.git] / gosa-plugins / goto / admin / systems / goto / class_workstationStartup.inc
1 <?php
2 class workstartup extends plugin
3 {
4   /* Ldap server list */
5   var $gotoLdapServers    = array();
6   var $gotoLdapServerList = array();
7   var $gotoLdap_inherit   = FALSE;
9   /* Generic terminal attributes */
10   var $bootmode             = "G";
11   var $gotoBootKernel       = "default-inherited";
12   var $gotoKernelParameters = "";
13   var $gotoLdapServer       = "default-inherited";
14   var $gotoModules          = array();
15   var $gotoAutoFs           = array();
16   var $gotoFilesystem       = array();
17   var $gotoTerminalPath     = "";
18   var $gotoBootKernels      = array();
20   /* attribute list for save action */
21   var $attributes           = array("gotoLdapServer", "gotoBootKernel", "gotoKernelParameters", 
22                                     "FAIclass", "FAIstatus", "gotoShare","FAIdebianMirror", "FAIrelease");
23   var $objectclasses        = array("GOhard", "FAIobject");
25   /* Share */
26   var $gotoShares         = array();// Currently Share Option
27   var $gotoShare          = "";     // currently selected Share Option
28   var $gotoShareSelections= array();// Available Shares for this account in Listbox format
29   var $gotoAvailableShares= array();// Available Shares for this account
31   /* Helper */
32   var $customParameters   = "";
33   var $orig_dn            = "";
34   var $ignore_account     = TRUE;
35  
36   /* FAI class selection */ 
37   var $FAIclass           = array();  // The currently selected classes 
38   var $FAIrelease         = "";
39   var $FAIdebianMirror    = "auto";
40   var $si_active            = FALSE;
41   var $si_fai_action_failed = FALSE;
43   var $cache              = array(); // Used as cache in fai mehtods
45   var $FAIstatus          = "";
46   var $FAIclasses         = array();
48   var $view_logged        = FALSE;
49   
50   /* FAI class selection */
51   var $InheritedFAIclass       = array();
52   var $InheritedFAIrelease     = "";
53   var $InheritedFAIdebianMirror= "auto";
55   var $CopyPasteVars    = array("gotoModules","gotoShares");
56   var $fai_activated    = FALSE;
57   var $o_group_dn       = "";
58   var $member_of_ogroup = FALSE;
60   function workstartup (&$config, $dn= NULL, $parent= NULL)
61   {
62     /* Check if FAI is active */
63     $tmp= $config->search("faiManagement", "CLASS",array('menu','tabs'));
64     if(!empty($tmp)){
65       $this->fai_activated = TRUE;
66     }else{
67       $this->attributes = array("gotoLdapServer", "gotoBootKernel", "gotoKernelParameters", "gotoShare");
68       $this->objectclasses  = array("GOhard");
69     }
71     plugin::plugin ($config, $dn, $parent);
73     /* Check for si daemon */
74     $this->si_active = isset($this->config->current['GOSA_SI']) && !empty($this->config->current['GOSA_SI']);
76     /* Check object group membership */
77     if(!isset($this->parent->by_object['ogroup'])){
78       $ldap = $this->config->get_ldap_link();
79       $ldap->cd ($this->config->current['BASE']);
80       $ldap->search("(&(objectClass=gotoWorkstationTemplate)(member=".LDAP::prepare4filter($this->dn)."))",array("cn","dn"));
81       if($ldap->count()){
82         $this->member_of_ogroup = TRUE;
83         $attrs = $ldap->fetch();
84         $this->o_group_dn = $attrs['dn'];
85       }
86     }
88     /* Creating a list of valid Mirrors 
89      * none will not be saved to ldap.
90      */
91     $ldap   = $this->config->get_ldap_link();
92     $ldap->cd($this->config->current['BASE']);
93     foreach($this->config->data['SERVERS']['LDAP'] as $server) {
94       $this->gotoLdapServerList[]= $server; 
95     }
97     /* Get list of assigned ldap servers 
98      */ 
99     if(isset($this->attrs['gotoLdapServer'])){
100       unset($this->attrs['gotoLdapServer']['count']);
101       sort($this->attrs['gotoLdapServer']);
102       foreach($this->attrs['gotoLdapServer'] as $value){
103         $this->gotoLdapServers[] = preg_replace("/^[0-9]*:/","",$value);
104       }
105     } 
106     if(!count($this->gotoLdapServers) && $this->member_of_ogroup){ 
107       $this->gotoLdap_inherit = TRUE;
108     }
110     /* FAI Initialization
111        Skip this if FAI is not activated 
112      */
113     if($this->fai_activated) {
115       $this->update_fai_cache(TRUE);
117       /* Parse used FAIclasses (stored as string).
118        * The single classes are seperated by ' '.
119        * There is also the release type given, after first
120        *  occurrence of ':'.
121        */
122       $this->FAIclass =array();
123       if(isset($this->attrs['FAIclass'][0])){
124         $tmp = split(" ",$this->attrs['FAIclass'][0]);
125         $tmp2 =array();  
127         foreach($tmp as $class){
128           if( ":" == $class[0] ) {
129             $this->FAIrelease = trim(substr($class, 1));
130           }else{
131             $tmp2[$class] = $class;
132           }
133         }
134         $this->FAIclass = $tmp2;
135       }
136     }
138     /* Get arrays */
139     foreach (array("gotoModules", "gotoAutoFs", "gotoFilesystem") as $val){
140       if (isset($this->attrs["$val"]["count"])){
141         for ($i= 0; $i<$this->attrs["count"]; $i++){
142           if (isset($this->attrs["$val"][$i])){
143             array_push($this->$val, $this->attrs["$val"][$i]);
144           }
145         }
146       }
147       sort ($this->$val);
148       $this->$val= array_unique($this->$val);
149     }
151     /* Parse Kernel Parameters to decide what boot mode is enabled */
152     if (preg_match("/ splash=silent/", $this->gotoKernelParameters)){
153       $this->bootmode= "G";
154     } elseif (preg_match("/ debug/", $this->gotoKernelParameters)){
155       $this->bootmode= "D";
156     } elseif ($this->gotoKernelParameters == "") {
157       $this->bootmode= "G";
158     } else {
159       $this->bootmode= "T";
160     }
161     if (preg_match("/ o /", $this->gotoKernelParameters)){
162       $this->customParameters= preg_replace ("/^.* o /", "", $this->gotoKernelParameters);
163     } else {
164       $this->customParameters= "";
165     }
167     /* Prepare Shares */
168     if((isset($this->attrs['gotoShare']))&&(is_array($this->attrs['gotoShare']))){
169       unset($this->attrs['gotoShare']['count']);
170       foreach($this->attrs['gotoShare'] as $share){
171         $tmp = $tmp2 = array();
172         $tmp = split("\|",$share);
173         $tmp2['server']      =$tmp[0];
174         $tmp2['name']        =$tmp[1];
175         $tmp2['mountPoint']  =$tmp[2];
176         $this->gotoShares[$tmp[1]."|".$tmp[0]]=$tmp2;
177       }
178     }
180     $this->gotoShareSelections= $config->getShareList(true);
181     $this->gotoAvailableShares= $config->getShareList(false);
182     $tmp2 = array();
183   
185     $this->orig_dn= $this->dn;
187     /* Handle inheritance value "default" */
188     if ($this->member_of_ogroup){
189       $this->gotoBootKernels= array("default-inherited" => '['._("inherited").']'); 
190     }
192     /* If we are member in an object group,
193      *  we have to handle inherited values.
194      * So you can see what is inherited.
195      */
196     if ($this->member_of_ogroup){
198       if(count($this->FAIclass)==0 && $this->FAIrelease == ""){
199         $this->FAIdebianMirror = "inherited";
200       }
202       if($this->fai_activated){
203         $map= array("gotoBootKernel","FAIclass","FAIdebianMirror");
204       }else{
205         $map= array("gotoBootKernel");
206       }
208       $ldap = $this->config->get_ldap_link();
209       $ldap->cat($this->o_group_dn);
210       $attrs= $ldap->fetch();
212       foreach ($map as $name){
213         if (!isset($attrs[$name][0])){
214           continue;
215         }
217         switch ($name){
218           case 'gotoBootKernel':
219             $this->gotoBootKernels['default-inherited']=  _("inherited").' ['.$attrs[$name][0].']' ;
220             break;
222           case 'FAIclass':
223             $str = split(":",$attrs[$name][0]);
224             $this->InheritedFAIclass    = split("\ ",trim($str[0]));
225             $this->InheritedFAIrelease  = trim($str[1]);
226             break;
228           case 'FAIdebianMirror':
229             $this->InheritedFAIdebianMirror = $attrs[$name][0];
230             break;
231         }
232       }
233     }
236     if($this->fai_activated && !$this->si_fai_action_failed && $this->si_active){
238       /* Check if the current mirror is available 
239        */
240       if(!isset($this->cache['SERVERS'][$this->FAIdebianMirror])){
241         if(count($this->FAIclass)){
242           msg_dialog::display(_("Error"), sprintf(_("FAI mirror '%s' is not available - setting to mirror 'auto'!"), $this->FAIdebianMirror), ERROR_DIALOG);
243         }
244         $this->FAIdebianMirror = "auto";
245         $this->FAIrelease = key($this->cache['SERVERS'][$this->FAIdebianMirror]);
246         $this->cache =array();
247         $this->update_fai_cache();
248         
249       }
250   
251       /* Check if the current mirror is available 
252        */
253       if(!isset($this->cache['SERVERS'][$this->FAIdebianMirror][$this->FAIrelease])){
254         $new_release = key($this->cache['SERVERS'][$this->FAIdebianMirror]); 
255         if(count($this->FAIclass)){
256           msg_dialog::display(_("Error"), sprintf(_("FAI release '%s' is not available on mirror '%s' - setting to release '%s'!"), $this->FAIrelease, $this->FAIdebianMirror,$new_release), ERROR_DIALOG);
257         }
258         $this->FAIrelease = $new_release;
259         $this->cache =array();
260         $this->update_fai_cache();
261       }
262     }
264     /* Get list of boot kernels */
265     if (isset($this->config->data['TABS'])){
266       $command= $this->config->search(get_class($this), "KERNELS",array('tabs'));
267       if (!check_command($command)){
268         $message[]= sprintf(_("Command '%s', specified as KERNELS hook for plugin '%s' doesn't seem to exist."), $command,
269             get_class($this));
270       } else {
271         $fh= popen($command, "r");
272         while (!feof($fh)) {
273           $buffer= trim(fgets($fh, 256));
274           if(!empty($buffer)){
275             $name=$value = $buffer;
276             if(preg_match("/:/",$buffer)){
277               $name = preg_replace("/:.*$/","",$buffer);
278               $value= preg_replace("/^.*:/","",$buffer);
279               $this->gotoBootKernels[$name]= $name.":".$value;
280             }else{
281               $this->gotoBootKernels[$name]= $value;
282             }
283           }
284         }
285         pclose($fh);
286       }
287     }
289     /* Turn to default, if we've nothing to inherit */
290     if (!isset($this->gotoBootKernels['default-inherited']) && $this->gotoBootKernel == "default-inherited"){
291       $this->gotoBootKernel= "default";
292     }
293   }
295   
296   function check()
297   {
298     $messages = array();
299     
300     /* Call common method to give check the hook */
301     $messages= plugin::check();
303     /* If there are packages selected, but no mirror show error */   
304     if(($this->FAIdebianMirror == "none")&&(count($this->FAIclass)>0)){
305       $messages[]=_("Please select a 'FAI server' or remove the 'FAI classes'.");
306     }
308     return($messages);
309   }
311   function execute()
312   {
313         /* Call parent execute */
314         plugin::execute();
316     if($this->is_account && !$this->view_logged){
317       $this->view_logged = TRUE;
318       new log("view","workstation/".get_class($this),$this->dn);
319     }
321     /* Do we need to flip is_account state? */
322     if(isset($_POST['modify_state'])){
323       if($this->is_account && $this->acl_is_removeable()){
324         $this->is_account= FALSE;
325       }elseif(!$this->is_account && $this->acl_is_createable()){
326         $this->is_account= TRUE;
327       }
328     }
330     /* Do we represent a valid terminal? */
331     if (!$this->is_account && $this->parent === NULL){
332       $display= "<img alt=\"\" src=\"images/stop.png\" align=middle>&nbsp;<b>".
333         msgPool::noValidExtension(_("workstation"))."</b>";
334       return ($display);
335     }
337     /* Add module */
338     if (isset ($_POST['add_module'])){
339       if ($_POST['module'] != "" && $this->acl_is_writeable("gotoModule")){
340         $this->add_list ($this->gotoModules, $_POST['module']);
341       }
342     }
344     /* Delete module */
345     if (isset ($_POST['delete_module'])){
346       if (count($_POST['modules_list']) && $this->acl_is_writeable("gotoModule")){
347         $this->del_list ($this->gotoModules, $_POST['modules_list']);
348       }
349     }
351     /* FAI class management */
352     if($this->fai_activated){
353       if(((isset($_POST['AddClass']))&&(isset($_POST['FAIclassesSel']))) && ($this->acl_is_writeable("FAIclass"))){
354         $found = 0 ; 
356         /* If this new class/profile will attach a second partition table
357          * to our list of classes, abort and show a message.
358          */
359         foreach($this->FAIclass as $name){
360           if(isset($this->FAIclassInfo[$name])){
361             foreach($this->FAIclassInfo[$name] as $atr){
362               if(isset($atr['obj'])){
363                 if($atr['obj'] == "FAIpartitionTable"){
364                   $found ++ ; 
365                 }
366               }
367             }
368           }
369         }
371         if((isset($this->FAIclassInfo[$_POST['FAIclassesSel']]['FAIpartitionTable']))&&($found>0)){
372           msg_dialog(_("Error"), _("There is already a profile containing a partition table in your configuration!") , ERROR_DIALOG);
373         }else{
374           $this->FAIclass[$_POST['FAIclassesSel']]=$_POST['FAIclassesSel'];
375         }
376       }
378       $sort = false;
380       /* Move one used class class one position up or down */
381       if($this->acl_is_writeable("FAIclass")){
382         foreach($_POST as $name => $val){
384           $sort_type = false;
385           if((preg_match("/sort_up/",$name))&&(!$sort)){
386             $sort_type = "sort_up_";
387           }
388           if((preg_match("/sort_down/",$name))&&(!$sort)){
389             $sort_type = "sort_down_";
390           }
392           if(($sort_type)&&(!$sort)){
393             $value = base64_decode(preg_replace("/_.*$/i","",preg_replace("/".$sort_type."/i","",$name)));
394             $sort = true;
396             $last = -1;
397             $change_down  = -1;
399             /* Create array with numeric index */ 
400             $tmp = array();
401             foreach($this->FAIclass as $class){
402               $tmp [] = $class;
403             }
405             /* Walk trough array */
406             foreach($tmp as $key => $faiName){
407               if($faiName == $value){
408                 if($sort_type == "sort_up_"){
409                   if($last != -1){
410                     $change_down= $last;
411                   }
412                 }else{
413                   if(isset($tmp[$key+1])){
414                     $change_down = $key;
415                   }
416                 }
417               }
418               $last = $key;
419             }
421             $tmp2 = array();
422             $skip = false;    
424             foreach($tmp as $ky => $vl){
426               if($ky == $change_down){
427                 $skip = $vl;
428               }else{
429                 $tmp2[$vl] = $vl;
430               }
431               if(($skip != false)&&($ky != $change_down)){
432                 $tmp2[$skip]  = $skip;
433                 $skip =false;
434               }
435             }   
436             $this->FAIclass = $tmp2; 
437           }
439           if(preg_match("/fai_remove/i",$name)){
440             $value = base64_decode(preg_replace("/_.*$/i","",preg_replace("/fai_remove_/i","",$name)));
441             unset($this->FAIclass[$value]);
442           }
443         }
444       }
446       /* Delete selected class from our list */
447       if($this->acl_is_writeable("FAIclass")){
448         if((isset($_POST['DelClass']))&&(isset($_POST['FAIclassSel']))){
449           if(isset($this->FAIclass[$_POST['FAIclassSel']])){
450             unset($this->FAIclass[$_POST['FAIclassSel']]);
451           }
452         }
453       }
454     }// END fai handling
456     /* Show main page */
457     $smarty= get_smarty();
459     /* Assign ACLs to smarty */
460     $tmp = $this->plInfo();
461     foreach($tmp['plProvidedAcls'] as $name => $translation){
462       $smarty->assign($name."ACL",$this->getacl($name));
463     } 
465     $smarty->assign("member_of_ogroup",$this->member_of_ogroup);
467     /* In this section server shares will be defined
468      * A user can select one of the given shares and a mount point
469      *  and attach this combination to his setup.
470      */
471     $smarty->assign("gotoShareSelections",    $this->gotoShareSelections);
472     $smarty->assign("gotoShareSelectionKeys", array_flip($this->gotoShareSelections));
474     /* if $_POST['gotoShareAdd'] is set, we will try to add a new entry
475      * This entry will be, a combination of mountPoint and sharedefinitions
476      */
477     if((isset($_POST['gotoShareAdd'])) && ($this->acl_is_writeable("gotoShare"))) {
478       /* We assign a share to this user, if we don't know where to mount the share */
479       if((!isset($_POST['gotoShareMountPoint']))||(empty($_POST['gotoShareMountPoint']))||(preg_match("/[\|]/i",$_POST['gotoShareMountPoint']))){
480         msg_dialog(_("Error"), msgPool::required(_("Mount point")), ERROR_DIALOG);
481       }else{
482         if(count($this->gotoAvailableShares)){
483           $a_share = $this->gotoAvailableShares[$_POST['gotoShareSelection']];
484           $s_mount = $_POST['gotoShareMountPoint'];
485           /* Preparing the new assignment */
486           $this->gotoShares[$a_share['name']."|".$a_share['server']]=$a_share;
487           $this->gotoShares[$a_share['name']."|".$a_share['server']]['mountPoint']=$s_mount;
488         }
489       }
490     }
492     /* if the Post  gotoShareDel is set, someone asked GOsa to delete the selected entry (if there is one selected)
493      * If there is no defined share selected, we will abort the deletion without any message
494      */
495     if(($this->acl_is_writeable("gotoShare"))&& (isset($_POST['gotoShareDel']))&&(isset($_POST['gotoShare']))){
496       unset($this->gotoShares[$_POST['gotoShare']]);
497     }
499     $smarty->assign("gotoShares",$this->printOutAssignedShares());
500     $smarty->assign("gotoSharesCount",count($this->printOutAssignedShares()));
501     $smarty->assign("gotoShareKeys",array_flip($this->printOutAssignedShares()));
502     $smarty->assign("gotoBootKernels",$this->gotoBootKernels);
504     /* Create divSelectBox for ldap server selection
505      */
506     $SelectBoxLdapServer = new divSelectBox("LdapServer");
507     $SelectBoxLdapServer->SetHeight(130);
509     /* Add new ldap server to the list */
510     if(!$this->gotoLdap_inherit && isset($_POST['add_ldap_server']) && isset($_POST['ldap_server_to_add'])){
511       if(isset($this->gotoLdapServerList[$_POST['ldap_server_to_add']])){
512         $to_add = $this->gotoLdapServerList[$_POST['ldap_server_to_add']];
513         if(!in_array($to_add,$this->gotoLdapServers)){
514           $this->gotoLdapServers[] = $to_add;
515         }
516       }
517     }
518     
519     /* Move ldap servers up and down */
520     if(!$this->gotoLdap_inherit){
521       foreach($_POST as $name => $value){
522         if(preg_match("/sort_ldap_up_/",$name)){
523           $id = preg_replace("/^sort_ldap_up_([0-9]*)_(x|y)$/","\\1",$name);
524           $from =  $id;  
525           $to   =  $id -1;
526           $tmp = $this->array_switch_item($this->gotoLdapServers,$from,$to);
527           if($tmp){
528             $this->gotoLdapServers = $tmp;
529           }
530           break;
531         }
532         if(preg_match("/sort_ldap_down_/",$name)){
533           $id = preg_replace("/^sort_ldap_down_([0-9]*)_(x|y)$/","\\1",$name);
534           $from =  $id;  
535           $to   =  $id +1;
536           $tmp = $this->array_switch_item($this->gotoLdapServers,$from,$to);
537           if($tmp){
538             $this->gotoLdapServers = $tmp;
539           }
540           break;
541         }
542         if(preg_match("/gotoLdapRemove_/",$name)){
543           $id = preg_replace("/^gotoLdapRemove_([0-9]*)_(x|y)$/","\\1",$name);
544           $value = $this->gotoLdapServers[$id];
545           $this->gotoLdapServers = array_remove_entries(array($value),$this->gotoLdapServers);
546           break;
547         }
548       } 
549     }
550   
551     /* Add Entries */
552     foreach($this->gotoLdapServers as $key => $server){
553       /* Announce missing entries */
554       if(!in_array($server,$this->gotoLdapServerList)){
555         $server = $server."&nbsp;<font style='color:red'>(missing)</font>";
556       }
558       /* Convert old style entry */
559       if (!preg_match('%:ldap://%', $server)){
560         $server= "ldap://".preg_replace('/^([^:]+):/', '\1/', $server);
562       /* Beautify new style entries */
563       } else {
564         $server= preg_replace("/^[^:]+:/", "", $server);
565       }
567       $SelectBoxLdapServer->AddEntry(
568           array(array("string" => $server),
569             array("string" => 
570               "<input class='center' type='image' src='images/sort_up.png' name='sort_ldap_up_".$key."'>&nbsp;".
571               "<input class='center' type='image' src='images/sort_down.png' name='sort_ldap_down_".$key."'>&nbsp;".
572               "<input class='center' type='image' src='images/edittrash.png' name='gotoLdapRemove_".$key."'>",
573               "attach" => "style='text-align:right;width:40px;border-right:0px;'")));
574     }    
576     if($this->gotoLdap_inherit){
577       $smarty->assign("gotoLdapServerACL_inherit", preg_replace("/w/","",$this->getacl("gotoLdapServer")));;
578     }else{
579       $smarty->assign("gotoLdapServerACL_inherit", $this->getacl("gotoLdapServer"));
580     }
581     
582     $list = array();
583     foreach($this->gotoLdapServerList as $key => $entry){
584       if(!in_array($entry,$this->gotoLdapServers)){
586         /* Convert old style entry */
587         if (!preg_match('%:ldap://%', $entry)){
588           $entry= "ldap://".preg_replace('/^([^:]+):/', '\1/', $entry);
590         /* Beautify new style entries */
591         } else {
592           $entry= preg_replace("/^[^:]+:/", "", $entry);
593         }
595         $list[$key] = $entry;
596       }
597     }
598     $smarty->assign("gotoLdapServers",    $SelectBoxLdapServer->DrawList());
599     $smarty->assign("gotoLdapServerList", $list);
600     $smarty->assign("gotoLdap_inherit",   $this->gotoLdap_inherit);
601     $smarty->assign("JS",  session::get('js'));
603     foreach (array("gotoModules", "gotoAutoFs", "gotoFilesystem") as $val){
604       $smarty->assign("$val", $this->$val);
605     }
607     /* Values */
608     foreach(array("gotoBootKernel", "customParameters", "gotoShare","FAIclasses","FAIclass","FAIdebianMirror","FAIrelease") as $val){
609       $smarty->assign($val, $this->$val);
610     }
612     $smarty->assign("fai_activated",$this->fai_activated);
614     /* Create FAI output */
615     $this->update_fai_cache();
616     $smarty->assign("si_fai_action_failed",$this->si_fai_action_failed);
617     $smarty->assign("si_active",$this->si_active);
618   
619     if(!$this->si_fai_action_failed && $this->si_active && $this->fai_activated){
621       $smarty->assign("FAIservers"  , $this->cache['SERVERS']);
622       $smarty->assign("FAIdebianMirror",$this->FAIdebianMirror);
623       $smarty->assign("FAIrelease"  , $this->FAIrelease);
624       $smarty->assign("FAIclasses"  , $this->selectable_classes());
626       $smarty->assign("InheritedFAIrelease",$this->InheritedFAIrelease);
628       $div = new divSelectBox("WSFAIscriptClasses");
629       $div -> SetHeight("110");
630       $str_up     = " &nbsp;<input type='image' src='images/sort_up.png'    name='sort_up_%s'    value='%s'>";
631       $str_down   = " &nbsp;<input type='image' src='images/sort_down.png'  name='sort_down_%s'  value='%s'>";
632       $str_remove = " &nbsp;<input type='image' src='images/edittrash.png'  name='fai_remove_%s' value='%s'>";
633       $str_empty  = " &nbsp;<img src='images/empty.png' alt=\"\" width='7'>"; 
635       /* Get classes */
636       if($this->FAIdebianMirror == "inherited"){
637         $tmp = $this->InheritedFAIclass;
638       }else{
639         $tmp = $this->FAIclass;
640       }
642       /* Get invalid classes */
643       $invalid = $this->get_invalid_classes($tmp);
645       /* Draw every single entry */
646       $i = 1;
647       foreach($tmp as $class){
649         /* Mark invalid classes. (Not in selected release)
650          */
651         $marker = "";
652         if(in_array_ics($class,$invalid)){
653           $marker = "&nbsp;<font color='red'>("._("Not available in current setup").")</font>";
654         }
656         /* Create up/down priority icons  
657          * Skip this, if we have inherited the FAI classes.
658          */
659         if($this->FAIdebianMirror == "inherited"){
660           $str = "";
661         }else{
662           if($i==1){
663             $str = $str_empty.$str_down.$str_remove;
664           }elseif($i == count($this->FAIclass)){
665             $str = $str_up.$str_empty.$str_remove;
666           }else{
667             $str = $str_up.$str_down.$str_remove;
668           }
669         }
670         $i ++ ; 
672         /* Get Description tag 
673          *  There may be several FAI objects with the same class name, 
674          *   use the description from FAIprofile, if possible.
675          */  
676         $desc = ""; 
677         if(isset($this->cache['CLASSES'][$this->FAIrelease][$class])){
678           foreach($this->cache['CLASSES'][$this->FAIrelease][$class] as $types ){
679             if(isset($types['Desc'])){
680               $desc= $types['Desc'];
681               if($types['Type'] == "FAIprofile"){
682                 break;
683               }
684             }
685           }
686         }
687         if(!empty($desc)){
688           $desc = "&nbsp;[".trim($desc)."]";
689         }        
691         $div->AddEntry(array(
692               array("string"=>$class.$desc.$marker),
693               array("string"=>preg_replace("/\%s/",base64_encode($class),$str),"attach"=>"style='width:50px;border-right:none;'")
694               ));
695       }  
696       $smarty->assign("FAIScriptlist",$div->DrawList()); 
697     }// END FAI output generation 
699     /* Radio button group */
700     if (preg_match("/G/", $this->bootmode)) {
701       $smarty->assign("graphicalbootup", "checked");
702     } else {
703       $smarty->assign("graphicalbootup", "");
704     }
705     if (preg_match("/T/", $this->bootmode)) {
706       $smarty->assign("textbootup", "checked");
707     } else {
708       $smarty->assign("textbootup", "");
709     }
710     if (preg_match("/D/", $this->bootmode)) {
711       $smarty->assign("debugbootup", "checked");
712     } else {
713       $smarty->assign("debugbootup", "");
714     }
716     /* Show main page */
717     return($smarty->fetch (get_template_path('workstationStartup.tpl', TRUE,dirname(__FILE__))));
718   }
721   function remove_from_parent()
722   {
723     $this->handle_post_events("remove");
724     new log("remove","workstation/".get_class($this),$this->dn);
725   }
728   /* Save data to object */
729   function save_object()
730   {
731     $old_mirror  = $this->FAIdebianMirror;
732     plugin::save_object();
734     /* Update release */
735     if($old_mirror != $this->FAIdebianMirror){
736       if(!isset($this->cache['SERVERS'][$this->FAIdebianMirror][$this->FAIrelease])){
737         $this->FAIrelease      = key($this->cache['SERVERS'][$this->FAIdebianMirror]);
738       }
739     }
741     if(isset($_POST['WorkstationStarttabPosted'])){
742       if(isset($_POST['gotoLdap_inherit'])){
743         $this->gotoLdap_inherit = TRUE;
744       }else{
745         $this->gotoLdap_inherit = FALSE;
746       }
748       /* Save group radio buttons */
749       if ($this->acl_is_writeable("bootmode") && isset($_POST["bootmode"])){
750         $this->bootmode= $_POST["bootmode"];
751       }
753       /* Save kernel parameters */
754       if ($this->acl_is_writeable("gotoKernelParameters") && isset($_POST["customParameters"])){
755         $this->customParameters= $_POST["customParameters"];
756       }
757     }
758   }
761   /* Save to LDAP */
762   function save()
763   {
765     /* Depending on the baseobject (Ogroup / WS) we
766      *  use another set of objectClasses
767      * In case of WS itself, we use  "array("GOhard", "FAIobject");"
768      * if we are currently editing from ogroup menu we use (array("gotWorkstationTemplate","GOhard", "FAIobject"))
769      */
770     if(isset($this->parent->by_object['ogroup'])){
771       $this->objectclasses = array("gotoWorkstationTemplate");
772     }elseif(isset($this->parent->by_object['workgeneric'])){
773       $this->objectclasses = array("GOhard");
774     }elseif(isset($this->parent->by_object['servgeneric'])){
775       $this->objectclasses = array("GOhard","gotoWorkstationTemplate");
776     }else{
777       print "Object Type Configuration : unknown";
778       exit();
779     }
781     /* Append FAI class */
782     if($this->fai_activated){
783       $this->objectclasses[]  = "FAIobject";
784     }
786     /* Find proper terminal path for tftp configuration
787        FIXME: This is suboptimal when the default has changed to
788        another location! */
789     if (($this->gotoTerminalPath == "default")){
790       $ldap= $this->config->get_ldap_link();
792       /* Strip relevant part from dn, keep trailing ',' */
793       $tmp= preg_replace("/^cn=[^,]+,".get_ou('terminalou')."/i", "", $this->dn);
794       $tmp= preg_replace("/".$this->config->current['BASE']."$/i", "", $tmp);
796       /* Walk from top to base and try to load default values for
797          'gotoTerminalPath'. Abort when an entry is found. */
798       while (TRUE){
799         $tmp= preg_replace ("/^[^,]+,/", "", $tmp);
801         $ldap->cat("cn=default,".get_ou('terminalou').$tmp.
802             $this->config->current['BASE'], array('gotoTerminalPath'));
803         $attrs= $ldap->fetch();
804         if (isset($attrs['gotoTerminalPath'])){
805           $this->gotoTerminalPath= $attrs['gotoTerminalPath'][0];
806           break;
807         }
809         /* Nothing left? */
810         if ($tmp == ""){
811           break;
812         }
813       }
814     }
816     /* Add semi automatic values */
817     // FIXME: LDAP Server may not be set here...
818     $this->gotoKernelParameters= "ldap=".base64_encode($this->gotoLdapServer);
820     switch ($this->bootmode){
821       case "D":
822         $this->gotoKernelParameters.= " debug";
823       break;
824       case "G":
825         $this->gotoKernelParameters.= " splash=silent";
826       break;
827     }
828     if ($this->customParameters != ""){
829       $this->gotoKernelParameters.= " o ".$this->customParameters;
830     }
832     plugin::save();
834     unset( $this->attrs['FAIrelease'] );
835     $str = "";
837     /* Skip FAI attribute handling if not necessary */
838     if($this->fai_activated && !$this->si_fai_action_failed){
839       if($this->FAIdebianMirror == "inherited"){
840         $this->attrs['FAIclass'] = $this->attrs['FAIrelease'] =  $this->attrs['FAIdebianMirror'] = array();
841       }else{
842         foreach($this->FAIclass as $class){
843           $str .= $class." ";
844         }
845         $str = trim($str);
846         if(empty($this->attrs['FAIclass'])){
847           $this->attrs['FAIclass'] = array();
848         }else{
849           $this->attrs['FAIclass']= $str." :".$this->FAIrelease;
850         }
851       }
852     }
854     /* Add missing arrays */
855     foreach (array("gotoFilesystem", "gotoAutoFs", "gotoModules") as $val){
856       if (isset ($this->$val) && count ($this->$val) != 0){
857     
858         $this->attrs["$val"]= array_unique($this->$val);
859       }
860       if(!isset($this->attrs["$val"])) $this->attrs["$val"]=array();
861     }
863     /* Prepare list of ldap servers */
864     $this->attrs['gotoLdapServer'] = array();
865     if(!$this->gotoLdap_inherit){
866       $i = 0;
867       foreach($this->gotoLdapServers as $server){
868         $i ++;
869         $this->attrs['gotoLdapServer'][] = $i.":".$server;
870       }
871     }
873     if (($this->attrs['gotoBootKernel'] == "default-inherited") || ($this->attrs['gotoBootKernel'] == "%default%")){
874       $this->attrs['gotoBootKernel']= array();
875     }
877     /* if mirror == none stop saving this attribute */
878     if($this->FAIdebianMirror == "none"){
879       $this->FAIdebianMirror = "";
880     }
881    
882     /* Get FAIstate from object, the generic tab could have changed it during execute */
883     $ldap= $this->config->get_ldap_link();
884     $ldap->cd($this->dn);
887     /* Skip FAI attribute handling if not necessary */
888     if($this->fai_activated && !$this->si_fai_action_failed && $this->si_active){
889       $ldap->cat($this->dn,array("FAIstate"));
890       $checkFAIstate = $ldap->fetch();
892       /* Remove FAI objects if no FAI class is selected */ 
893       if((count($this->FAIclass)==0) && (!isset($checkFAIstate['FAIstate']))){
894         $this->attrs['FAIclass']        = array();
895         $this->attrs['FAIdebianMirror'] = array();
896       }
897     }
900     /* prepare share settings */
901     $tmp = array();
902     foreach($this->gotoShares as $name => $settings){
903       $tmp2= split("\|",$name);
904       $name = $tmp2[0];
905       $tmp[] = $settings['server']."|".$name."|".$settings['mountPoint'];
906     }
907     $this->attrs['gotoShare']=$tmp;
908     $this->cleanup();
909     $ldap->modify ($this->attrs); 
910     new log("modify","workstation/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
912     if (!$ldap->success()){
913       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
914     }
915     $this->handle_post_events("modify");
917     /* Check if LDAP server has changed */
918     if (isset($this->attrs['gotoLdapServer']) && class_available("DaemonEvent")){
919       $events = DaemonEvent::get_event_types(SYSTEM_EVENT | HIDDEN_EVENT);
920       $o_queue = new gosaSupportDaemon();
921       if(isset($events['TRIGGERED']['DaemonEvent_reload_ldap_config'])){
922         $evt = $events['TRIGGERED']['DaemonEvent_reload_ldap_config'];
923         $macs = array();
924     
925         /* Get list of macAddresses 
926          */
927         if(isset($this->parent->by_object['ogroup'])){
928         
929           /* If we are an object group, add all member macs 
930            */
931           $p = $this->parent->by_object['ogroup'];
932           foreach($p->memberList as $dn => $obj){
933             if(isset($p->objcache[$dn]['macAddress']) && !empty($p->objcache[$dn]['macAddress'])){
934               $macs[] = $p->objcache[$dn]['macAddress'];
935             }
936           }
937         }elseif(isset($this->parent->by_object['workgeneric']->netConfigDNS->macAddress)){
939           /* We are a workstation. Add current mac.
940            */
941           $mac = $this->parent->by_object['workgeneric']->netConfigDNS->macAddress;
942           if(!empty($mac)){
943             $macs[] = $mac;
944           }          
945         }
947         /* Trigger event for all member objects 
948          */
949         foreach($macs as $mac){
950           $tmp = new $evt['CLASS_NAME']($this->config);
951           $tmp->set_type(TRIGGERED_EVENT);
952           $tmp->add_targets(array($mac));
953           if(!$o_queue->append($tmp)){
954             msg_dialog::display(_("Service infrastructure"),msgPool::siError($o_queue->get_error()),ERROR_DIALOG);
955           }
956         }
957       }
958     }
959   }
962   /* Add value to array, check if unique */
963   function add_list (&$array, $value)
964   {
965     if ($value != ""){
966       $array[]= $value;
967       sort($array);
968       array_unique ($array);
969     }
970   }
973   /* Delete value to array, check if unique */
974   function del_list (&$array, $list)
975   {
976     $tmp= array();
977     foreach ($array as $mod){
978       if (!in_array($mod, $list)){
979         $tmp[]= $mod;
980       }
981     }
982     $array= $tmp;
983   }
985   /* Generate ListBox frindly output for the defined shares
986    * Possibly Add or remove an attribute here,
987    */
988   function printOutAssignedShares()
989   {
990     $a_return = array();
991     if(is_array($this->gotoShares)){
992       foreach($this->gotoShares as $share){
993         $a_return[$share['name']."|".$share['server']]= $share['name']." [".$share['server']."]";
994       }
995     }
996     return($a_return);
997   }
1001   function PrepareForCopyPaste($source)
1002   {
1003     plugin::PrepareForCopyPaste($source);    
1004     $source_o = new workstartup ($this->config, $source['dn']);
1005     foreach(array("FAIclass","gotoModules", "gotoAutoFs", "gotoFilesystem",
1006           "gotoKernelParameters","gotoShares","customParameters") as $attr){
1007       $this->$attr = $source_o->$attr;
1008     }
1009   }
1011   
1012   function array_switch_item($ar,$from,$to)
1013   {
1014     if(!is_array($ar)){
1015       return(false);
1016     }
1017     if(!isset($ar[$from])){
1018       return(false);
1019     }
1020     if(!isset($ar[$to])){
1021       return(false);
1022     }
1024     $tmp = $ar[$from];
1025     $ar[$from] = $ar[$to];    
1026     $ar[$to] = $tmp;    
1027     return($ar);
1028   }
1031   /* Return plugin informations for acl handling */ 
1032   static function plInfo()
1033   {
1034     return (array( 
1035           "plShortName"   => _("Startup"),
1036           "plDescription" => _("System startup"),
1037           "plSelfModify"  => FALSE,
1038           "plDepends"     => array(),
1039           "plPriority"    => 9,
1040           "plSection"     => array("administration"),           
1041           "plCategory"    => array("workstation","server","ogroups"),
1043           "plProvidedAcls"=> array(
1044             "gotoLdapServer"        => _("Ldap server"),
1045             "gotoBootKernel"        => _("Boot kernel"),
1046             "gotoKernelParameters"  => _("Kernel parameter"),
1048             "gotoModules"           => _("Kernel modules"),
1049             "gotoShare"             => _("Shares"),
1051             "FAIclass"              => _("FAI classes"),
1052             "FAIdebianMirror"       => _("Debian mirror"),
1053             "FAIrelease"            => _("Debian release"),
1055             "FAIstatus"             => _("FAI status flag")) // #FIXME is this acl realy necessary ?
1056           ));
1057   }
1060   /* Updates release dns 
1061    *  and reads all classes for the current release, 
1062    *  if not already done ($this->cache).
1063    */
1064   function update_fai_cache($first_call = FALSE)
1065   {
1066     $force = FALSE;
1067     if(!$this->si_active) return; 
1068     $start = microtime(TRUE);  
1070     if($this->si_fai_action_failed && !isset($_POST['fai_si_retry'])) return;
1072     $this->si_fai_action_failed = FALSE;
1074     /* Get the list of available servers and their releases. 
1075      */
1076     if($force || !isset($this->cache['SERVERS'])){
1078       /* Only add inherit option, if we are part in an object group
1079        */
1080       if($this->member_of_ogroup){
1081         $this->cache['SERVERS']['inherited']=array();
1082       }
1084       $o_queue = new gosaSupportDaemon();
1085       $tmp = $o_queue->FAI_get_server(); 
1086       if($o_queue->is_error()){
1087         msg_dialog::display(_("Service infrastructure"),msgPool::siError($o_queue->get_error()),ERROR_DIALOG);
1088         $this->si_fai_action_failed = TRUE;
1089         $this->cache = array();
1090         return;
1091       }else{
1092         foreach($tmp as $entry){
1093           $rel = $entry['RELEASE'];
1094           $this->cache['SERVERS']['auto'][$rel] = $rel;
1095           $this->cache['SERVERS'][$entry['SERVER']][$rel] = $rel;
1096         }
1097       }
1098     }
1100     /* Build up arrays, without checks */
1101     if(!$first_call){
1103       /* Check if the selected mirror is available */
1104       if(!isset($this->cache['SERVERS'][$this->FAIdebianMirror])){
1105         $this->FAIdebianMirror = "auto";
1106         $this->FAIrelease      = key($this->cache['SERVERS'][$this->FAIdebianMirror]);
1107         trigger_error("There was a problem with the selected FAIdebianMirror. This mirror ('".$this->FAIdebianMirror."') is not available");
1108       }
1110       /* Check if the selected release is available */
1111       if($this->FAIdebianMirror != "inherited" && !isset($this->cache['SERVERS'][$this->FAIdebianMirror][$this->FAIrelease])){
1112         trigger_error("There was a problem with the selected FAIrelease. This release ('".$this->FAIrelease."') is not available");
1113         $this->FAIrelease = key($this->cache['SERVERS'][$this->FAIdebianMirror]);
1114       }
1115     }
1117     /* Get classes for release from cache. 
1118      * Or build cache
1119      */
1120     if($this->FAIdebianMirror == "inherited"){
1121       $release = $this->InheritedFAIrelease;
1122     }else{
1123       $release = $this->FAIrelease;
1124     }
1126     if($force || !isset($this->cache['CLASSES'][$release])){
1128       /* Get the list of available servers and their releases.
1129        */
1130       $o_queue = new gosaSupportDaemon();
1131       $tmp = $o_queue->FAI_get_classes($release);
1132       $this->cache['CLASSES'][$release] = array();
1133       if($o_queue->is_error()){
1134         msg_dialog::display(_("Service infrastructure"),msgPool::siError($o_queue->get_error()),ERROR_DIALOG);
1135         $this->si_fai_action_failed = TRUE;
1136         $this->cache=array();
1137         return;
1138       }else{
1139         foreach($tmp as $entry){
1140           $class = $entry['CLASS'];
1141           $this->cache['CLASSES'][$release][$class] = $this->analyse_fai_object($entry); 
1142         }
1143       }
1145       /* Add object caught from external hook
1146        */
1147       $lines= $this->GetHookElements();
1148       foreach ($lines as $hline){
1149         $entries= split(";", $hline);
1150         $server = $entries['0'];
1151         $url    = $entries['1'];
1152         if (!empty($url)){
1154           /* Split releases */
1155           if (isset($entries[2])){
1156             $releases= split(",", $entries[2]);
1158             foreach ($releases as $release_data){
1159               $release_c  = preg_replace('/:.*$/', '', $release_data);
1160               $sections_c = split(':', preg_replace('/^[^:]+:([^|]+)|.*$/', '\1', $release_data));
1161               $classes_c  = split('\|', preg_replace('/^[^|]+\|(.*)$/', '\1', $release_data));
1163               if($release_c == $release){
1164                 $this->cache['SERVERS'][$url][$release_c]=$release_c;
1165                 $this->cache['SERVERS']['auto'][$release_c]=$release_c; 
1166                 foreach ($classes_c as $class){
1167                   if ($class != ""){
1168                     $this->cache['CLASSES'][$release_c][$class]= array();
1169                   }
1170                 }
1171               }
1172             }
1173           }
1174         }
1175       }
1176     }
1177 #    echo sprintf("Took %.6f <br> ",microtime(1) - $start);
1178   }
1181   /* This function return an array containing all 
1182    *  invalid classes for the selected server/release
1183    */
1184   function get_invalid_classes($classes)
1185   {
1186     $this->update_fai_cache();
1187     if($this->FAIdebianMirror == "inherited"){
1188       $release_classes = $this->cache['CLASSES'][$this->InheritedFAIrelease];
1189     }else{
1190       $release_classes = $this->cache['CLASSES'][$this->FAIrelease];
1191     }
1194     /* Detect all classes that are not valid 
1195      *  for the selected release 
1196      */
1197     $NA = array();
1198     foreach($classes as $class){
1199       if(!isset($release_classes[$class])){
1200         $NA[] = $class;
1201       }
1202     }
1203     return($NA);
1204   }  
1206   
1207   /* Get all selectable classes for the ui select box
1208    */
1209   function selectable_classes()
1210   {
1211     $this->update_fai_cache();
1213     if($this->FAIdebianMirror == "inherited"){
1214       $classes = $this->cache['CLASSES'][$this->InheritedFAIrelease];
1215     }else{
1216       $classes = $this->cache['CLASSES'][$this->FAIrelease];
1217     }
1219     $Abbr ="";
1220     $ret= array();
1221     foreach($classes as $class_name => $class_types){
1222       if(!in_array($class_name,$this->FAIclass)){
1223         foreach($class_types as $type){
1224           if(!preg_match("/".$type['Abbr']."/",$Abbr)){
1225             $Abbr .= $type['Abbr']." ";
1226           }
1227         }
1228         $ret[$class_name] = trim($Abbr);
1229       }
1230     }
1231     uksort($ret, 'strnatcasecmp');
1232     return($ret);
1233   }
1236   /* Analyse FAI object and return an array with usefull informations like 
1237    *  FAIobject type.
1238    */
1239   function analyse_fai_object($attr)
1240   {
1241     $tmp = array();
1242     switch($attr['TYPE']){
1244       case 'FAIpackageList':
1245         $tmp["Type"]= 'FAIpackageList';
1246         $tmp["Abbr"]= 'Pl';
1247         break;
1248       case 'FAItemplate': 
1249         $tmp["Type"]= 'FAItemplate'; 
1250         $tmp["Abbr"]= 'T'; 
1251         break;
1252       case 'FAIvariable':
1253         $tmp["Type"]= 'FAIvariable'; 
1254         $tmp["Abbr"]= 'V'; 
1255         break;
1256       case 'FAIscript':
1257         $tmp["Type"]= 'FAIscript'; 
1258         $tmp["Abbr"]= 'S'; 
1259         break;
1260       case 'FAIhook':
1261         $tmp["Type"]= 'FAIhook'; 
1262         $tmp["Abbr"]= 'H'; 
1263         break;
1264       case 'FAIpartitionTable':
1265         $tmp["Type"]= 'FAIpartitionTable'; 
1266         $tmp["Abbr"]= 'Pt'; 
1267         break;
1268       case 'FAIprofile':
1269         $tmp["Type"]= 'FAIprofile'; 
1270         $tmp["Abbr"]= 'P'; 
1271         break;
1272       default: trigger_error("Unknown FAI object type!");;
1273     }
1274     return($tmp);
1275   }
1278   /* Return repository hook output, if possible.
1279    */
1280   function GetHookElements()
1281   {
1282     $ret = array();
1283     $cmd= $this->config->search("servrepository", "REPOSITORY_HOOK",array('tabs'));
1284     if(!empty($cmd)){
1285       $res = shell_exec($cmd);
1286       $res2 = trim($res);
1287       if((!$res)){
1288         msg_dialog(_("Configuration error"), msgPool::cmdexecfailed("REPOSITORY_HOOK", $cmd), ERROR_DIALOG);
1289       }elseif(empty($res2)){
1290         msg_dialog(_("Configuration error"), _("REPOSITORY_HOOK returned no result!"), ERROR_DIALOG);
1291       }else{
1292         $tmp = split("\n",$res);
1293         foreach($tmp as $line){
1294           if(empty($line)) continue;
1295           $ret[]= $line;
1296         }
1297       }
1298     }
1299     return($ret);
1300   }
1303   /* This function creates the release name out of a dn 
1304    *  e.g. "ou=1.0rc2,ou=siga,ou=fai,..." => "siga/1.0rc2"
1305    */
1306   function dn_to_release_name($dn)
1307   {
1308     $relevant = preg_replace("/,".normalizePreg(get_ou("faiou")).".*$/","",$dn);
1309     $parts    = array_reverse(split("\,",$relevant));
1310     $str ="";
1311     foreach($parts as $part){
1312       $str .= preg_replace("/^ou=/","",$part)."/";
1313     }
1314     return(preg_replace("/\/$/","",$str)); 
1315   }
1318 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1319 ?>