Code

Fixed copy'n paste problem in FAI. Closes #842
[gosa.git] / gosa-plugins / fai / admin / fai / class_faiManagement.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: class_faiManagement.inc 14742 2009-11-04 13:18:33Z hickert $$
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 class faiManagement extends management
24 {
25   var $plHeadline     = "Software deployment";
26   var $plDescription  = "Manage software packages and deployment reciepes";
27   var $plIcon  = "plugins/fai/images/plugin.png";
29   // Tab definition 
30   protected $tabClass = "";
31   protected $tabType = "";
32   protected $aclCategory = "";
33   protected $aclPlugin   = "";
34   protected $objectName   = "FAI object";
36   //  Attributes Managed by this plugin can be used in post events
37   public $attributes   = array("lock_type","lock_name","lock_dn");  
39   var $dispNewBranch=false;
40   var $dispNewFreeze=false;
42   var $fai_release = ""; // The currently selected release while in release management mode!
43   var $fai_base = ""; 
44   var $acl_base = ""; 
46   var $lock_type = "";
47   var $lock_dn = "";
48   var $lock_name = "";
50   var $opsi = NULL;
53   function __construct($config,$ui)
54   {
55     $this->config = $config;
57     /* Check if the opsi plugin is installed.
58      */
59     if(class_available("opsi")){
60       $this->opsi = new opsi($this->config);;
61     }
63     $this->fai_base = get_ou("faiBaseRDN").$this->config->current['BASE'];
64     $cfg_rel = $this->config->search("faiManagement","DEFAULTFAIRELEASE",array("menu"));
65     if(!empty($cfg_rel)){
66       $this->fai_release = $cfg_rel;
67     }else{
68       $this->fai_release = $this->fai_base;
69     }
71     $releases = $this->getReleaseList();
72     if(!isset($releases[$this->fai_release])){
73       $this->fai_release = $this->fai_base;
74     }
76     $this->acl_base = $this->config->current['BASE'];
77     $this->ui = $ui;
78     $this->storagePoints = array(
79         get_ou('faiPartitionRDN'),
80         get_ou('faiPackageRDN'),
81         get_ou('faiScriptRDN'),
82         get_ou('faiVariableRDN'),
83         get_ou('faiHookRDN'),
84         get_ou('faiProfileRDN'),
85         get_ou('faiTemplateRDN'));
87     // Build filter
88     if (session::global_is_set(get_class($this)."_filter")){
89       $filter= session::global_get(get_class($this)."_filter");
90     } else {
91       $filter = new filter(get_template_path("fai-filter.xml", true));
92       $filter->setObjectStorage($this->storagePoints);
93     }
94     $filter->elementValues['RELEASE'] = $this->fai_release;
95     $this->setFilter($filter);
97     // Build headpage
98     $headpage = new listing(get_template_path("fai-list.xml", true));
99     $headpage->setFilter($filter);
100     $headpage->setBase($this->fai_release);
101     $headpage->registerElementFilter("filterProperties", "faiManagement::filterProperties");
103     // Add copy&paste and snapshot handler.
104     if ($this->config->boolValueIsTrue("main", "copyPaste")){
105       $this->cpHandler = new CopyPasteHandler($this->config);
106     }
108     $this->registerAction("remove_multiple","removeEntryRequested");
109     $this->registerAction("new_profile","newEntry");
110     $this->registerAction("new_template","newEntry");
111     $this->registerAction("new_script","newEntry");
112     $this->registerAction("new_hook","newEntry");
113     $this->registerAction("new_variable","newEntry");
114     $this->registerAction("new_package","newEntry");
115     $this->registerAction("new_partition","newEntry");
116     $this->registerAction("newClassNameSelected","newClassNameSelected");
117     $this->registerAction("saveOpsiProperties","saveOpsiProperties");
118     $this->registerAction("editByGroup","editByGroup");
119     $this->registerAction("createBranch","createBranch");
120     $this->registerAction("createFreeze","createFreeze");
121     $this->registerAction("removeBranch","removeBranch");
122     $this->registerAction("removeBranchConfirmed","removeBranchConfirmed");
123     $this->registerAction("saveBranch","saveBranch");
124     $this->registerAction("PerformBranch","PerformBranch");
126     parent::__construct($config, $ui, "FAI object", $headpage);
127   }
130   /*! \brief  Act on copy & paste actions here.
131    */
132   function copyPasteHandler($action="",$target=array(),$all=array(),$altTabClass ="",$altTabType="",$altAclCategory="",$altAclPlugin="")
133   {
134     // Collect real dns, the listed objects are grouped by their cn
135     $headpage = $this->getHeadpage();
136     if($action == "copy"){
138       if(count($target) == 1){
140         // We just want to copy a single FAI object, let the user choose entries from the FAI-Group
141         $entry = $headpage->getEntry($target[0]);
142         if(count($entry['GROUPS']) == 1){
143           $data = array_pop($entry['GROUPS']);
144           $type = $this->get_type($data);
145           $this->cpHandler->add_to_queue($g['dn'],"copy",$type[0],$type[2],'fai',$this);
146           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,$g['dn'],"Entry copied!");
147         }else{
148           $this->dialogObject = new faiGroupHandle($entry['GROUPS'],"copy");
149         }
150         
151       }else{
153         // More than one group was selected, expect that the user wants to copy the complete groups.
154         foreach($target as $t){
155           $entry = $headpage->getEntry($t);
157           // Check for valid FAI objects
158           if(in_array('FAKE_OC_FAI', $entry['objectClass'])){
159             foreach($entry['GROUPS'] as $g){
160               $type = $this->get_type($g);
161               $this->cpHandler->add_to_queue($g['dn'],"copy",$type[0],$type[2],'fai',$this);
162               @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,$g['dn'],"Entry copied!");
163             }
164           }
165         }
166       }
167     }
169     // Initiate pasting
170     if($action == "paste"){
171       $this->cpPastingStarted = TRUE;
172     }
174     // Display any c&p dialogs, eg. object modifications required before pasting.
175     if($this->cpPastingStarted && $this->cpHandler->entries_queued()){
176       $this->cpHandler->SetVar("base",$headpage->getBase());
177       $data = $this->cpHandler->execute();
178       FAI::save_release_changes_now();
179       if(!empty($data)){
180         return($data);
181       }
182     }
184     // Automatically disable pasting process since there is no entry left to paste.
185     if(isset($this->cpHandler) && !$this->cpHandler->entries_queued()){
186       $this->cpPastingStarted = FALSE;
187     }
188     return("");
189   }
192   /*! \brief  A new FAI object was requested, let the user specify a name theis object now. 
193    */
194   function newEntry($action="",$target=array(),$all=array(), $altTabClass ="", $altTabType = "", $altAclCategory="")
195   {
196     $types = array( 
197         "new_partition"     =>  "FAIpartitionTable",
198         "new_script"        =>  "FAIscript",
199         "new_hook"          =>  "FAIhook",
200         "new_variable"      =>  "FAIvariable",
201         "new_template"      =>  "FAItemplate",
202         "new_package"       =>  "FAIpackageList");
203     $types_i18n = array( 
204         "new_partition"     =>  _("partition table"),
205         "new_script"        =>  _("script"),
206         "new_hook"          =>  _("hook"),
207         "new_variable"      =>  _("variable"),
208         "new_template"      =>  _("template"),
209         "new_package"       =>  _("package list"));
211     if(isset($types[$action])){
212       $type_acl_mapping = array(
213           "FAIpartitionTable"  => "faiPartitionTable",
214           "FAIpackageList"     => "faiPackage",
215           "FAIscript"          => "faiScript",
216           "FAIvariable"        => "faiVariable",
217           "FAIhook"            => "faiHook",
218           "FAIprofile"         => "faiProfile",
219           "FAItemplate"        => "faiTemplate");
221       $acl = $this->ui->get_permissions($this->acl_base,"fai/".$type_acl_mapping[$types[$action]]);
222       if(preg_match("/c/",$acl)){
223         $this->dialogObject = new askClassName($this->config,$this->dn,$this->ui,$types[$action]);
224         $this->dialogObject->parent = &$this;
225       }else{
226         msg_dialog::display(_("Permission error"), 
227             sprintf(_("You have no permission to create a new %s!"), $types_i18n[$action]),      ERROR_DIALOG);
228       }
229     }
230     if($action == "new_profile"){
231       $this->dn = "new" ;
233       $acl = $this->ui->get_permissions($this->acl_base,"fai/faiProfile");
234       if(preg_match("/c/",$acl)){
235         $type= $this->get_type(array("objectClass"=>array("FAIprofile")));
236         $str= management::newEntry('newEntry',array(),array(),$type[0],$type[2],$type[1]);
237         if($str) return($str);
238         $this->tabObject->set_acl_base($this->acl_base);
239         $this->tabObject->by_object[$type[1]]->cn = $name;
240       }else{
241         msg_dialog::display(_("Permission error"), sprintf(_("You have no permission to create a new %s!"), _("profile")), ERROR_DIALOG);
242       }
243     }
244   }
247   /*! \brief   A new FAI class was requested and the user had a specify a name for it.
248    *           Here we check if this name is useable and then open the edit dialogs.
249    */
250   function newClassNameSelected()
251   {
252     $this->dialogObject->save_object();
253     if(count($this->dialogObject->check())!=0){
254       foreach($this->dialogObject->check() as $msg){
255         msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
256       }
257     }elseif(isset($this->dialogObject->objectClass)){
258       $this->dn = "new" ;
259       $type= $this->get_type(array("objectClass"=>array($this->dialogObject->objectClass)));
260       $name = $this->dialogObject->save();
262       if(class_exists($type[0])){
263         $this->closeDialogs();
264         $str = management::newEntry('newEntry',array(),array(),$type[0],$type[2],$type[1]);
265         if($str) return($str);
266         $this->tabObject->set_acl_base($this->acl_base);
267         $this->tabObject->by_object[$type[1]]->cn = $name;
268       }
269     }
270   }
273   /*! \brief   Edit the selected entry.
274    *           If there was a FAI group clicked, display a dialog with all members of the group.
275    */
276   function editEntry($action="",$target=array(),$all=array(), $altTabClass ="", $altTabType = "", $altAclCategory="")
277   {
278     $headpage = $this->getHeadpage();
279     if(count($target) == 1){
280       $entry = $headpage->getEntry($target[0]);
281       if($entry){
283         // Edit Opsi objects here 
284         if(in_array("opsi_local", $entry['TYPES']) || in_array("opsi_netboot", $entry['TYPES'])){ 
285           $name = $entry['cn'];
286           $cfg = $this->opsi->get_product_properties($name);
288           $str = management::editEntry('editEntry',array($name),array(),'tabs_opsiProdConfig','OPSIPRODCONFIG','opsi');
289           if($str) return($str);
290           if(isset($this->tabObject->by_object['opsiProperties'])){
291             $this->tabObject->by_object['opsiProperties']->set_cfg($cfg);
292             $this->tabObject->by_object['opsiProperties']->set_product($name);
293             $this->skipFooter = TRUE;
294           }else{
295             trigger_error("Unknown tab, please check config.");
296           }
298         }else{
300           // Edit FAI objects here 
301           if(count($entry['GROUPS']) == 1){
302             $data = array_pop($entry['GROUPS']);
303             $type = $this->get_type($data);
304             $str = management::editEntry('editEntry',array($data['dn']),array(),$type[0],$type[2],$type[1]);
305             if($str) return($str);
306             $this->tabObject->by_object[$type[1]]->FAIstate = $data['FAIstate'];
307             $this->tabObject->read_only = preg_match("/freeze/i", $data['FAIstate']);
309           }else{
310             $this->dialogObject = new faiGroupHandle($entry['GROUPS'],"edit");
311           }
312         }
313       }
314     }
315   }
318   /*! \brief   Save changes made in opsi dialogs.
319    */
320   function saveOpsiProperties()
321   {
322     if($this->tabObject instanceof tabs_opsiProdConfig && isset($_POST['save_properties'])){
323       $this->tabObject->save_object();
324       $op    = $this->tabObject->by_object['opsiProperties'];
325       $name  = $op->get_product();
326       $cfg   = $op->get_cfg();
327       $this->opsi->set_product_properties($name,$cfg);
328       if($this->opsi->is_error()){
329         msg_dialog::display(_("Error"),msgPool::siError($this->opsi->get_error()),ERROR_DIALOG);
330       }else{
331         $this->remove_lock();
332         $this->closeDialogs();
333       }
334     }
335   }
338   /*! \brief   Someone wants to remove some object(s)
339    *            ask for a confirmation now.
340    */
341   function removeEntryRequested($action="",$target=array(),$all=array(), $altTabClass ="", $altTabType = "", $altAclCategory="")
342   {
343     $this->closeDialogs();
344     if($action == "remove_multiple"){
346       // Collect objects to delete
347       $headpage = $this->getHeadpage();
348       $to_delete = array();
349       foreach($target as $id){
350         $object = $headpage->getEntry($id);
351         if(in_array("FAKE_OC_FAI", $object['objectClass'])){
352           foreach($object['GROUPS']  as $entry){
353             array_push($to_delete, $entry);
354           }
355         }
356       }
357       return($this->removeFAIObjects($to_delete));
358     }else{
360       // Try to remove a single object, only FAI objects can be removed!
361       $headpage = $this->getHeadpage();
362       if(count($target) == 1){
363         $entry = $headpage->getEntry($target[0]);
364         if($entry && in_array("FAKE_OC_FAI",$entry['objectClass'])){
365           $this->dialogObject = new faiGroupHandle($entry['GROUPS'],"remove");
366         }
367       }
368     }
369   }
372   /*! \brief   Someone wants to remove some object(s)
373    *            ask for a confirmation now.
374    */
375   function removeFAIObjects($to_delete)
376   {
377     // Do not allow to remove objects with state freeezed
378     $errors = $disallowed = array();
379   
380     foreach($to_delete as $obj){
381       $type = $this->get_type($obj);
382       $acl  = $this->ui->get_permissions($obj['dn'],"fai/".$type[1]);
383       if(!preg_match("/d/",$acl)){
384         $disallowed[] = $obj['dn'];
385       }elseif(isset($obj['FAIstate']) && preg_match('/^freeze/', $obj['FAIstate'])){
386         $errors[] = $obj['dn'];
387       }else{
388         $this->dns[] = $obj['dn'];
389       }
390     }
391     if(count($errors)){
392       msg_dialog::display(_("Branch locked"),
393           sprintf(_("The following entries are locked, you can't remove them %s."),msgPool::buildList($errors)),INFO_DIALOG);
394     }
395     if(count($disallowed)){ 
396       msg_dialog::display(_("Permission error"), msgPool::permDelete($disallowed), ERROR_DIALOG);
397     }
399     // Check entry locking
400     if(count($this->dns)){
401       if ($user= get_multiple_locks($this->dns)){
402         return(gen_locked_message($user,$this->dns));
403       }
404       if(count($this->dns)){
405         $smarty = get_smarty();
406         $dns_names = array();
407         foreach($this->dns as $dn){
408           add_lock ($dn, $this->ui->dn);
409           $dns_names[] = LDAP::fix($dn);
410         }
411         $smarty->assign("info",msgPool::deleteInfo($dns_names,_("FAI object")));
412         $smarty->assign("multiple", true);
413         return($smarty->fetch(get_template_path('remove.tpl', TRUE)));
414       }
415     }
416   }
419   /*! \brief   Entry removal is confirmed, now remove objects
420    */
421   function removeEntryConfirmed($action="",$target=array(),$all=array(),
422       $altTabClass="",$altTabType="",$altAclCategory="")
423   {
424     $ldap = $this->config->get_ldap_link();
425     $ldap->cd($this->config->current['BASE']); 
427     $disallowed = array();
428     foreach($this->dns as $key => $dn){
429       $ldap->cat($dn);
430       if($ldap->count()){
431         $attrs = $ldap->fetch();
432         $type= $this->get_type($attrs);
434         $acl  = $this->ui->get_permissions($dn,"fai/".$type[1]);
435         if(preg_match("/d/",$acl)){
437           // Now save changes
438           $str = management::removeEntryConfirmed($action,array($dn),$all,$type[0],$type[2],$type[1]);
439           if(!empty($str)) return($str);
440           FAI::save_release_changes_now();
441           $to_del = FAI::clean_up_releases($dn);
442           foreach($to_del as $dn){
443             $ldap->rmdir_recursive($dn);
444           }
446         } else {
447           $disallowed[] = $dn;
448           new log("security","fai/".get_class($this),$dn,array(),"Tried to trick deletion.");
449         }
450       }
451     }
453     /* Normally this shouldn't be reached, send some extra
454        logs to notify the administrator */
455     if(count($disallowed)){ 
456       msg_dialog::display(_("Permission error"), msgPool::permDelete($disallowed), ERROR_DIALOG);
457     }
458   }
461   /*! \brief   Someone clicked on edit/remove for a grouped FAI object.
462    *           We are now going to display a dialog to let the user select the entry 
463    *            he wants to perform the action on.
464    */
465   function editByGroup()
466   {
467     if($this->dialogObject instanceOf faiGroupHandle && $this->dialogObject->get_mode() == "edit"){
468       $this->dialogObject->save_object();
469       $entry = $this->dialogObject->get_selected();
470       $this->closeDialogs();
471       $data = array_pop($entry);
472       $type = $this->get_type($data);
473       $str = management::editEntry('editEntry',array($data['dn']),array(),$type[0],$type[2],$type[1]);
474       if($str) return($str);
475       $this->tabObject->by_object[$type[1]]->FAIstate = $data['FAIstate'];
476       $this->tabObject->read_only = preg_match("/freeze/i", $data['FAIstate']);
477     }elseif($this->dialogObject instanceOf faiGroupHandle && $this->dialogObject->get_mode() == "remove"){
478       $this->dialogObject->save_object();
479       $to_delete = $entry = $this->dialogObject->get_selected();
480       if(count($to_delete)) $this->closeDialogs();
481       return($this->removeFAIObjects($to_delete));
482     }elseif($this->dialogObject instanceOf faiGroupHandle && $this->dialogObject->get_mode() == "copy"){
483       $this->dialogObject->save_object();
484       $entries = $entry = $this->dialogObject->get_selected();
485       if(count($entries)){
486         foreach($entries as $entry){
487           $type = $this->get_type($entry);
488           $this->cpHandler->add_to_queue($entry['dn'],"copy",$type[0],$type[2],'fai',$this);
489           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,$entry['dn'],"Entry copied!");
490         }
491         $this->closeDialogs();
492       }
493     }
494   }
497   /*! \brief   Save dialog/object modifications
498    */
499   protected function saveChanges()
500   {
501     $str = management::saveChanges();
502     if($str) return($str);
504     // Now save changes
505     FAI::save_release_changes_now();
506     $to_del = FAI::clean_up_releases($this->last_dn);
507     foreach($to_del as $dn){
508       $ldap->rmdir_recursive($dn);
509     }
510   }
513   /*! \brief   Save dialog/object modifications but keep the dialogs opened
514    */
515   protected function applyChanges()
516   {
517     $str = management::applyChanges();
518     if($str) return($str);
520     // Now save changes
521     FAI::save_release_changes_now();
522     $to_del = FAI::clean_up_releases($this->last_dn);
523     foreach($to_del as $dn){
524       $ldap->rmdir_recursive($dn);
525     }
526   }
529   /*! \brief   Initiates release removal
530    */
531   function removeBranch()
532   {
533     /* Check if we have a post remove method configured
534      *  else skip this operation. (Skip:Button in the ui should be disabled in this case too)
535      */
536     if("" != $this->config->search("faiManagement", "POSTREMOVE",array('menu','tabs'))){
537       /* Load permissions for selected 'dn' and check if
538          we're allowed to remove this 'dn' */
539       if(preg_match("/d/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
540         $smarty=get_smarty();
541         $smarty->assign("release_hidden",base64_encode($this->fai_release));
542         $smarty->assign("info", msgPool::deleteInfo(LDAP::fix($this->fai_release),_("FAI branch/freeze")));
543         return($smarty->fetch(get_template_path('remove_branch.tpl',TRUE)));
544       } else {
545         msg_dialog::display(_("Permission error"), _("You have no permission to delete this release!"), ERROR_DIALOG);
546       }
547     }
548   }
551   /*! \brief   Remove a release after removal was confirmed
552    */
553   function removeBranchConfirmed()
554   {
555     /* Check if we have a post remove method configured
556      *  else skip this operation. (Skip:Button in the ui should be disabled in this case too)
557      */
558     if("" != $this->config->search("faiManagement", "POSTREMOVE",array('menu','tabs'))){
560       if(!isset($_POST['release_hidden']) || base64_decode($_POST['release_hidden']) != $this->fai_release){
561         msg_dialog::display(_("Warning"),_("Release remove aborted because the release name check failed!"));
562       }else{
564         $bb =  $this->fai_release;
565         $ldap = $this->config->get_ldap_link();
567         $br = $this->getBranches();
569         if(isset($br[$bb]) && preg_match("/d/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
570           $name = $br[$bb];
572           $ldap->cd($bb);
573           $ldap->recursive_remove();
574           $ldap->cd(preg_replace('/,'.preg_quote(get_ou('faiBaseRDN'), '/').'/i', ','.get_ou('applicationRDN'), $bb));
575           $ldap->recursive_remove();
576           $ldap->cd(preg_replace('/,'.preg_quote(get_ou('faiBaseRDN'), '/').'/i', ','.get_ou('mimetypeRDN'), $bb));
577           $ldap->recursive_remove();
579           /* Search for all groups with configured application menus.
580              - First search all groups, to ensure that we only remove entries form whithin groups.
581              - The search für menu configuration for the specified release and collect all those dns.
582              - Remove entries
583            */
584           $release_ou = preg_replace("/".preg_quote(get_ou("faiBaseRDN"), '/').".*$/i","",$bb);
585           $ldap->cd($this->config->current['BASE']);
586           $ldap->search("(objectClass=posixGroup)",array("dn"));
588           /* Collect all group dns
589            */
590           $groups = array();
591           while($attrs = $ldap->fetch()){
592             $groups[] = $attrs['dn'];
593           }
596           /* Collect all group menu release dns that match the release we have removed
597            */
598           $dns = array();
599           foreach($groups as $dn){
600             $ldap->cd($dn);
601             $ldap->search("(objectClass=FAIbranch)",array("dn"));
602             while($attrs = $ldap->fetch()){
603               if(preg_match("/^".preg_quote($release_ou, '/')."/",$attrs['dn'])){
604                 $dns[] = $attrs['dn'];
605               }
606             }
607           }
609           /* Finally remove collected release dns
610            */
611           foreach($dns as $dn){
612             $ldap->cd($dn);
613             $ldap->recursive_remove();
614           }
616           /* Post remove */
617           $this->fai_release = $this->fai_base;
618           $this->lock_name   = $name;
619           $this->lock_dn     = $bb;
620           $this->postremove();
622           $fai_filter = session::get("fai_filter");
623           $fai_filter['fai_release'] = $this->fai_release;
624           session::set("fai_filter",$fai_filter);
626           new log("remove","fai/".get_class($this),$br[$bb],array(),"Release removed");
627         }
628       }
629     }
630   }
633   /*! \brief   Initiates release creation 
634    */
635   function createBranch()
636   { 
637     if($this->config->search("faiManagement", "POSTCREATE",array('menu','tabs')) == ""){ 
638       msg_dialog::display(_("Configuration"), msgPool::cmdnotfound("POSTCREATE", get_class()), ERROR_DIALOG);
639     }elseif(!preg_match("/c/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
640       msg_dialog::display(_("Permission error"), msgPool::permCreate(_("Branch")), ERROR_DIALOG);
641     }else{
642       $smarty = get_smarty();
643       $this->dispNewBranch=true;
644       $this->dispNewFreeze=false;
645       $smarty->assign("iframe",false);
646       if(isset($_POST['BranchName'])){
647         $smarty->assign("BranchName", $_POST['BranchName']);
648       }else{
649         $smarty->assign("BranchName","");
650       }
651       return($smarty->fetch(get_template_path('faiNewBranch.tpl', TRUE, dirname(__FILE__))));
652     }
653   }
656   /*! \brief   Initiates release creation 
657    */
658   function createFreeze()
659   {
660     if($this->config->search("faiManagement", "POSTCREATE",array('menu','tabs')) == ""){ 
661       msg_dialog::display(_("Configuration"), msgPool::cmdnotfound("POSTCREATE", get_class()), ERROR_DIALOG);
662     }elseif(!preg_match("/c/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
663       msg_dialog::display(_("Permission error"), msgPool::permCreate(_("Branch")), ERROR_DIALOG);
664     }else{
665       $smarty = get_smarty();
666       $this->dispNewFreeze=true;
667       $this->dispNewBranch=false;
668       $smarty->assign("iframe",false);
669       if(isset($_POST['BranchName'])){
670         $smarty->assign("BranchName", $_POST['BranchName']);
671       }else{
672         $smarty->assign("BranchName","");
673       }
674       return($smarty->fetch(get_template_path('faiNewBranch.tpl', TRUE, dirname(__FILE__))));
675     }
676   }
679   /*! \brief   Creates a new branch
680    */
681   function PerformBranch()
682   {
683     if(!preg_match("/c/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
684       msg_dialog::display(_("Permission error"), msgPool::permCreate(_("Branch")), ERROR_DIALOG);
685     }else{
687       /* In order to see error messages we have to reset the error handler.
688          Due to the exit();
689        */
690       restore_error_handler();
692       $this->dispNewBranch = false;
693       $this->dispNewFreeze = false;
695       $LASTPOST = session::get('LASTPOST');
696       $base = $LASTPOST['base'];
697       $_POST  = session::get('LASTPOST');
698       $name = $_POST['BranchName'];
700       $type = $LASTPOST['type'];
701       $ldap = $this->config->get_ldap_link();
703       $baseToUse = $base;
704       if($this->fai_release !=  $this->fai_base){
705         $baseToUse = $this->fai_release;
706       }
708       /* Create new Release name to be able to set faidebianRelease for FAIpackageList */
710       $CurrentReleases  = $this->getBranches();
711       $NewReleaseName   = $name;
712       if(isset($CurrentReleases[$this->fai_release])) {
713         if($this->fai_release != $this->fai_base){
714           $NewReleaseName = $CurrentReleases[$this->fai_release]."/".$name;
715           $NewReleaseName = preg_replace("#\/#","/",$NewReleaseName);
716         }else{
717           $NewReleaseName   = $name;
718         }
719       }
720       $appsrc = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('applicationRDN'),$baseToUse);
721       $appdst = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('applicationRDN'),"ou=".$name.",".$baseToUse) ;
723       $mimesrc = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('mimetypeRDN'),$baseToUse);
724       $mimedst = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('mimetypeRDN'),"ou=".$name.",".$baseToUse) ;
726       /* Check if source depeartments exist */
727       foreach(array($baseToUse,$appsrc,$mimesrc) as $dep){
728         $ldap->cd($this->config->current['BASE']);
729         $ldap->cat($dep);
730         if(!$ldap->count()){
731           $ldap->create_missing_trees($dep);
732         }
733       }
735       /* Print header to have styles included */
736       echo '  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
737         <html>
738         <head>
739         <title></title>
740         <style type="text/css">@import url("themes/default/style.css");</style>
741         <script language="javascript" src="include/focus.js" type="text/javascript"></script>
742         </head>
743         <body style="background: none;margin:3px;color:black">
744         ';
746       new log("create","fai/".get_class($this),$NewReleaseName,array(),"New $type created");
748       /* Duplicate group application releases
749        */
750       FAI::copy_FAI_group_releases($CurrentReleases[$this->fai_release],$name,$type);
752       /* Duplicate applications
753        */
754       $ldap->cat($appsrc,array("dn")) ;
755       if($ldap->count()){
756         $ldap->cd ($appdst);
757         $ldap->recursive_remove();
758         FAI::copy_FAI_resource_recursive($appsrc,$appdst,$NewReleaseName,$type,true);
759       }
761       /* Duplicate mime types
762        */
763       $ldap->cat($mimesrc,array("dn")) ;
764       if($ldap->count()){
765         $ldap->cd ($mimedst);
766         $ldap->recursive_remove();
767         FAI::copy_FAI_resource_recursive($mimesrc,$mimedst,$NewReleaseName,$type,true);
768       }
770       $attr = array();
771       $attr['objectClass'] = array("organizationalUnit","FAIbranch");
772       $attr['ou']       = $name;
773       $attr['FAIstate'] = $type;
774       $ldap->cd($this->config->current['BASE']);
775       $ldap->cd("ou=".$name.",".$baseToUse);
776       $ldap->cat("ou=".$name.",".$baseToUse);
777       if($ldap->count()){
778         $ldap->modify($attr);
779       }else{
780         $ldap->add($attr);
781       }
783       /* Duplicate fai objects
784        */
785       //      $ldap->cd ("ou=".$name.",".$baseToUse);
786       //      $ldap->recursive_remove();
787       //      FAI::copy_FAI_resource_recursive($baseToUse,"ou=".$name.",".$baseToUse,$NewReleaseName,$type,true);
789       echo "<div style='width:100%;text-align:right;'><form name='form' method='post' action='?plug=".$_GET['plug']."' target='_parent'>
790         <br><input type='submit' name='CloseIFrame' value='"._("Continue")."'>
791         <input type='hidden' name='php_c_check' value='1'>
792         </form></div>";
794       echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
796       /* Print footer to have valid html */
797       echo "</body></html>";
799       $this->dispNewFreeze = false;
801       /* Postcreate */
803       /* Assign possible attributes */
804       $this->lock_type  = $type;
805       $this->lock_name  = $name;
806       $this->lock_dn    = $baseToUse;
807       $this->postcreate();
809       /* Send daemon event to reload the fai release database
810        */
811       if(class_available("DaemonEvent") && class_available("gosaSupportDaemon")){
812         $events = DaemonEvent::get_event_types(SYSTEM_EVENT | HIDDEN_EVENT);
813         if(isset($events['TRIGGERED']['DaemonEvent_recreate_fai_release_db'])){
814           $evt = $events['TRIGGERED']['DaemonEvent_recreate_fai_release_db'];
815           $tmp = new $evt['CLASS_NAME']($this->config);
816           $tmp->set_type(TRIGGERED_EVENT);
817           $tmp->add_targets(array("GOSA"));
818           $o_queue = new gosaSupportDaemon();
819           if(!$o_queue->append($tmp)){
820             msg_dialog::display(_("Service infrastructure"),msgPool::siError($o_queue->get_error()),ERROR_DIALOG);
821           }
822         }
823       }else{
824         trigger_error("Unknown class DaemonEvent / gosaSupportDaemon");
825         msg_dialog::display(_("Fatal error"),
826             "Daemon events called but classes where not accessible, DaemonEvent gosaSupportDaemon",
827             FATAL_ERROR_DIALOG);
828       }
829       exit();
830     }
831   }
834   /*! \brief   Creates a new branch, after a useable name was specified.
835    */
836   function saveBranch()
837   {
838     if($this->dispNewBranch){
839       $type = "branch";
840     }else{
841       $type = "freeze";
842     }
844     /* Check branch name */
845     $name = $_POST['BranchName'];
846     $is_ok = true;
847     $smarty = get_smarty();
848     $smarty->assign("BranchName",$name);
849     $base= $this->fai_base;
851     /* Check used characters */
852     if(!preg_match("/^[0-9a-z\.]*$/",$name)){
853       msg_dialog::display(_("Error"), msgPool::invalid(_("Name"),$name,"/[0-9a-z\.]/"), ERROR_DIALOG);
854       $is_ok = false;
855     }
857     // Check if this name is already in use 
858     if(!$this->CheckNewBranchName($_POST['BranchName'],$this->fai_release)){
859       msg_dialog::display(_("Error"), msgPool::duplicated(_("Name")), ERROR_DIALOG);
860       $is_ok = false;
861     }
863     // Handle errors
864     if(!$is_ok && $this->dispNewFreeze){
865       return($this->createFreeze());
866     }elseif(!$is_ok && $this->dispNewBranch){
867       return($this->createBranch());
868     }
870     // Now create new release
872     if(session::is_set('LASTPOST')){
873       $LASTPOST = session::get('LASTPOST');
874     }else{
875       $LASTPOST = array();
876     }
877     $LASTPOST['base'] = $base;
878     $LASTPOST['type'] = $type;
879     $LASTPOST['BranchName'] = $name;
880     session::set('LASTPOST',$LASTPOST);
881     $smarty->assign("iframe", true);
882     $smarty->assign("plugID", $_GET['plug']);
883     $display  = $smarty->fetch(get_template_path('faiNewBranch.tpl', TRUE, dirname(__FILE__)));
884     return($display);
886   }
890   /*! \brief   Returns a list of all releases for useable for drop down boxes.
891    *                      ou=fai... /
892    *              ou=siga,ou=fai... &nbsp; siga
893    *         ou=1,ou=siga,ou=fai... &nbsp;&nbsp; 1
894    */
895   function getReleaseList($base = "", $prefix ="")
896   {
897     $list = array();
898     if(empty($base)){
899       $base = $this->fai_base;
900       $list[$base] = "/";
901     }
903     $ldap = $this->config->get_ldap_link();
904     $ldap->ls("(objectClass=FAIbranch)",$base,array("ou","FAIstate"));
906     while($release = $ldap->fetch()){
907       $list[$release['dn']] = $prefix.$release['ou'][0];
908       $list = array_merge($list,$this->getReleaseList($release['dn'],$prefix."&nbsp; "));
909     }
910     return($list);
911   }
914   /*! \brief   Returns a list of all releases with full release names
915    *                      ou=fai... /
916    *              ou=siga,ou=fai... siga
917    *         ou=1,ou=siga,ou=fai... siga/1
918    */
919   function getBranches($base = false,$prefix = "")
920   {
921     $ret = array("/"=>$this->fai_base);
922     $ldap = $this->config->get_ldap_link();
923     if(!$base){
924       $base = $this->fai_base;
925     }
926     $tmp = FAI::get_all_releases_from_base($base,true);
927     foreach($tmp as $dn => $name){
928       $ret[$name]=$dn;
929     }
930     ksort($ret);
931     $ret = array_flip($ret);
933     return ($ret);
934   }
937   /*! \brief   Detects object info like corresponding  tab,class,acl 
938    *    e.g.    [0]   =  tabsPartition
939    *            [1]   =  faiPartitionTable
940    *            [2]   =  FAIPARTITIONTABS
941    */
942   function get_type($array)
943   {
944     if(!isset($array['objectClass'])) return(array());
945     if(in_array("FAIpartitionTable",$array['objectClass'])){
946       return(array("tabsPartition","faiPartitionTable","FAIPARTITIONTABS"));
947     }
948     if(in_array("FAIscript",$array['objectClass'])){
949       return(array("tabsScript","faiScript","FAISCRIPTTABS"));
950     }
951     if(in_array("FAItemplate",$array['objectClass'])){
952       return(array("tabsTemplate","faiTemplate","FAITEMPLATETABS"));
953     }
954     if(in_array("FAIhook",$array['objectClass'])){
955       return(array("tabsHook","faiHook","FAIHOOKTABS"));
956     }
957     if(in_array("FAIvariable",$array['objectClass'])){
958       return(array("tabsVariable","faiVariable","FAIVARIABLETABS"));
959     }
960     if(in_array("FAIprofile",$array['objectClass'])){
961       return(array("tabsProfile","faiProfile","FAIPROFILETABS"));
962     }
963     if(in_array("FAIpackageList",$array['objectClass'])){
964       return(array("tabsPackage","faiPackage","FAIPACKAGETABS"));
965     }
966     return(array());
967   }
970   /*! \brief   Checks if the given string can be used as class name
971    */
972   static function check_class_name($oc,$name,$dn)
973   {
974     $base = FAI::get_release_dn($dn);
976     if($oc == "FAIprofile"){
977       $f = "";
978       $ocs = array("FAIprofile","FAItemplate","FAIhook","FAIpartitionTable","FAIpackageList","FAIscript","FAIvariable");
979       foreach($ocs as $oc){
980         $f .= "(objectClass=".$oc.")";
981       }
982       $res  = FAI::get_all_objects_for_given_base($base,"(|".$f.")",TRUE);
983     }else{
984       $res  = FAI::get_all_objects_for_given_base($base,"(objectClass=".$oc.")",TRUE);
985     }
986     $delete = array();
987     $used   = array();
988     foreach($res as $object){
989       $used[$object['cn'][0]]= $object['cn'][0];
990     }
991     return($used);
992   }
995   /*! \brief   Checks if the given string can be used for a new release
996    */
997   function CheckNewBranchName($name,$base)
998   {
999     $f = $this->fai_release;
1000     if($name == ""){
1001       return(false);
1002     }elseif(in_array($name,$this->getBranches($f))) {
1003       return(false);
1004     }elseif(tests::is_department_name_reserved($name,$base)){
1005       return(false);
1006     }
1007     return(true);
1008   }
1011   /*! \brief   This filter is used to display small icons for each listed object 
1012    *            instead of their typ names
1013    */
1014   static function filterProperties($row, $classes)
1015   {
1016     $objects = array(
1017         "FAIpartitionTable"  => array("IMG"=> "plugins/fai/images/fai_partitionTable.png",
1018           "NAME"=>_("Partition table"),"KZL"=> "PT", "VAR"=>"ShowPartitions"),
1019         "FAIpackageList"     => array("IMG"=> "plugins/fai/images/fai_packages.png",
1020           "NAME"=>_("Package list") ,  "KZL"=> "PL", "VAR"=>"ShowPackages"),
1021         "FAIscript"          => array("IMG"=> "plugins/fai/images/fai_script.png",
1022           "NAME"=>_("Scripts") ,       "KZL"=> "S",  "VAR"=>"ShowScripts"),
1023         "FAIvariable"        => array("IMG"=> "plugins/fai/images/fai_variable.png",
1024           "NAME"=>_("Variables") ,     "KZL"=> "V",  "VAR"=>"ShowVariables"),
1025         "FAIhook"            => array("IMG"=> "plugins/fai/images/fai_hook.png",
1026           "NAME"=>_("Hooks"),          "KZL"=> "H",  "VAR"=>"ShowHooks"),
1027         "FAIprofile"         => array("IMG"=> "plugins/fai/images/fai_profile.png",
1028           "NAME"=>_("Profile") ,       "KZL"=> "P",  "VAR"=>"ShowProfiles"),
1029         "FAItemplate"        => array("IMG"=> "plugins/fai/images/fai_template.png",
1030           "NAME"=>_("Templates") ,     "KZL"=> "T",  "VAR"=>"ShowTemplates"),
1031         "opsi_netboot"       => array("IMG"=> "plugins/opsi/images/netboot_package.png",
1032           "NAME"=>_("OPSI netboot product") ,     "KZL"=> "ON",  "VAR"=>"ShowOpsiNetboot"),
1033         "opsi_local"         => array("IMG"=> "plugins/opsi/images/local_package.png",
1034           "NAME"=>_("OPSI localboot product")   ,     "KZL"=> "OL",  "VAR"=>"ShowOpsiLocal"));
1036     $icon_list = "";
1037     foreach($objects as $type => $type_data){
1038       if(in_array($type, $classes)){
1039         $icon_list .= "<input type='image' src='".$type_data['IMG']."' title='".$type_data['NAME']."'
1040           alt='".$type_data['KZL']."' class='center' name='edit_".$row."_".$type."'>\n";
1041       }else{
1042         $icon_list .= "<img src='images/empty.png' alt=' ' class='center'>\n";
1043       }
1044     }
1046     return $icon_list;
1047   }
1050   /*! \brief   Overridden render method of class mangement. 
1051    *            this allows us to add a release selection box.
1052    */
1053   function renderList()
1054   {
1055     $filter = $this->getFilter();
1056     $headpage = $this->getHeadpage();
1057     $filter->setComboBoxOptions("RELEASE",$this->getReleaseList());
1059     if(isset($_POST['RELEASE'])){
1060       $this->fai_release = get_post('RELEASE');
1061     }
1062     $headpage->setBase($this->fai_release);
1063     $headpage->update();
1064     $smarty = get_smarty();
1065     $smarty->assign("fai_release", $this->fai_release);
1066     $smarty->assign("opsi_available", (is_object($this->opsi) && $this->opsi->enabled()));
1067     $smarty->assign("fai_base", $this->fai_base);
1068     $r = $this->config->search("faiManagement", "POSTREMOVE",array('menu','tabs'));
1069     $c = $this->config->search("faiManagement", "POSTCREATE",array('menu','tabs'));
1070     $smarty->assign("allow_create", $c);
1071     $smarty->assign("allow_remove", $r);
1072     $display = $headpage->render();
1073     return($this->getHeader().$display);
1074   }
1077   /*! \brief   Convert POST and GET variables into actions.
1078    */
1079   function detectPostActions()
1080   {
1081     $action = management::detectPostActions();
1082     if(isset($_POST['remove_multiple'])) $action['action'] = "remove";
1083     if(isset($_POST['new_profile'])) $action['action'] = "new_profile";
1084     if(isset($_POST['new_template'])) $action['action'] = "new_template";
1085     if(isset($_POST['new_script'])) $action['action'] = "new_script";
1086     if(isset($_POST['new_hook'])) $action['action'] = "new_hook";
1087     if(isset($_POST['new_variable'])) $action['action'] = "new_variable";
1088     if(isset($_POST['new_package'])) $action['action'] = "new_package";
1089     if(isset($_POST['new_partition'])) $action['action'] = "new_partition";
1091     if(isset($_POST['save_properties'])) $action['action'] = "saveOpsiProperties";
1092     if(isset($_POST['cancel_properties'])) $action['action'] = "cancel";
1094     if(isset($_POST['edit_continue'])) $action['action'] = "newClassNameSelected";
1095     if(isset($_POST['edit_cancel'])) $action['action'] = "cancel";
1097     if(isset($_POST['faiGroupHandle_cancel'])) $action['action'] = "cancel";
1098     if(isset($_POST['CancelBranchName'])) $action['action'] = "cancel";
1099     if(isset($_POST['delete_branch_confirm'])) $action['action'] = "removeBranchConfirmed";
1100     if(isset($_GET['PerformBranch'])) $action['action'] = "PerformBranch";
1101     if(isset($_POST['UseBranchName'])) $action['action'] = "saveBranch";
1102     if(isset($_POST['faiGroupHandle_apply']))  $action['action'] = "editByGroup";
1103     if(isset($_GET['act']) && $_GET['act'] == "branch_branch")  $action['action'] = "createBranch";
1104     if(isset($_GET['act']) && $_GET['act'] == "freeze_branch")  $action['action'] = "createFreeze";
1105     if(isset($_GET['act']) && $_GET['act'] == "remove_branch")  $action['action'] = "removeBranch";
1107     foreach($_POST as $name => $value){
1108       if(preg_match("/^edit_([0-9]*)_([a-z_]*)_(x|y)/i", $name)){
1109         $id = preg_replace("/^edit_([0-9]*)_([a-z_]*)_(x|y)/i","\\1", $name);
1110         $tab = preg_replace("/^edit_([0-9]*)_([a-z_]*)_(x|y)/i","\\2", $name);
1112         $headpage = $this->getHeadpage();
1113         $entry = $headpage->entries[$id];
1115         if(in_array('FAKE_OC_FAI', $entry['objectClass'])){
1116           if(isset($headpage->entries[$id]['GROUPS'][$tab])){
1117             $data =$headpage->entries[$id]['GROUPS'][$tab];
1118             $type = $this->get_type($data);
1119             $str = management::editEntry('editEntry',array($data['dn']),array(),$type[0],$type[2],$type[1]); 
1120             if($str) return($str);
1121           } 
1122         }else{
1123           $str = $this->editEntry('editEntry',array($entry['dn'])); 
1124           if($str) return($str);
1125         }
1126         break;
1127       }
1128     }
1129     return($action);
1130   }
1133   static function plInfo()
1134   {
1135     return (array(
1136           "plShortName"   => _("FAI releases"),
1137           "plDescription" => _("FAI release management"),
1138           "plSelfModify"  => FALSE,
1139           "plDepends"     => array(),
1140           "plPriority"    => 0,
1141           "plSection"     => array("administration"),
1142           "plCategory"    => array("fai"=> array("description" => _("FAI"),
1143               "objectClass" => "FAIclass")),
1144           "plProvidedAcls"=> array()));
1145   }
1146
1147 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1148 ?>